0 Replies Latest reply on May 26, 2011 4:53 PM by treate77

    Creating AIR/Web Apps. with XML & E4X using AS3

    treate77

      Needing tips using AS3 with XML/E4X to make my project work over the server:

      1) Here I'm having trouble trying to create a component with a 'GOOGLE MAP' with the user being able to input their location for directions with once submitting the get directions button that it generates the directions in the datagrid automatically.

       

      2) Including a 'DATAGRID'  for customers to be able to retain their info in a datagrid that has been updated by office personnel from an 'AIR APPLICATION' with a XML file that holds the customers info

       

      /**the Component*/

      <?xml version="1.0" encoding="utf-8"?>
      <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:s="library://ns.adobe.com/flex/spark" width="1400" backgroundColor="#666666" xmlns:mx2="library://ns.adobe.com/flex/mx" creationComplete="initApp(event)">
          <mx:Style source="map_1.css"/>
          <mx:XML id="customer_info.xml" source="Assets/customer_info.xml" />
      <mx:Script>
              <![CDATA[
                  /**Google Map Code API:http://code.google.com/apis/maps/documentation/flash/tutorial-flexbuilder.html#DeclaringMa ps_&
                   _http://www.adobe.com/devnet/flex/articles/googlemaps_api.html */
                  import com.google.maps.LatLng;
                  import com.google.maps.Map;
                  import com.google.maps.MapEvent;
                  import com.google.maps.MapType;
                  private function onMapReady(event:Event):void {
                          this.map.setCenter(new LatLng(31.683952973286058, -97.09904551506042), 14, MapType.NORMAL_MAP_TYPE);
                      }
                              click="processForm(event);"
                              private function processForm(event:Event):void { trace(from.text + " " + to.text); }
                  [Bindable]
                      public var directionsSteps:ArrayCollection = new ArrayCollection();
                      dataProvider="{directionsSteps}"
                      var directions:Directions = new Directions(); directions.addEventListener(DirectionsEvent.DIRECTIONS_SUCCESS, onDirectionsSuccess);
                      directions.addEventListener(DirectionsEvent.DIRECTIONS_FAILURE, onDirectionsFail);directions.load("from: " + from.text + " to: " + to.text);
                      Alert.show("Status:" + event.directions.status);
                      map.clearOverlays(); var directions:Directions = event.directions; var directionsPolyline:IPolyline = directions.createPolyline(); map.addOverlay(directionsPolyline);
                                  var directionsBounds:LatLngBounds = directionsPolyline.getLatLngBounds(); map.setCenter(directionsBounds.getCenter()); map.setZoom(map.getBoundsZoomLevel(directionsBounds));
                                  var startLatLng:LatLng = dir.getRoute(0).getStep(0).latLng;
                                  var endLatLng:LatLng = dir.getRoute(directions.numRoutes-1).endLatLng; map.addOverlay(new Marker(startLatLng)); map.addOverlay(new Marker(endLatLng));
                      for (var r:Number = 0 ; r < directions.numRoutes; r++ ) { var route:Route = directions.getRoute(r); for (var s:Number = 0 ; s < route.numSteps; s++ )
                      { var step:Step = route.getStep(s); directionsSteps.addItem(step);
                  }
              }
                                      directionsSteps.removeAll();
                                      itemClick="onGridClick(event)"
                                      privatefunction onGridClick(event:Event):void { var latLng:LatLng = directionsGrid.selectedItem.latLng;
                                          var opts:InfoWindowOptions = new InfoWindowOptions(); opts.contentHTML = directionsGrid.selectedItem.descriptionHtml; map.openInfoWindow(latLng, opts);
                                      }
                                          var ServerPath:String = "http://www.sometext.com/";
                                          var ServerPage:String = serverPath + "getCountries";
                                          }
                                                  dataProvider="{directionsSteps}"
                                                  var directions:Directions = new Directions(); directions.addEventListener(DirectionsEvent.DIRECTIONS_SUCCESS, onDirectionsSuccess); directions.addEventListener(DirectionsEvent.DIRECTIONS_FAILURE, onDirectionsFail);
                                                  directions.load("from: " + from.text + " to: " + to.text);
                                                  Alert.show("Status:" + event.directions.status);
                                                  map.clearOverlays(); var directions:Directions = event.directions; var directionsPolyline:IPolyline = directions.createPolyline();
                                                  map.addOverlay(directionsPolyline);
                                                  var directionsBounds:LatLngBounds = directionsPolyline.getLatLngBounds(); map.setCenter(directionsBounds.getCenter());
                                                  map.setZoom(map.getBoundsZoomLevel(directionsBounds));
                                                  var startLatLng:LatLng = dir.getRoute(0).getStep(0).latLng; var endLatLng:LatLng = dir.getRoute(directions.numRoutes-1).endLatLng; map.addOverlay(new Marker(startLatLng));
                                                  map.addOverlay(new Marker(endLatLng));
                                                  for (var r:Number = 0 ; r < directions.numRoutes; r++ ) { var route:Route = directions.getRoute(r); for (var s:Number = 0 ; s < route.numSteps; s++ )
                                                  { var step:Step = route.getStep(s); directionsSteps.addItem(step); } }
                                                  directionsSteps.removeAll();
                                                  itemClick="onGridClick(event)"
                                                                  }
                                                              }                       
                          import flash.events.IOErrorEvent;
                          import flash.events.SecurityErrorEvent;
                                      var sender:URLLoader;
                                      var sendPage:URLRequest;
                                      var sendVars:URLVariables;
                                           initApp;
                                          function initApp:void {
                                      var ServerPath:String = "http://localhost/silverfoxcc/";
                                      var url:String = serverPath + "login.aspx";
                                      sender = new URLLoader();
                                      sendPage = new URLRequest(url);
                                      sendPage.method = URLRequest.POST;
                                      sendvars = new URLVariables();
                                      SUBMIT.btn.addEventListener(MouseEvent.CLICK, clickHandler);
                                      sender.addEventListener(Event.COMPLETE, completeHandler);
                                      sender.addEventListener(IOErrorEvent.SECURITY_ERROR, securityErrorhandler);
                                      }
                                                  function clickhandler(e:MouseEvent:void{
                                                      var suppSUBMIT:String = username_txt.text;
                                                      var suppRESET:String = reset_txt.text;
                                                      if (suppSUBMIT.length > 0 && suppRESET.length > 0) {
                                                          message_txt.text = "";
                                                          sendVars.submit = suppSUBMIT;
                                                          sendVars.reset = suppRESET;
                                                          sendPage.data = sendVars;
                                                          sender.load(sendPage);
                                                      }
                                                      else{
                                                          message_txt.text ="You must enter a last name and customer identification before clicking the submit button."
                                                      }
                                                  }
                                                    function completeHandler(e:Event):void{
                                                        var xmlResponse:XML = XML(e.target.data;
                                                            var userMessage:String;
                                                            if (xmlResponse.text().toString() == "true") {
                                                                userMessage = "Congratulations, information is retrieved"'';
                                                                 }
                                                            else {
                                                                usermessage = "Information to be retrieved failed. Please try again";
                                                                                }
                                                                                message_txt.text =userMessage;
                                                                        }
                                                                        function ioErrorHandler(e:IOErrorEvent):void{
                                                                            message_txt.text = e.text;
                                                                        }
                                                                        function securityErrorHandler(e:SecurityErrorEvent):void {
                                                                            message_txt.text = e.text;
                                                                        }
                                                                   }
                                                               /**Foundation for Ed: XML & E4X-Chapter 9: COMMUNICATION WITH THE SERVER*/
                                                                import mx.events.FlexEvent;
                                                                import xmlUtilities.XMLLoader;
                                                                import flash.events.IOErrorEvent;
                                                                import flash.events.SecurityErrorEvent
                                                                private var serverPath:String = "http://localhost/FOE/";
                                                                private function initApp(e:FlexEvent):void {
                                                                    myXMLLoader = new XMLLoader();
                                                                    myXMLLoader.addEventListener(Event.COMPLETE, completeHandler);
                                                                    myXMLLoader.addEventListener(IOErrorEvent.IO_Error, IOErrorHandler);
                                                                    SUBMIT.btn.addEventListener(MouseEvent.CLICK, clickHandler);
                                                                            }
                                                                            private function completeHandler(e:Event):void{
                                                                                var userMessage:String;
                                                                                var response:String =myXMLLoader.response().toString();
                                                                                if (response:String = myXMLLoader.response().toString();
                                                                                    if (response == true"){
                                                                                           usermessage = "Congratualtions. You were successful";
                                                                            }
                                                                                                else{
                                                                                              userMessage = Login failed. Please try again";
                                                                                              )
                                                                                        message_txt.text = userMessage;
                                                                            }
                                                                                    private function clickHandler(e:MouseEvent):void{
                                                                                        var SUBMIT:String = submit_txt.text;
                                                                                        var RESET:String = reset_txt.text;
                                                                                        vars myVars:URLVariables = new URLVariables();
                                                                                        if (username.length > 0 && password.length > 0) {
                                                                                            myVars.SUBMIT = submit;
                                                                                            myVars.CUSTMER ID = customerid;
                                                                                            myXMLLOADER.loafxml("login.aspx, myVars);
                                                                              }
                                                                                              else {
                                                                                               message_txt.text = "You must enter a last name and customer id before clicking the submit button"
                                                                                    }
                                                                                   }
                                                                                    private function IOErrorHandler(e:IOErrorEvent):void{
                                                                                        message_txt.text = e.text;
                                                                                    }
                                                                                    private function securityErrorHandler(e:SecurityErrorEvent):void{
                                                                                        message_txt.text = e.text;
                                                                            }
                                                                      }
                                                                              /**Foundation for Ed: XML & E4X-Chapter 8: MODIFYING XML CONTENT WITH ACTIONSCRIPT 3.0*/
                                                                                  import mx.events.FlexEvent;
                                                                                  import mx.events.ListEvent;
                                                                                  import mx.collections.XMLListCollection;
                                                                                  import xmlUtilities.MyXMLLoaderHelper;
                                                                                  import mx.events.FlexEvent;
                                                                                  import mx.events.DataGridEvent;
                                                                                  private function initApp(e:Event):void {
                                                                                  /add testing lines here
                                                                                  }
                                                                                              private var myXMLLoader:MyXMLLoaderHelper;
                                                                                              private function initApp(e:FlexEvent):void {
                                                                                                   myXMLLoader = new MyXMLLoaderHelper();
                                                                                                   myXMLLoader.addEventListener(Event.COMPLETE, completeHandler);
                                                                                                   myXMLLoader.addEventListener("xmlUpdated", xmlUpdatedHandler);
                                                                                                   authors_cbo.addEventListener(ListEvent.CHANGE, changeHandler);
                                                                                                   addRow_btn.addEventListener(MouseEvent.CLICK, addClickHandler);
                                                                                                   delete_btn.addEventListener(MouseEvent.CLICK, deleteClickHandler);
                                                                                                   books_dg.addEventListener(DataGridEvent.ITEM_EDIT_END, itemEditEndHandler);
                                                                                                   authors_cbo.labelFunction = getFullName;
                                                                                                   myXMLLoader.loadXML("Assets/customer_info.xml", "lastname");
                                                                                              }
                                                                                              private function completeHandler(e:Event):void {
                                                                                                   authors_cbo.dataProvider = myXMLLoader.getChildElements("author");
                                                                                                   tree_txt.text = myXMLLoader.getXML().toXMLString();
                                                                                                   books_dg.dataProvider = myXMLLoader.getBooks(0);
                                                                                              }
                                                                                              private function getFullName(item:Object):String {
                                                                                                return item.authorFirstName + " " + item.customerLastName;
                                                                                              }
                                                                                              private function changeHandler(e:Event):void {
                                                                                                   books_dg.dataProvider = myXMLLoader.getBooks(e.target.selectedIndex);
                                                                                              }
                                                                                              private function addClickHandler(e:MouseEvent):void {
                                                                                                var newBookName:String = name_txt.text;
                                                                                                var newPublishYear:String = year_txt.text;
                                                                                                var newBookCost:String = cost_txt.text;
                                                                                                var authorIndex:int = authors_cbo.selectedIndex;
                                                                                                if(newBookName.length > 0 && newPublishYear.length > 0 && newBookCost.length > 0) {
                                                                                                   myXMLLoader.addBook(authorIndex, newBookName, newPublishYear, newBookCost);
                                                                                                }
                                                                                              }
                                                                                              private function deleteClickHandler(e:MouseEvent):void {
                                                                                                var bookIndex:int = books_dg.selectedIndex;
                                                                                                var authorIndex:int = authors_cbo.selectedIndex;;
                                                                                                if (books_dg.selectedIndex != -1) {
                                                                                                   myXMLLoader.deleteBook(authorIndex, bookIndex);
                                                                                                }
                                                                                              }
                                                                                              private function itemEditEndHandler(e:DataGridEvent):void {
                                                                                                var authorIndex:int = authors_cbo.selectedIndex;
                                                                                                var dg:DataGrid = e.target as DataGrid;
                                                                                                var field:String = e.dataField;
                                                                                                var row:int = e.rowIndex;
                                                                                                var col:int = e.columnIndex;
                                                                                                var oldVal:String = e.itemRenderer.data[field];
                                                                                                var newVal:String = dg.itemEditorInstance[dg.columns[col].editorDataField];
                                                                                                if (oldVal != newVal) {
                                                                                                     myXMLLoader.modifyXMLTree(authorIndex, dg.columns[col].dataField, row, newVal)
                                                                                                }
                                                                                              }
                                                                                              private function xmlUpdatedHandler(e:Event):void {
                                                                                                   books_dg.dataProvider = myXMLLoader.getBooks(authors_cbo.selectedIndex);
                                                                                                   tree_txt.text = myXMLLoader.getXML().toXMLString();
                                                                                              }

       

              ]]>
          </mx:Script>
         
          <s:Panel x="9" y="257" width="459" height="383" contentBackgroundColor="#666666" backgroundColor="#666666" chromeColor="#FCF6F6" title="DIRECTIONS TO SILVER FOX COLLISION CENTER:" fontSize="14">
              <s:TextInput x="55" y="7" contentBackgroundColor="#030000" height="17" width="392"/>
              <mx:Label x="3" y="6" text="FROM:" fontSize="14" color="#FDF9F9"/>
              <s:TextInput x="1114" y="637" contentBackgroundColor="#FCF7F7" height="17" width="213"/>
              <s:Button x="1337" y="634" label="GET DIRECTIONS" focusColor="#FBFCFD" chromeColor="#666666" color="#FEFEFE" width="141" fontSize="14"/>
              <mx:Label x="1088" y="637" text="TO:" fontSize="12" color="#FDFBFB"/>
              <s:Button x="295" y="56" label="GET DIRECTIONS" focusColor="#FBFCFD" chromeColor="#666666" color="#FEFEFE" width="157" fontSize="12"/>
              <s:TextInput x="55" y="31" contentBackgroundColor="#070000" height="17" width="392"/>
              <mx:Label x="25" y="30" text="TO:" fontSize="14" color="#FDFBFB"/>
          </s:Panel>
          <mx2:DataGrid x="10" y="54" width="458" height="104" color="#666666" contentBackgroundColor="#060000" borderColor="#030000" fontSize="8" focusColor="#666666" chromeColor="#030000" selectionColor="#666666" dropShadowVisible="true" rollOverColor="#FFFFFF">
              <mx2:columns>
                  <mx2:DataGridColumn headerText="LAST NAME:" dataField="col1"/>
                  <mx2:DataGridColumn headerText="DESIGNATED DUE DATE:" dataField="col2"/>
                  <mx2:DataGridColumn headerText="STATUS UPDATED:" dataField="col3"/>
                  <mx2:DataGridColumn headerText="CUSTOMER ID:" dataField="col3"/>
              </mx2:columns>
          </mx2:DataGrid>
          <mx:Text id="directionsSummary" width="100%"/> <mx:DataGrid id="directionsGrid" dataProvider="{directionsSteps}" width="100%" height="100%" sortableColumns="false" />
          <mx:Text id="directionsCopyright" width="100%"/>
          <mx:HBox> <mx:Label text="From: " width="70"/> <mx:TextInput id="from" text="San Francisco, CA" width="100%"/> </mx:HBox>
          <mx:HBox> <mx:Label text="To: " width="70"/> <mx:TextInput id="to" text="Mountain View, CA" width="100%"/> </mx:HBox>
          <s:Label x="11" y="38" text="LAST NAME:" color="#FCFBFB" fontSize="14" verticalAlign="top"/>
          <s:TextArea x="96" y="32" width="145" height="18" focusColor="#FCFAFA" color="#010000" contentBackgroundColor="#000000" id="message_txt" text="{xmlService.lastResult.toString()}>
          <s:Label x="273" y="37" text="CUSTOMER ID;" fontSize="14" color="#FDFBFB"/>
          <s:TextInput x="376" y="32" width="89" height="18" focusColor="#FCF9F9" color="#FAF8F8" contentBackgroundColor="#040000"/>
          <s:Button x="318" y="212" label="RESET" focusColor="#F8FAFB" color="#FEFBFB" chromeColor="#666666" fontSize="12"/>
          <s:Button x="393" y="212" label="SUBMIT" focusColor="#F8F9FA" color="#FFFBFB" chromeColor="#666666" fontSize="12"/>
          <s:TextArea x="10" y="160" width="458" height="48" color="#FEF8F8" contentBackgroundColor="#050000"/>
          <mx:Panel x="483" y="31" width="750" height="609" layout="absolute" backgroundColor="#666666" borderVisible="true" dropShadowVisible="true" chromeColor="#FDF9F9">
              <mx:VBox x="26" y="7" height="559" width="708">
                  <maps:Map xmlns:maps="com.google.maps.*" id="map" mapevent_mapready="onMapReady(event)" x="500" y="25" width="700" height="550" key="ABQIAAAA9YXHa-b0xqHBMiooUNYUbhRpa9TAnukyOWjhoGl3Y9H2BJoi9xSrm6cnM0lBZ4lCtqRLxKpQK_eb Rg" sensor="true"/>
              </mx:VBox>
          </mx:Panel>
      </mx:Application>

       

       

      /**the AIR APPLICATION*/

      <?xml version="1.0" encoding="utf-8"?>
      <s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
                             xmlns:s="library://ns.adobe.com/flex/spark"
                             xmlns:mx="library://ns.adobe.com/flex/mx" backgroundColor="#666666" width="854" height="348" creationComplete="initApp(event)">
          <s:HTTPService id="customer_info" url="data/customer_info.xml" resultFormat="e4x" result="resultHandler(event)"/>
          <mx:Script>
              <![CDATA[
              /**FLEX 4 Bible: Chapter 24- Managing XML w/ E4X*/
              private var xmlData:XML;
              private function resultHandler(event:ResultEvent):void
              {
                  xmlData = event.result as XML:
              }
              ]]>
          </mx:Script>
          <fx:Declarations>
              <!-- Place non-visual elements (e.g., services, value objects) here -->
          </fx:Declarations>
          <mx:Image source="@Embed('Assets/logo.png')" x="1" y="0" width="760" height="168"/>
          <s:Label x="96" y="126" text="Last Name:&#xd;" color="#FFFFFF" fontSize="20" fontFamily="Times New Roman"/>
          <s:Label x="13" y="218" text="Designated Due Date:&#xd;" fontSize="20" fontFamily="Times New Roman" color="#FBF8F8"/>
          <s:Label x="63" y="186" text="Status Updated:&#xd;" color="#FCF5F5" fontSize="20" fontFamily="Times New Roman"/>
          <s:TextInput x="192" y="125" width="196"/>
          <s:TextInput x="193" y="215" width="195"/>
          <s:TextInput x="193" y="185" width="195"/>
          <s:Label x="80" y="158" text="Customer ID:" color="#FDFCFC" fontSize="20" fontFamily="Times New Roman"/>
          <s:TextInput x="192" y="155" width="196"/>
          <s:Button x="243" y="241" label="RESET"/>
          <s:Button x="317" y="241" label="UPDATE" focusColor="#666666"/>
      </s:WindowedApplication>

       

      /**the Customer Information XML*/

      <?xml version="1.0" encoding="utf-8"?>
          <allNames>
              <name namesID="1">
                  <nameLastName>Ambrose</nameLastName>
                  <customerids>
                      <customerid customerID="1">
                          <customerID>777777</customerID>
                      </customerid>
                  </customerids>