Donnerstag, November 14, 2013

AjaxEngine: get rid of event.srcElement

It’s time to say goodbye to some of the compatibility tricks in the AjaxEngine. Here is the first article on maintaining your Javascript code if you come from some older versions.

A note for the future

If time is beyond April 2014 (the time when Windows XP and IE 8 and older dies), you don’t need to read and understand. If you find a code that reads obj.srcElement, just change it to obj.target.
You stumbled upon some old-browser-compatibility issue.

History

The srcElement property on event objects was introduced by Microsoft to find out what html element was actually meant when a event was fired. The AjaxEngine then implemented some tricky code to make this property available in other browser too:

  // enable using evt.srcElement in Mozilla/Firefox
  Event.prototype.__defineGetter__("srcElement", function () {
    var node = this.target;
    while (node.nodeType != 1) node = node.parentNode;
    // test this:
    if (node != this.target) alert("Unexpected event.target!")
    return node;
  });

Now, the W3C standard defines a target property that has the same meaning and also Microsoft moves to use the standard conform property in the newer browsers. I strongly advise to not support these older browsers any more because they never will be fixed for security issues any more.

For now you should find the target object inside an event handler by using:

var obj = evt.target || evt.srcElement;

and starting with April 2014 you just should use:

var obj = evt.target;

Changes to AjaxEngine

I searched all “.srcElement” occurrences and changed them to the compatible assignment

var obj = evt.target || evt.srcElement;
An updated download archive is available as well as commits to the sourcecode repository:
http://sourceforge.net/projects/ajaxengine/
or directly using subversion:
https://svn.code.sf.net/p/ajaxengine/code/trunk
See also

http://msdn.microsoft.com/en-us/library/ie/ff974945(v=vs.85).aspx

Samstag, Dezember 05, 2009

How to read cookie values in JavaScript

I recently had some odd effects with some pages that use cookies to store some local information. The bug seems to be widely spread in many web applications so here are my findings:

To read the value of a specific cookie that was set previously you have to analyze the string in document.cookie that contains all cookies. It’s a very readable format and looks like:

a=a101; aha=aha101; bob=bob101; b=b101; c01=c0101

The trick is to find the right cookie in this string and extract the value.

I used a JavaScript function, named getCookie() that searched for the position of the cookie name by using

start = document.cookie.indexOf(name + "=");

… and this is wrong in some cases.

If you search for the cookie named "b" in the sample above you will get a starting-position within the cookie named "bob" because the indexOf function stops at the first occurrence of the text "b=".

This seems to be a very common approach and some educational web sites still publish this kind of code that contains the mistake.

http://www.w3schools.com/js/js_cookies.asp

It’s easy to fix this line by including the space character:

var start = document.cookie.indexOf(" " + name + "=");
if (start >= 0) {
  start += 1
} else if (document.cookie.indexOf(name + "=") == 0) {
  start = 0;
} // if

But there is a more elegant solution when using regular expressions and even the retrieval of the value gets easier that I found at

http://www.elated.com/articles/javascript-and-cookies/

Here is the full function:

function get_cookie (cookie_name)
{
  var results = document.cookie.match('(^;) ?' + cookie_name + '=([^;]*)(;$)');
  if (results)
    return (unescape(results[2]));
  else
    return (null);
}

Check your code.

Samstag, November 15, 2008

Extending the initialization sequence of JavaScript behaviors

This topic was recently discussed in the OpenAjax group and here is the implemented solution for the AjaxEngine framework. The consensus was to solve the initialization problem on the application level and not within the OpenAjax hub.

 

When multiple components resist side by side on the same page the initialization sequence of the components can become critical for the page to work as expected. Therefore the JavaScript behavior mechanism supports 3 phases of initializing the application when a page loads:

  1. The optional init() method is called first for every control that was initialized by LoadBehavior. This method should contain all initialization code that puts the control in a fully working state. Especially the control should register for any interesting OpenAjax event.
  2. The optional initstate() method is called then and allows the control to inform other controls about their existence and publish state information by using OpenAjax events or direct method calls if appropriate.
  3. The optional afterinit() method is called at last to controls can finish the setup where all other controls are also working.

All controls can participate in the initialization phases by implementing the calls. They are all optional. All 3 methods will be called when the onload event is raised for the window object.

The term method

Another method named "term" can be defined in the JavaScript prototypes to implement a method that is called just before a page unloads. There is a real need for implementing code just before all HTML and JavaScript objects are thrown away in Microsoft Internet Explorer, because there is a well known problem with the memory management used by the HTML DOM and JavaScript. Both object libraries do have their own garbage collector implementation and in some cases circular references between objects of both worlds are not properly detected and memory will not get freed and useless memory consumption is the unwanted result.

The best solution against this “design weakness” is to set all references of JavaScript variables to HTML elements to null in this method.

There is also a great tool and some more background information available that helps to detect this kind of memory leak named Drip available at http://outofhanwell.com/ and is a definitive TO-DO when supporting older browser versions of IE.

Montag, Juli 07, 2008

How to set up a web project using the AjaxEngine – Part 1b

Some days ago I posted part 1a - a short instruction about how to set up a minimal project.

The sample I used to demonstrate that the infrastructure works was as simple as possible and is using a RPC style of Ajax calls to the server. Some topics have not been touched so here they come.

How to get the files

The easiest way to get all the files I’ve talked about is to go get them directly from the repository hosted as sourceforge. 

http://sourceforge.net/projects/ajaxengine/ is the projects's home page and you can browse the repository directly by using the url http://ajaxengine.svn.sourceforge.net/viewvc/ajaxengine/trunk/.

Here all the development progress will be available as soon as soon as I write about it.

Another possible way to get the files is to use a subversion client for example http://tortoisesvn.tigris.org/ that includes more functionality like getting a copy of all the current files at once, looking into the change log and comparing different versions of the same file.

From time to time the download archives are updated too. You can find them on my site at http://www.mathertel.de/AjaxEngine/#view=Downloads

Calling web services the right way

I have to mention, that this is not the best way of calling a server because synchronous calls may block or freeze the client during the call and the call time may be very long when the network or the server is used a lot. Using asynchronous calls is the answer to that problem and there is simple but great mechanism inside the ajax.js file that makes asynchronous programming quiet easy. Here is just a brief explanation of how to use it. More of the mechanism and it's options can be found in the book Aspects of Ajax.

The typical AJAX scenario follows the following pattern and can be split into 4 separate problems:

  1. Waiting for an event that will start the Ajax call to the server.
    Sometime that’s an easy thing to do, because there is a button clicked and we just can attach the initializing code to an event. But sometimes events have to be queued up to avoid a race condition and get wrong answers.
  2. Collecting some data on the client side.
    It is often necessary to do this right before you call the server and not in the moment when the call is initiated.
  3. Communication with the server.
    That is done by using the client stub that is generated for each SOAP based web service.
  4. Finally using the result from the server.
    That must be done, when the data is available and is the typical asynchronous functionality of Ajax.

Many grown-up Ajax implementations are using a JavaScript object that binds the JavaScript functions that all together will solve the scenario and so does the AjaxEngine:

// declare an AJAX action var action1 = { // the prepare function collects and returns the data for the server side method.

// It just returns an array with the parameters and marks it with "multi". prepare: function(obj) { var p = []; p[0] = document.getElementById("n1").value; p[1] = document.getElementById("n2").value; p.multi = true; // the hint for the ajax Engine return (p); }, // the call element points to the proxy for the server call as usual call: proxies.CalcService.AddInteger, // the result will be written it into the appropriate html field. finish: function (p) { document.getElementById("outputField").value = p; } } // action1

This action can be used to start an Ajax call by using some inline code like this:

<input id="n1" onkeyup="ajax.Start(action1)" />

Now Ajax starts getting robust enough in a real web application.

The code is from the sample that you can find in the sample at

http://www.mathertel.de/AJAXEngine/S02_AJAXCoreSamples/CalcAJAX.aspx

Sonntag, Juli 06, 2008

Calling WCF and SOAP based webservices from AJAX

The JavaScript proxy that is implemented for the Ajax engine to call SOAP based web services has been used on the ASP.NET platform for a long time and was ported to other platforms like Java. Some derived work can also be found for PHP and the Qooxdoo. It’s pretty stable for a while and that’s a good message.

When working with some specific Java based platforms there was a specific problem with the automatic generated WSDL descriptions, because they use an external schema for defining the structure of the passed data:

<wsdl:types> <xsd:schema targetNamespace="http://tempuri.org/Imports"> <xsd:import schemaLocation=http://localhost/AJAXEngine/S02_AJAXCoreSamples/CalcFactors.svc?xsd=xsd0

namespace="http://tempuri.org/" /> ... </xsd:schema> </wsdl:types>

The workaround was to write the JSON structure that is used by the JavaScript proxy by hand (and that is still a good idea for high trafic web sites).

When adopting the WCF .svc services this kind of using WSDL and XML schema definitions can be found too.

A solution for this is quiet simple and can now be found in the wsdl.xslt and the GetJavaScriptProxy.aspx files.

wsdl.xslt

The WSDL to JavaScript transformation now looks for import nodes under the wsdl:types and then imports the referenced schema by using the xslt document() function. Then this imported document is searched for the right element and the parameter and return value description is generated through the soapElem template. Here is the added xslt code:

<xsl:when test="/wsdl:definitions/wsdl:types/s:schema/s:import">

<!-- importing an external schema –>

<xsl:variable name="inputElementName" select="substring-after(wsdl:part/@element, ':')" />

<xsl:for-each select="/wsdl:definitions/wsdl:types/s:schema/s:import">

<xsl:variable name="doc" select="document(@schemaLocation)"/>

<xsl:for-each select="$doc/s:schema/s:element[@name=$inputElementName]//s:element">

<xsl:call-template name="soapElem">

<xsl:with-param name="name" select="@name" />

<xsl:with-param name="type" select="@type" />

</xsl:call-template>

<xsl:if test="position()!=last()">,</xsl:if>

</xsl:for-each>

</xsl:for-each>

</xsl:when>

GetJavaScriptProxy

In the .NET environment the document function will not work for security reasons without some special instructions for the xslt transform. When passing a  XmlUrlResolver when loading the xslt file the document() function can retrieve the referenced external document.

XmlUrlResolver resolver = new XmlUrlResolver();
resolver.Credentials = CredentialCache.DefaultCredentials;

XslCompiledTransform xsl = new XslCompiledTransform();
xsl.Load(Server.MapPath("~/ajaxcore/wsdl.xslt"), XsltSettings.TrustedXslt, resolver);

Implementing a WCF service for Ajax

Implementing a WCF service for Ajax is almost as simple as programming an *.asmx based service but you can also use an external C# class or interface for implementing the service.

You can find a sample source code in:

http://www.mathertel.de/AJAXEngine/S02_AJAXCoreSamples/CalcFactors.svc

The configuration

By default the WCF services use the SOAP 1.2 format but we don’t need the ws-* functionality and the soap basic profile is perfect for using webservice with AJAX solutions. This can be done by using the following configuration in web.config:

<system.serviceModel>
  <behaviors>
    <serviceBehaviors>
      <behavior name="AjaxBehavior">
        <serviceMetadata httpGetEnabled="true" />
        <serviceDebug includeExceptionDetailInFaults="false" />
      </behavior>
    </serviceBehaviors>
  </behaviors>

  <services>
    <service behaviorConfiguration="AjaxBehavior" name="CalcFactors">
      <endpoint address="" binding="basicHttpBinding" contract="CalcFactors" />
    </service>
  </services>
</system.serviceModel>

Sonntag, Juni 22, 2008

How to setup a new AjaxEngine web project

I was asked how to setup a web project that uses the AjaxEngine so here is step by step tutorial for a minimal Ajax web project that calls a server side web service:

1. Create a new web project (I prefer using c#) or use your existing web project.

I started with a new project and named it "mini". There is nothing special that you have to set up. It even works without a web.config.

2. Copy the ajaxcore folder to your project.

You can find this folder and the files on sourceforge http://sourceforge.net/projects/ajaxengine/
in the subversion repository by using the path https://ajaxengine.svn.sourceforge.net/svnroot/ajaxengine
or in one of the source code downloads like http://www.mathertel.de/Downloads/Start_AJAX_new.aspx.

For this project you only need the following core files
ajax.js: the client side AjaxEngine

GetJavaScriptProxy.aspx: the JavaScript proxy generator
wsdl.xslt: the WSDL to JavaScript transformation

 

That’s all you have to do to prepare the web project to use the core part of the AjaxEngine. I suggest you use the ajaxcore folder

3. Create a folder named "/calc"

This folder will contain the minimal web application by using a web form and a web service.

I guess you don't implement pages in the root folder of your web application so I follow this best practice here too.

4. Implement a service /calc/WebService1.asmx

There is only one method we need so here is some c# code:

using System.ComponentModel;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

namespace mini.calc {
  /// 
  /// Summary description for WebService1
  /// 
  [WebService(Namespace = "http://tempuri.org/")]
  [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
  // [System.Web.Script.Services.ScriptService]
  public class WebService1 : System.Web.Services.WebService {

    [WebMethod]
    public double Add(double sum1, double sum2) {
      return (sum1 + sum2);
    }
  }
}

5. Create a new page named WebForm1.aspx in the calc folder

I just use the new item wizard from visual Studio to do this so the typical elements are there already.
There is not much code that must be put into this file.

6. include the ajax.js:

<script src="../ajaxcore/ajax.js" type="text/javascript"></script>

The ajax.js file reference should be included in the <head> element.

7. include the proxy for the webservice:

<script src="../ajaxcore/GetJavaScriptProxy.aspx?service=/calc/WebService1.asmx" type="text/javascript"></script>

This script include should also be included in the <head> element and will make the just implemented webservice and webmethod available through the JavaScript object proxies.WebService1.Add.

8. Implement the User interface

A minimalist UI means just 3 fields and some text.
You also have to remove the <form> element because the fields are not used to post data to the server. 

<input id="sum1" type="text" /> + <input id="sum2" type="text" /> = <input id="result" type="text" />

9. Implement the JavaScript code

This is the trickiest part of it, but it's simple too:
A timer is used to call a function every 200 milliseconds that checks for some changed input values.
The web service is called if any value has changed.

<script type="text/javascript">
  var sum1_obj = document.getElementById("sum1");
  var sum2_obj = document.getElementById("sum2");
  var result_obj = document.getElementById("result");
  var sum1_val = "";
  var sum2_val = "";

  window.setInterval(window.checkValues, 200);
  
  function checkValues() {
    if ((sum1_obj.value != sum1_val) || (sum2_obj.value != sum2_val)) {
      sum1_val = sum1_obj.value;
      sum2_val = sum2_obj.value;
      
      result_obj.value = proxies.WebService1.Add(sum1_val, sum2_val);
    } // if
  } // checkValues
</script>

10. And that's all

Start the Web Form and see how it works.

Mittwoch, April 02, 2008

OpenAjax Call-to-Action to Ajax Developers for Browser Wishlist

The OpenAjax Alliance is developing an Ajax industry wishlist for future browsers, using a dedicated wiki for this initiative (http://www.openajax.org/runtime/wiki). The main purpose of the initiative is to inform the browser vendors about what future features are most important to the Ajax community and why. So far, the alliance has interviewed roughly a dozen industry leaders, including representatives from the ASP.NET AJAX, Dojo, Ext JS, Douglas Crockford of JSON fame, jQuery, Spry, and XAP, and recently held a townhall discussion on the feature request list among its members. The members have concluded that the wishlist (~25 items) is ready for public comments.

The alliance is now issuing a call-to-action to Ajax developers to participate in this initiative, which is open to both OpenAjax Alliance members and to non-members. The alliance especially would like participation from Ajax toolkit developers and leading web developers with expertise in using open browser technologies to achieve rich user experiences. To join the effort, create a wiki login for yourself by following the instructions on the wiki home page (http://www.openajax.org/runtime/wiki). After you have a login, you can then add new feature requests or comment on existing feature requests as you see fit. The initiative operates on an honor-system basis.

The moderators have attempted to make it possible that the community can add comments and vote on particular feature requests without large time commitments. For example, it is possible to simply vote for your favorite feature requests by adding a single row to a wiki table. The alliance’s wiki uses the same markup language as wikipedia.

Here is the timeline:

    • April - Phase I review, where participants not only add comments, but also are asked to identify their Top 5 features (i.e., those features that are most critical for inclusion in next-generation browsers).
    • May - The moderators reorganize and possibly trim away feature requests for which little interest was shown.
    • June - Phase II review, where participants will be asked to provide importance ratings for each of the feature requests on a scale of 0.0 to 5.0.
    • July - The moderators will produce a summary report and notify the major browser vendors about the results.

The process is completely open and Wiki-based, so feel free to contribute^.