A AJAX Framework: A AJAX Engine for JavaScript, XML, SOAP, WSDL und ASP.NET using standard WebServices on the server. How to read cookie values in JavaScriptI 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. Labels: JavaScript Extending the initialization sequence of JavaScript behaviorsThis 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:
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 methodAnother 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. How to set up a web project using the AjaxEngine – Part 1bSome 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 filesThe 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 wayI 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:
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:
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 Labels: Ajax, AJAXEngine, documentation, JavaScript Calling WCF and SOAP based webservices from AJAXThe 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:
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.xsltThe 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:
GetJavaScriptProxyIn 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 AjaxImplementing 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 configurationBy 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> Labels: Ajax, JavaScript, SOAP, WCF, webservice How to setup a new AjaxEngine web projectI 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/ For this project you only need the following core files GetJavaScriptProxy.aspx: the JavaScript proxy generator
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.asmxThere 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 {
///
5. Create a new page named WebForm1.aspx in the calc folderI just use the new item wizard from visual Studio to do this so the typical elements are there already.
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 interfaceA minimalist UI means just 3 fields and some text.
<input id="sum1" type="text" /> + <input id="sum2" type="text" /> = <input id="result" type="text" /> 9. Implement the JavaScript codeThis is the trickiest part of it, but it's simple too:
<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. Labels: AJAXEngine OpenAjax Call-to-Action to Ajax Developers for Browser WishlistThe 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:
The process is completely open and Wiki-based, so feel free to contribute^. Data bound fields for Ajax formsAn overview of the Ajax forms implementation of the AjaxEngine framework has already been published some days ago at http://ajaxaspects.blogspot.com/2007/12/using-openajax-events-for-building-data.html. Here are more details of the concept around binding html elements to Open Ajax events.
Client side API for data bound elementsThe API for the data controls is unified as far as possible and for all the data controls the following common features are implemented: element.eventname If this attribute is set the the element will listen to and possibly publish an OpenAjax hub event to exchange the changed value through the eventing mechanism. If the value of the eventname attribute does not contain a full namespace but only the local name of the event, the eventnamespace attribute of any parent element is used to complete the namespace. This may be in many cases the surrounding DataFormBehavior element. element.datatype This attribute can be set to the name of the datatype of the values. This enables some datatype specific behavior implementation within the element for example converting the non-string datatypes to the specific notation. If this attribute is not set then the exchanged data will is used without any special formatting conversions and no other restrictions are applied. Just like a string type. This attribute should not be changed by JavaScript. Use the setDatatype(type) method in the case you need that. element.setData(newValue) This method is available to set the value of the control directly by using JavaScript. This method is also used internally for all cases when the value of the control has to change. This method can be overwritten by other, derived controls. element.getData() This method is available to JavaScript implementations that need to access the value of a (input) field directly. Don't use the innerText or value attributes of an HTML element directly because there may be type conversion and/or translations necessary that are executed for your convenience when using this method. element.setDatatype(newType) When the datatype of an data item is not known when loading the page and by using the datatype attribute this method can be to pass the new datatype. All the values that are exchanged between the Ajax form element and the inner data controls are using the format defined by the XML datatypes (here simply called the standard format) . This implies that the inner data controls have to take care about converting the values into some more useful formats and that the Ajax form and more important the server doesn't have to care about these specific formats. There is also another way how values can be exchanged among different controls that is the OpenAjax event mechanism. Every time the Ajax form gets a new dataset is also published all the values by using the eventnamespace of the Ajax form. OpenAjax events are also used to sync the inner data controls that all deal with the same data item. name attribute This attribute of an inner element is not used. Using this attribute is heavily used by the classic HTML form mechanism. This still allows "hybrid" web pages where the user gets some advice and aid by using AJAX calls to the server but where the form.submit functionality is still used for the real processing of the data of the form.
Data bound elements and behaviorsDataOutput ControlsIf you have data items that come from the server an that will not be changed by the user you can use the DataOutput control. The DataOutput Behavior only registers for the appropriate event that is specified through the eventname attribute and displays all published values inside the control. The implementation uses a <span> element for displaying the values but other Controls that derive from DataOutput can also use different element eventually by overwriting the setData method. The setData method can also be used to display values when implementing directly with JavaScript. It also takes care of the datatype attribute. If this attribute is set the given value in the standard format will then be converted into the national language specific notation within the setData method by using the nls object that will be described later. The reference documentation can be found at http://www.mathertel.de/AJAXEngine/documentation/ViewDoc.aspx?file=~/controls/DataOutput.js DataInput ControlsThe DataInput component is a general purpose JavaScript Behavior based control that implements the functionality for binding a regular <input> element to OpenAjax events for building Ajax forms. The implementation takes also care of the datatype in a special way by using the implementation of datatype specific functionality that are available through the nls object that will be described in a later article in detail.
You can build more specific components based on this JavaScript Behavior by deriving from this implementation and adding some special features. The reference documentation can be found at http://www.mathertel.de/AJAXEngine/documentation/ViewDoc.aspx?file=~/controls/DataInput.js The DataFade controlThe DataFade Behavior implementation inherits from the DataOutput implementation and adds the Fade effect. Every time a new value is set into this element the background becomes yellow and is then smoothly fading to the original background color to attract the users attention. A sample page for this effect can be found at http://www.mathertel.de/AJAXEngine/S04_VisualEffects/FadeDemo.aspx. The reference documentation can be found at http://www.mathertel.de/AJAXEngine/documentation/ViewDoc.aspx?file=~/controls/DataFade.js |
The bookThe book "Aspects of AJAX" is available in PDF format at: Sample WebSiteThe samples as well as the complete source code can be found on this web site:
http://www.mathertel.de/ DownloadsAJAX.zip (180 kByte) This Zip-File contains the ASP.NET 2.0 web project that builds this side. All samples and Controls are included. AJAXEngine.zip (80 kByte) This Zip-File contains the core files of the AJAX engine and the AJAX controls. License
Recent posts:How to read cookie values in JavaScript Extending the initialization sequence of JavaScrip... How to set up a web project using the AjaxEngine –... Calling WCF and SOAP based webservices from AJAX How to setup a new AjaxEngine web project OpenAjax Call-to-Action to Ajax Developers for Bro... Data bound fields for Ajax forms Building menus with OpenAjax events More OpenAjax compatible components Archives
Tags: Ajax Javascript webservices soap wsdl xmlhttp |