DennyDotNet

Awesome ASP.NET C# and other cool coding stuff

About the author

Denny Ferrassoli
Developer at Casting Networks. MCP / .NET
E-mail me Send mail
Add to Technorati Favorites

Recent posts

Recent comments

Authors

Categories

None


Disclaimer

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

© Copyright 2010

ASP.NET AJAX History and ASP.NET Hacks

I was running through my list of blogs and I ran into "Create a Facebook-like Ajax Image Gallery!" by John Katsiotis. In John's post he shows how to create an image gallery - it's quick and easy - but more importantly he utilizes the new ASP.NET AJAX History feature. That means you can use the back and forward buttons on your browser to go back and forward through the AJAX calls.

And on another note, LessThanDot has published a collection of ASP.NET Hacks in 18 categories (currently) including: Caching, Email, Encryption, Validation, Files and others.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags: ,
Posted by Denny on Monday, July 07, 2008 3:52 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Passing a JSON object to a WCF service with jQuery

[Updated: 04/25/08] 

This example uses WCF to create a service endpoint that will be accessible via an ASP.NET page with jQuery/AJAX. We will use AJAX to pass a JSON object from the client-side to the webservice. We will only use jQuery to connect to the web service, there will be no ASP.NET AJAX library used. Why no ASP.NET AJAX library? jQuery is already included in the project and it can handle all the necessary AJAX calls and functionality that we would want if we were using the ASP.NET AJAX script library. We're also going to save  about 80kb of overhead (much more if in debug mode) by excluding the ASP.NET AJAX library. This is in no way saying that the ASP.NET AJAX library isn't useful... As a matter of fact if we were to do the same example with the library we could save ourselves from writing extra code. However the point of this example is to show that we can access the web service even if we don't have a nicely generated client-side proxy a la ASP.NET AJAX.

The WCF Service:

I'm going to start by adding an AJAX-enabled WCF Service to a Website. (Make sure you're running the correct version of .NET - I am using 3.5 here)

After adding the service it opens up to the service's code-behind file. Go ahead and browse around the file for a second.

The first thing I'm going to point out is to make sure that the "AspNetCompatibilityRequirements" is set to "Allowed":


[AspNetCompatibilityRequirements( RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed )]

This attribute indicates that our service should run in ASP.NET compatibility mode. If it were not "Allowed" we would not be able to access the service from ASP.NET. This attribute is automatically generated when you add the "AJAX-enabled WCF Service." For a detailed explanation of the attribute go to MSDN.

Looking at the generated code-behind file we can see it has placed a "DoWork()" method with the "OperationContract" attribute. This is created by default but lets keep it since we will be using this method to run this example. One thing we want to add is a "WebGet" attribute and set the "RequestFormat" to "Json." WebGet associates the operation with a UriTemplate (not discussed in this example) as well as the GET verb. Setting the RequestFormat allows us to define that the Request should be in JSON format. For the sake of this example I will be using the GET method to post data to the web service, however it is recommended to use POST for data like this. Our "DoWork()" method should now look like this:


[OperationContract]
[WebGet( RequestFormat=WebMessageFormat.Json )]
public void DoWork()
{
 // Add your operation implementation here
 return;
}



The Data/Object Structure:

We want to pass in a "Person" object to the "DoWork()" method so lets quickly create a Person object with properties for a Name, Age and the types of Shoes they own (first thing that popped into my head). This class will also serve as the structure for our JSON object.


[Serializable]
[DataContract( Namespace = "http://www.dennydotnet.com/", Name = "Person" )]
public class Person
{
 private string _name = string.Empty;
 private int _age = 0;

 [DataMember( IsRequired = true, Name = "Name" )]
 public string Name
 {
  get { return _name; }
  set { _name = value; }
 }

 [DataMember( IsRequired = true, Name = "Age" )]
 public int Age
 {
  get { return _age; }
  set { _age = value; }
 }

 [DataMember( IsRequired = true, Name = "Shoes" )]
 public List<String> Shoes;

}

We've decorated our Person class as a DataContract specifying the Namespace and Name. We've also decorated our properties with a DataMember attribute. We've set "IsRequired" for each one to true and specified the Name. You really only need to specify the "Name" if it's going to be different than the property name. For example you could have a property named "Level" and the DataMember attribute's Name set to "Rank." We can now go back and modify our "DoWork()" method to receive a Person object as a param. It should now look like the following:


[OperationContract]
[WebGet( RequestFormat=WebMessageFormat.Json )]
public void DoWork(Person p)
{
 // Add your operation implementation here
 return;
}

The Web.Config File:

You'll need to make a few changes to your web.config file before you can access your service. You'll need to add a serviceBehavior to allow httpGet and we'll also add some helpful debugging options too. Add the following to your web.config:

Below </endpointBehaviors>


<serviceBehaviors>
 <behavior name="ServiceAspNetAjaxBehavior">
  <serviceMetadata httpGetEnabled="true" httpGetUrl="" />
  <serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true" />
 </behavior>
</serviceBehaviors>


Between <services>[here]</services> your service node should look like this:

<service name="Service" behaviorConfiguration="ServiceAspNetAjaxBehavior">
 <endpoint address="" behaviorConfiguration="ServiceAspNetAjaxBehavior"
  binding="webHttpBinding" contract="Service" />
 <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>

A security note about the following line:


<serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true" />


Allowing exception details can expose internal application information including personally identifiable or otherwise sensitive information. Setting the option to true is only recommended as a way to temporarily debug your service!!

Your Web.Config should look like the following: (pardon the colors)

The Front-End:

Now that the service is created and configured we can move to the front-end (make sure jQuery.js is included in your ASP.NET page). First let's create a sample JSON object that we will pass to the service. We'll create the JSON object based on the structure of the Person class.


var mydata = { "Name":"Denny", "Age":23, "Shoes":["Nike","Osiris","Etnies"] };


If you're not too familiar with JSON this is what our JSON object looks like as an object (JsonViewer):

We need to somehow communicate with the WCF service and since we're using jQuery we can use the library's built-in AJAX methods. The code below creates an AJAX call. the headers are set to GET and the contentType is application/json. We set the url to the path to our WCF service's svc file with a trailing / and then the name of the method we want to execute. In this case we're calling the "DoWork()" method. "data" will be passed in to our function and processData should be set to false so that jquery does not try to auto-process our data. We've also added a success and error function to let us know what happens after executing the AJAX.

Once again, for the sake of this example I am using the GET method to post data to the web service, however it is recommended to use POST.


function sendAJAX(data) {
 $.ajax({
  type: "GET",
  contentType: "application/json",
  url: "Service.svc/DoWork",
  data: data,
  processData: false,
  success:
   function(msg){
     alert( "Data Saved!" );
   },
  error:
   function(XMLHttpRequest, textStatus, errorThrown){
       alert( "Error Occured!" );
   }
 });
}

Now unfortunately there is a small issue here. We must send the actual JSON string as the value for DoWork's Person p param and there's no easy way of turning your JSON object into a string. If you try "data.toString()" you'll just get an "[object Object]" value (remind you of anything?), which is not what we want. So here's a slightly modified function that will take your JSON and turn it into a string.

Note* The JSON de/serialization handles Date/Time in a specific way. The json2string function below does not take this into account. I'm sure there are some implementations out there which will work with ASP.NET AJAX but this one does not. For more information on this you can go here.

Update [4/11/08]: The javascript below has a few issues so it's been suggested that you should use the JSON.org version to "stringify" your object. You can download the script from here.

Update [4/25/08]: Rick Strahl has modified the JSON.org script so that it will properly create the dates to work with ASP.NET AJAX (read his post)


function json2string(strObject) {
 var c, i, l, s = '', v, p;

 switch (typeof strObject) {
 case 'object':
  if (strObject) {
   if (strObject.length && typeof strObject.length == 'number') {
    for (i = 0; i < strObject.length; ++i) {
     v = json2string(strObject[i]);
     if (s) {
      s += ',';
     }
     s += v;
    }
    return '[' + s + ']';
   } else if (typeof strObject.toString != 'undefined') {
    for (i in strObject) {
     v = strObject[i];
     if (typeof v != 'undefined' && typeof v != 'function') {
      v = json2string(v);
      if (s) {
       s += ',';
      }
      s += json2string(i) + ':' + v;
     }
    }
    return '{' + s + '}';
   }
  }
  return 'null';
 case 'number':
  return isFinite(strObject) ? String(strObject) : 'null';
 case 'string':
  l = strObject.length;
  s = '"';
  for (i = 0; i < l; i += 1) {
   c = strObject.charAt(i);
   if (c >= ' ') {
    if (c == '\\' || c == '"') {
     s += '\\';
    }
    s += c;
   } else {
    switch (c) {
     case '\b':
      s += '\\b';
      break;
     case '\f':
      s += '\\f';
      break;
     case '\n':
      s += '\\n';
      break;
     case '\r':
      s += '\\r';
      break;
     case '\t':
      s += '\\t';
      break;
     default:
      c = c.charCodeAt();
      s += '\\u00' + Math.floor(c / 16).toString(16) +
       (c % 16).toString(16);
    }
   }
  }
  return s + '"
';
 case '
boolean':
  return String(strObject);
 default:
  return '
null';
 }
}

Now that we have a function to turn our JSON object into a string we need to go back and update the "mydata" variable that we defined above. After applying the json2string function we should have the following: 


var mydata = { "Name":"Denny", "Age":23, "Shoes":["Nike","Osiris","Etnies"] };
var jsonStr = "p=" + json2string(mydata);

Notice that I prepended the "p=" string to our json string. "p" matches the parameter name in our "DoWork()" method. So if our parameter name was "Dude" ( i.e. DoWork(Person Dude) ) then we would use "Dude=" instead.

Now that we've built the querystring to the web service we can see what our call is going to look like (if using GET method):

http://www.dennydotnet.com/Service.svc/DoWork/?p={ "Name":"Denny", "Age":23, "Shoes":["Nike","Osiris","Etnies"] }

You may get a URL Encoded value too, which would look like:

http://www.dennydotnet.com/Service.svc/DoWork/?p=%7b+%22Name%22%3a%22Denny%22%2c+%22Age%22%3a23%2c+%22Shoes%22%3a%5b%22Nike%22%2c%22Osiris%22%2c%22Etnies%22%5d+%7d%3b

Go ahead and link "jsonStr" to the "SendAjax()" javascript method so we can debug our service and verify that the data was passed through to the service... check it out:

And now you just need to implement your logic in the DoWork() method. Notice how you don't have to do any de/serialization on the WCF service side either, it's already done for you. Now you should certainly implement some exception management so that you don't get any invalid data, or even add some authentication, but I'll leave that up to you...

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags: , , ,
Posted by Denny on Monday, March 03, 2008 9:40 AM
Permalink | Comments (12) | Post RSSRSS comment feed

SoCal Code Camp!

Just finished RSVP'ing for SoCal Code Camp! It will be held on Jan. 26 and 27 at the University of California Fullerton (UCF). Head over to the website (below) and sign up! Hope to see you there!

From the email:

If you haven't already registered at http://www.socalcodecamp.com for the upcoming Rock & Roll Code Camp to be held in Fullerton - why not take a minute to do it now!?!?

We already have 50 sessions and counting. Many of your favorite speakers are returning to provide you with great new content including Kevin McNeish, Paul Sheriff, Daniel Egan, Michele Leroux Bustamante, Mickey Williams, Woody Pewitt, David McCarter and more! Imagine, many of these internationally known speakers frequent conferences like Tech Ed, PDC, MIX, Dev Connections, VSLive and more! And you get to see them talk for FREE!!!!

There are also some budding new speakers that offer great sessions based on their real world experiences in the local community. You could even be one of them - feel free to add more sessions to the site, we have room for more!

The schedule will be posted one week before Code Camp so you can plan your attack!

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by Denny on Wednesday, January 16, 2008 5:44 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Animating ASP.NET AJAX Update Panel Updates

Do you dislike the way that ASP.NET AJAX Update Panels update (or replace the content within the update panel)? Is it not flashy and Web 2.0 enough for you? Well fear no more! I've devised a straight-forward script to help you animate your update panel updates. This script uses jQuery (www.jquery.com) to animate the content when an update panel updates. It can easily be modified to use another library such as Scriptaculous. It uses javaScript to override ASP.NET AJAX's _updatePanel method within the PageRequestManager (the method which does the actual replacing of the content).

I've commented the script so you can understand what it's doing:


$(document).ready(
  function() {
      // SAVE the original _updatePanel function for later use.
      var old_prm_updatePanel = Sys.WebForms.PageRequestManager.getInstance()._updatePanel; 

      // Overwrite the original method with our code which will apply animation.
      // (Note: The method signature remains the same)
      Sys.WebForms.PageRequestManager.getInstance()._updatePanel = 
          function(updatePanelElement, rendering) {
              // Using jQuery to hide (animate) the element. Then use the callback function 
              // to load and show the new data. You don't want to update the
              // data beforehand otherwise you'll see your update panel flicker.
              $(updatePanelElement).hide('slow',
                  function() {
                      // Pass the old function and the args
                      loadShowUpdatePanel(old_prm_updatePanel, updatePanelElement, rendering);
                  });
          }
   });
 
function loadShowUpdatePanel(old_prm_updatePanel, updatePanelElement, rendering) {
    // Call the original (old) function with context of Page Request Manager instance.
    // We call the original method so ASP.NET AJAX can do all the necessary actions.
    old_prm_updatePanel.apply(Sys.WebForms.PageRequestManager.getInstance(),
                                                               new Array(updatePanelElement, rendering));

    // using jQuery again to show (animate) the update panel.
    $(updatePanelElement).show('slow');
}

And that's all you need. This script isn't just limited to animating the update panel update either... You can extend this script to do anything you want immediately before and after the new content is displayed. The main difference between this method and using the add_BeginRequest or add_EndRequest methods is the timing. This script will fire exactly before and after the update takes place - This would not be a good place to show a loading screen because the AJAX call has already been made, there's nothing to wait for. Whereas the BeginRequest executes before the AJAX call and EndRequest fires after the update has completed - This would be good to apply a loading screen.

kick it on DotNetKicks.com

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by Denny on Thursday, November 08, 2007 6:08 PM
Permalink | Comments (3) | Post RSSRSS comment feed

The ASP.NET MVC Framework...

Finally some great news! Scott Gu officialy announced the ASP.NET MVC Framework on his blog. I'm so anxious to get my hands on the framework! If you're not familiar with MVC I would suggest reading Scott's post, he explains it briefly.

However there are some really cool features... for example you can use both MVC and WebForm frameworks. You can also continue to use Master Pages, ASCX controls, <%=%> snippets and plenty more. The MVC framework will not use the existing post-back model, instead you route all end-user interaction to a Controller (no viewstate or page lifecycle - a great approach).

What about ASP.NET AJAX UpdatePanels? Scott mentions this in his comments:

UpdatePanel does use postback, so you won't use that control directly within a MVC based view.  But there will be a control (and optional helper method) with capabilities very similar to it.  It will invoke an action on a controller and allow you to incrementally update a portion of HTML really easily.  It will enable you to use the ASP.NET AJAX libraries really easily.

Curious to see the "optional helper method."

My biggest frustration has been with the difficulty in mashing JavaScript with ASP.NET WebForm's rendered output. With the MVC Framework it seems like I'll finally have the control I want to use JavaScript frameworks and server-side controls seamlessly.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags: , ,
Posted by Denny on Monday, October 15, 2007 3:35 AM
Permalink | Comments (2) | Post RSSRSS comment feed

A DataTable Serializer for ASP.NET AJAX

A DataTable Serializer for ASP.NET AJAX, implements JavaScriptConverter. Note that I did not implement a Deserialize method since I am using this for read only data.


/// <summary>
/// DataTable to JSON converter
/// </summary>
public class JavaScriptDataTableConverter : JavaScriptConverter {
 public override object Deserialize( IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer ) {
  throw new NotImplementedException( "Deserialize is not implemented." );
 }

 public override IDictionary<string, object> Serialize( object obj, JavaScriptSerializer serializer ) {
  DataTable dt = obj as DataTable;
  Dictionary<string, object> result = new Dictionary<string, object>();

  if( dt != null && dt.Rows.Count > 0 ) {
   // List for row values
   List<object> rowValues = new List<object>();

   foreach( DataRow dr in dt.Rows ) {
    // Dictionary for col name / col value
    Dictionary<string, object> colValues = new Dictionary<string, object>();

    foreach( DataColumn dc in dt.Columns ) {
     colValues.Add( dc.ColumnName, // col name
      ( string.Empty == dr[dc].ToString() ) ? null : dr[dc] ); // col value
    }

    // Add values to row
    rowValues.Add( colValues );
   }

   // Add rows to serialized object
   result["rows"] = rowValues;
  }

  return result;
 }

 public override IEnumerable<Type> SupportedTypes {
  //Define the DataTable as a supported type.
  get {
   return new System.Collections.ObjectModel.ReadOnlyCollection<Type>(
    new List<Type>(
     new Type[] { typeof( DataTable ) }
    )
   );
  }
 }
}

And how do you implement this? In a web service...


using System.Web.Script.Serialization;

// ...

[WebMethod()]
[ScriptMethod( ResponseFormat = ResponseFormat.Json )]
public string TestJS( int Id ) {
 JavaScriptSerializer toJSON = new JavaScriptSerializer();
 toJSON.RegisterConverters( new JavaScriptConverter[] { new JavaScriptDataTableConverter() } );

 DataTable dt = new Query( Log.Schema )
   .WHERE( Log.Columns.ID, Id )
   .ExecuteDataSet().Tables[0];

 return toJSON.Serialize( dt );
}

That's all there is to it! Just deserialize to an object on the client-side and you're good to go!

Side Note: There is a DataTable serializer from Microsoft in the ASP.NET Futures package.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags: ,
Posted by Denny on Friday, September 14, 2007 11:05 AM
Permalink | Comments (2) | Post RSSRSS comment feed

UpdatePanels: When and Where

I've been using the ASP.NET AJAX Update Panels for quite some time now and have picked up a lot of tips on when and how to use them. Update Panels were intended to allow the developer to do Partial Page Updates. Usually what you see is Update Panels updating nearly the entire page which completely defeats the purpose of Update Panels!

Here are some good tips to take into account when developing with Update Panels:

#1. One thing I notice is that people want to stuff all their functionality into one page with multiple hidden/visible panels. Then utilize the functionality by showing/hiding the panels based on actions within the page. This can lead to very confusing code...

If you're changing from one action which does a lot of functionality with X to an action which does a lot of functionality with Y then separate the functionality and use a page postback to switch between those pages. Don't throw everything together into one update panel and separate it by hidden panels. You'll end up with a ton of code which is not resuable and difficult to understand. Separate your functionality just like you would separate your DAL, BL and Presentation.

Example for an Admin section:
  • User Management (insert, update, delete users)
  • Settings (change your web app's settings)
  • Media Management (insert, update, delete media)
  • etc...

#2. Separate your Update Panels. Instead of throwing everything into one update panel break it up! Plan what areas of your page will need to update and what will trigger them to update. This will save you an insane amount of bandwidth (and download time) and return much better performance.

Example:
Lets say you have 3 areas on your page that will allow a user to: select a category, select a video and then watch the video.

  • Part 1 displays a list of categories
  • Part 2 displays a list of videos within that category
  • Part 3 displays a video player

Lets think logically about the flow of execution with the 3 parts. First a user picks a category in Part 1. Then they select which video they want to watch in Part 2. And finally the video displays in Part 3 and begins playing.

So there are 2 steps involved to watch a video:

  1. Pick a category
  2. Pick a video


And 2 triggers:

  1. "Click" a category
  2. "Click" a video



(Each arrow represents a click)

So we've got the basic idea down now how do we determine WHERE we need update panels? We need to determine what parts change. The only parts that change are Part 2 which shows a list of videos within the selected category and Part 3 which plays the selected video. Part 1 will not change because nothing within that part changes. Part 1 is only used to select a category and the categories are loaded at Page_Load.

(Of course if you added paging or sorting to Part 1 you could then use an update panel but for this example Categories are static.)

So you have 2 parts that change meaning you only need 2 update panels, one for Part 2 and one for Part 3. Now how do we trigger these updates? Based on the flow we determined above we know what triggers are needed...

Triggers:

  • Part 2 needs to update when a category is selected from Part 1.
  • Part 3 should update when a video is selected from Part 2.

We also want to hide the video player when the user selects a new category because it wouldn't make sense to continue showing a video from the "Comedy" category after they selected the "Drama" category. So we'll need one more trigger:

  • Part 3 should update when a category has been selected since we don't want to display the old video when they select a new category.


(Each arrow represents where the item is triggered from [start of line inside part] and what part it affects [end of line])

And that's all we need to properly separate our update panels. The cool thing about upate panels is that your trigger control does not need to be within the same update panel. In other words, it can be located anywhere on your page outside the update panel. That's why we only need 2 update panels. The triggers in part 1 can be set programatically or through the update panel "triggers" GUI from the properties menu.

Quick Tip: If you want to know how to set a trigger programatically then read this post.

What's the benefit of separating the update panels? Alot of Bandwidth! Update panels respond with their entire rendered contents when doing an AJAX call. Update panels also attach any control viewstates to the response. If you were to place the entire content of the example above in one update panel you'll be uploading and downloading everything every time you do a callback. On the other hand if you separate your update panels, like the example above, you'll only download the contents of the update panel that has been triggered.

Quick Tip: If a control within an update panel does not need viewstate enabled then disable it! This is a good way to decrease the size of the response.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by SuperGhost on Thursday, August 30, 2007 9:19 AM
Permalink | Comments (1) | Post RSSRSS comment feed

ASP.NET AJAX createDelegate and the JavaScript "this"

If you're doing ASP.NET AJAX and you're creating a lot of JavaScript then you are hopefully aware of the Function.createDelegate method. If you're not using the createDelegate method then read on!

When you're building your classes in ASP.NET AJAX you'll have various function that interact with each other. Sometimes you may even have external methods that you're calling. So when you want to reference a javascript object you would probably pass the object through the parameters list. When it comes to doing a Web Service call you have a callback method for success and fail such as:


var el = this;
Client.GetSomeField(1, 5, onSuccess, onFail);

function onSuccess(r) {
 var el = this;
 alert(r);
}


Everything looks dandy. However when I use "this" inside any of the callback methods I won't get the object I am looking for. Lets say I wanted to pass "this" object to my onSuccess function. How could I do that? Well that's where the createDelegate comes in:


var el = this;
var newSuccess = Function.createDelegate(el, onSuccess);

Client.GetSomeField(1, 5, newSuccess, onFail);

function onSuccess(r) {
 // You now have access to the same object using "this"
 var hw = this.HelloWorld();
 alert(r + hw);
}


Wow well that was easy! The cool thing about this is that you can pass any object with the createDelegate method. So if I wanted to pass a string I could do:


var el = "Hey I came from down the way";
var newSuccess = Function.createDelegate(el, onSuccess);

Client.GetSomeField(1, 5, newSuccess, onFail);

function onSuccess(r) {
 var hw = this; // this = "Hey I came from down the way"
 alert(r + hw);
}


Tada! I just passed my string across.

Well now wait a second, I have another function that takes in a few extra params. It's not within a Web Service method, it's an external function. How do I use createDelegate with that?


var el = this;
var newSuccess = Function.createDelegate(el, onSuccess);

// Call the function
newSuccess(param1, param2, param3);

function onSuccess(p1, p2, p3) {
 // still the same object that we passed
 var hw = this.HelloWorld();
 hw += p1;
 hw += p2;
 hw += p3;
 alert(hw);
}


The createDelegate method takes two parameters. The first one is the object that will be referenced by "this" (inside the function). The second parameter is the function to be executed (where you'll use "this").

Another good trick is to use the createDelegate function with the $addHandler method:


$addHandler(btnSave, 'click', Function.createDelegate(someOtherObj, this.onSaveClicked));


So in conclusion, why use createDelegate? It wraps an existing function and returns a new function which can use the "this" keyword that points to an object of your desire. Why do I need this? In an event handler raised by a DOM element the "this" keyword will refer to the DOM element whereas you may want it to refer to a class or class object, or any other object for that matter.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by SuperGhost on Tuesday, July 24, 2007 8:57 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Programmatically adding an AsyncPostBackTrigger

The AsyncPostBackTrigger is used in ASP.NET AJAX to, as it states, trigger an asynchronous postback. Adding a trigger to an UpdatePanel is fairly straight forward. You can either do it through the UP's Triggers GUI or within the <asp:UpdatePanel> tag under the <Triggers> tag by adding:


<asp:AsyncPostBackTrigger ControlID="someControl" EventName="Click" />

Adding a trigger through any of the previously mentioned methods works as expected. The problem is when you want to set an AsyncPostBackTrigger on a dynamically generated control, like one within a DataList. You cannot do this through the GUI mode because it will not list the control. Instead you have to programmatically add an AsyncPostBackTrigger.

My issue began when I tried to set a trigger on a LinkButton within a DataList. The LinkButton uses the OnCommand event to pass a CommandArgument. In the DataList_OnItemDataBound I added the appropriate code to wire up the AsyncPostBackTrigger:


// Add postback trigger
AsyncPostBackTrigger ap = new AsyncPostBackTrigger();
ap.ControlID = lnkControl.UniqueID;
ap.EventName = "Command";
upFMV.Triggers.Add(ap);

Now it seems rational that the EventName would be "Command" and that this should work the same way as the previous methods. However after running the code I get no UpdatePanel update! I tried a few other event names but to no avail. After posting a question on forums.asp.net I was told to remove the event name. This actually worked but I'm still not sure why.

My code now looks like:


// Add postback trigger
AsyncPostBackTrigger ap = new AsyncPostBackTrigger();
ap.ControlID = lnkControl.UniqueID;
upFMV.Triggers.Add(ap);

It seems to fire for the correct event too. Even though it works if anyone has any insight to this I would greatly appreciate it! And if you're trying to learn how to use the AsyncPostBackTrigger, well now you've got an example.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by Denny on Wednesday, July 18, 2007 4:40 AM
Permalink | Comments (4) | Post RSSRSS comment feed

New Dad, Job and Knowledge

Well it's been a long while since I've blogged and I'm finally getting around to it. There's been a lot of things going on lately! First and foremost I'm going to be a new Dad starting next year around February or March. I'm excited about the news and can't wait to find out if it's a boy or girl. Things will definitely start changing around the house!

Secondly, I started a new job! I'm really excited about working at this new place because they're doing some really cool AJAX stuff. It's a great opportunity for me because I'll get to work with some really bright people and work with the latest technologies too. I recently picked up a book titled: "Professional ASP.NET 2.0 AJAX" by Matt Gibbs and Dan Wahlin (Amazon) to get some further insight on the ASP.NET AJAX Framework. It's an excellent book and there's plenty of tips and knowledge in here even if you're experienced. For example, I finally found out what the benefit of using the ASP.NET AJAX registration methods (for namespaces, classes, etc...). It has to do with performance, amongst other things. I'll blog more about this later! On another note I introduced SubSonic to the team as well. I had some positive feedback and it looks like we could be implementing it across various projects in the future.

I've recently been working with the ASP.NET AJAX Serialization classes, in particular the JSON serializer. There didn't seem to be too many resources while Googling for examples so I poked around and created a few helper functions for myself such as serializing a DataTable or DataReader into a JSON array / object (Yes ASP.NET Futures supports this already). I'll blog about this in the future as well. Anyways, upon creating some helper functions I realized I had something interesting started. I began thinking about how I could bind my array of JSON objects to a pre-defined template, like a Repeater only on the client-side. It seems possible but I haven't researched this thoroughly to see what implications it could have. It may be a side project in the future.

Feedback:
What I'm interested in knowing is how other people have been using ASP.NET AJAX. Are you taking adavntage of Web Services, or are you using PageMethods? Are you relaying your data as XML or JSON? Why? How are you using the data passed to the client. For example are you using it to update one or two specific elements or are you bulking your objects together to complete multiple tasks?

I'm very interested in hearing your responses.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by SuperGhost on Monday, July 16, 2007 5:05 PM
Permalink | Comments (2) | Post RSSRSS comment feed