Search Flex Components Free

Custom Search
Showing posts with label Flex Data Services. Show all posts
Showing posts with label Flex Data Services. Show all posts

July 6, 2009

uploading an image into flash without server side script using flash player 10

The FileReference class in flash player 10 has a new method : FileReference.load() which provides the power of uploading the image, text file etc into flash player without any server side script.

Before proceeding with FileReference.load() method, we need to call FileReference.browse()method so that user can select a file to load a selected file into flash player. Once the file get loaded into flash player you can access the loaded data by using a property of FileReference.data.
The data loaded at FileReference.data property is commonly a type of ByteArray. we want to convert it to bitmap. so the trick is to use the loader class; loader.loadBytes() method. The method converts the ByteArray to a loader image object. once it completes loading we can add the loader object to display list to display the image. so here we go;

Note: the example has been created in flash cs4 and targets flash player 10;

settings:

1) create a blank flash document in flash cs4.

2) create a folder named with “flexScript” and copy and paste the below code to a new actionscript file and save the file into “flexScript” folder with the name “uploadImage”.

3) put a button component on the stage and put a instance name as “upload_Image”;

4) set the document class as “flexScript.uploadImage”; and run the application and check the magic;

  1. package flexScript {  
  2.     import flash.display.Sprite;  
  3.     import flash.events.MouseEvent;  
  4.     import flash.net.*;  
  5.     import flash.display.*;  
  6.     import flash.events.*;  
  7.     import flash.utils.ByteArray;  
  8.   
  9.     public class uploadImage extends Sprite {  
  10.         private var jagFileRefSave:FileReference = new FileReference();  
  11.         private var loader:Loader = new Loader();  
  12.         private var imagesFilter:FileFilter = new FileFilter("Images", "*.jpg;*.gif;*.png");  
  13.   
  14.     public function uploadImage(){  
  15.         super();  
  16.         upload_Image.addEventListener(MouseEvent.CLICK,onClickSave);  
  17.   
  18.     }  
  19.     private function onClickSave(e:MouseEvent):void{      
  20.         jagFileRefSave.browse([imagesFilter]);  
  21.         jagFileRefSave.addEventListener(Event.SELECT, selectedFile);  
  22.     }          
  23.     private function selectedFile(e:Event):void{  
  24.         jagFileRefSave.load();  
  25.         jagFileRefSave.addEventListener(Event.COMPLETE, loaded);  
  26.     }  
  27.     private function loaded(e:Event):void{  
  28.         var rawBytes:ByteArray = jagFileRefSave.data;  
  29.         loader.contentLoaderInfo.addEventListener(Event.COMPLETE, getBitmapData)  
  30.         loader.loadBytes(rawBytes);  
  31.     }  
  32.     private function getBitmapData(e:Event):void{  
  33.         addChild(loader);  
  34.     }  
  35.   
  36.     }  
  37. }  

Using a Web Service to populate a DataGrid with XML data

In this example I will be using XML data that is returned from a remote site. This example retrieves data about web sites (Name and URL). The XML data will be consumed and displayed in a FlexDataGrid control. Make sure you see the next blog about customizing a DataGrid. Here is a sample of the data returned by the program:



Google
http://google.com


Yahoo
http://yahoo.com



In this example, the data returned will be parsed and stored in an ArrayCollection object. Using an ArrayCollection is a good idea because it used in a lot of Flex tags as a data provider. It also include many methods that will allow you to manipulate the data. The following are the steps taken in Flex to retrieve the data and populate the DataGrid.
  1. Create the HttpService tag in Flex and link it to the XML source:
  2. url="http://some.examplewebsite.com/getSitesInXML.php"
    result="handleSiteData(event)" />

    id -- The name assigned to the service
    url -- is the source of the XML
    result -- Specify the name of the function that will handle the results. This function is called automatically. Incidentally, you can also add a method that will be invoked on errors (fault="someMethod()").
    resultFormat -- self explanatory.
  3. Send service request
  4. getSitesService.send();
    This is usually done upon application loading. For example, in the application tag you can add the code:
    applicationComplete="getSitesService.send();"
    Remember the method "handleSiteData()" will be called automatically upon successful return of the web service. Now, let's look at the method that will handle the returned result.

  5. Handle Site Data (Parse XML data)
    
    
    [Bindable]
    private var siteList:ArrayCollection;
    public function handleSiteData(event:ResultEvent):void {
    xmlData = XMLList(event.result);
    var siteArray:Array = new Array();
    for (var i:int = 0; i < xmlData.site.length(); i++) {
    //Create an object of type Site.
    //Site is a simple ActionScript class
    //that incldes a URL and a Name
    var s:Site = new Site(xmlData.site[i].URL,
    xmlData.site[i].Name);
    //Add the object to the array
    siteArray.push(s);
    }
    //Convert the array to an ArrayCollection
    siteList = new ArrayCollection(siteArray);
    }

    Now we have an 
    ArrayCollection of sites. This collection will be used as the "dataProvider" for the DataGrid control.

  6. Define the DataGrid Control to use the ArrayCollection "siteList" defined above.

January 5, 2008

Quickstart flex development with this maven archetype

Have you considered starting some flex development, but haven´t found out where to start? Or are you already flex'ing but could use some easy way to quickstart new flex projects in java?

I have created a maven archetype called maven-archetype-flex and distributed it to ibiblio for all to use.
It will quickly get you up and running.

Here is how you do it:

1. Download flex sdk
Download the flex sdk from adobe , if you haven't got it already.

1b. Minor change to flex-config.xml
You have to uncomment the following in your flex-config.xml located in:
${flex.home}/frameworks/flex-config.xml < local-fonts-snapshot > localFonts.ser < local-fonts-snapshot > Otherwise the compiler will complain as Matt mentions in his comment.

2. Create flex project
Running the following maven command will create a flex project called my-flex having groupId my.group . Feel free you change these to what ever you like:
mvn archetype : create
- DarchetypeArtifactId = maven - archetype - flex
- DarchetypeVersion = 1.0
- DarchetypeGroupId = dk . jacobve . maven . archetypes
- DgroupId = my . group
- DartifactId = my - flex
- DpackageName = Note: it is important that you remember the -DpackageName= as the Main.mxml flex file in the archetype is to be kept in the root of your source dir and not in some subpackage.

3. Set flex.home property
In the newly created project pom.xml you should change the flex.home property to fit your flex.home path.

4. Build flex project
Now you are ready to build the flex project:
mvn install Running this command inside your project will build the project and create a swf file in the target directory.

December 19, 2007

Loading XML at run-time using the mx:HTTPService tag

In the previous post we looked at how to load an XML document in at compile-time and have it embedded in our Flex application. But that technique really only works if the XML data in question never changes. What if you had an XML document that was constantly changing on a daily, or hourly, basis. For example, consider an RSS reader application. If the XML was loaded and embedded in the XML document at compile-time, the RSS would never get updated. And while that may be good in some cases (such as a kiosk, or somewhere without an internet connection where you wanted to display static information), in many cases it may not work.
So, lets take a look at using the mx:HTTPService tag to dynamically load an XML file.
The following example dynamically loads an XML file at run-time using the mx:HTTPService tag, rather than using mx:XML and grabbing the data at compile-time:

<?xml version="1.0" encoding="UTF-8" standalone="no" ? ><FLVCoreCuePoints version="1" >
<CuePoint > <Time >0</Time > <Type >event</Type > <Name >slide1</Name > <Parameters > <Parameter > <Name >id</Name > <Value >value</Value > </Parameter > </Parameters > </CuePoint >
<CuePoint > <Time >5000</Time > <Type >event</Type > <Name >slide2</Name > <Parameters > <Parameter > <Name >param1</Name > <Value >value1</Value > </Parameter > <Parameter > <Name >param2</Name > <Value >value2</Value > </Parameter > </Parameters > </CuePoint >
<CuePoint > <Time >20000</Time > <Type >event</Type > <Name >slide3</Name > </CuePoint >
</FLVCoreCuePoints ><?xml version="1.0" encoding="utf-8"? ><mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="top" backgroundColor="white" creationComplete="tempXML.send();" >
<mx:HTTPService id="tempXML" url="xml/cuePoints.xml" resultFormat="e4x" / > <mx:XMLListCollection id="cuePointXMLList" source="{tempXML.lastResult.CuePoint}" / > <mx:XMLListCollection id="parametersXMLList" source="{dataGrid.selectedItem.Parameters.Parameter}" / >
<mx:Script > <![CDATA[ private function parametersLabelFunction(item:Object, column:DataGridColumn):String { return item.Parameters.Parameter.length(); }
private function numericSortCompareFunction(objA:Object, objB:Object):int { var itemA:Number = parseInt(objA.Time.text()) as Number; var itemB:Number = parseInt(objB.Time.text()) as Number;
if (itemA > itemB) { return 1; } else if (itemA < itemB) { return -1; } else { return 0; } } ]] > </mx:Script >
<mx:VBox >
<mx:DataGrid id="dataGrid" dataProvider="{cuePointXMLList}" width="100%" rowCount="{cuePointXMLList.length + 1}" > <mx:columns > <mx:DataGridColumn id="timeCol" dataField="Time" headerText="Time (ms):" sortCompareFunction="numericSortCompareFunction" / > <mx:DataGridColumn id="typeCol" dataField="Type" headerText="Type:" / > <mx:DataGridColumn id="nameCol" dataField="Name" headerText="Name:" / > <mx:DataGridColumn id="parametersCol" dataField="Parameters" headerText="Parameters:" labelFunction="parametersLabelFunction" / > </mx:columns > </mx:DataGrid >
<mx:DataGrid id="parametersDataGrid" dataProvider="{parametersXMLList}" width="100%" visible="{parametersXMLList.length > 0}" rowCount="{parametersXMLList.length + 1}" > <mx:columns > <mx:DataGridColumn id="parameterNameCol" dataField="Name" headerText="Parameter Name:" / > <mx:DataGridColumn id="parameterValueCol" dataField="Value" headerText="Parameter Value:" / > </mx:columns > </mx:DataGrid >
</mx:VBox >
</mx:Application >The first thing you notice is that the code is nearly identical to the previous example which used mx:XML. The subtle differences are that instead of mx:XML we used mx:HTTPService to get the data. Also, we now listen for the creationComplete event for on the Application tag where we trigger the XML loading using the HTTPService.send() method. Finally, the locations of the files changed slightly. Now instead of the XML being calculated relative to the MXML file, the XML gets placed relative to the generated SWF file. All the other code stayed the same.

December 17, 2007

Flex Data Services Project Template

I just recently starting using Flash Develop 2.0. I was motivated by Keith Peter's ANT based project template that I created one for Flex Data Services. This tutorial is still in its early stages but I would like to get some feedback from other developer. This tutorial requires that you have Ant, Tomcat 5.5 and Flex Data Services installed. Flex Data Services Project Template Tutorial.

Flex Data Services - CRM Sample using Hibernate

I've played around a great deal with the sample applications that shipped with Flex Data Services. In particular I was intrigued in getting the CRM example to work with Hibernate. I'm not going to get too deep into the particulars. Here's just a good overview of what needed to be done or what purpose was served, by file.

samples\web-inf\web.xml
In this file there's a section of code that needs to be uncommented. This enables a servlet that runs when jrun boots up, which creates a file called hibernate.cfg.xml and puts it in the samples\web-inf\classes\samples folder.

samples\web-inf\classes\samples\hibernate.cfg.xml
Once you uncomment the web.xml and start up FDS once, this file should exist. In here you will see some basic configuration stuff that basically creates a jdbc connection to an hsqldb database (a java sql engine that runs within the context of the app server). Also you will not two mapping files, explained next.

samples\web-inf\classes\samples\crm\employee.hbm.xml
samples\web-inf\classes\samples\crm\company.hbm.xml
These two files serve to map sql tables & columns to java classes and properties, found in samples.crm.Employee and samples.crm.Company, respectively. You can find the source code for these files (if you're new to the java world like me) in samples\web-inf\src\(...)

samples\web-inf\flex\data-management-config.xml
In this file there are 2 sections that need to be uncommented out. You can leave the other destinations in place and just uncomment the destinations crm.employee.hibernate and crm.company.hibernate. Once you've saved these changes it's a good idea to restart FDS.

samples\dataservice\crm\companyapp.mxml
First go ahead and launch this in a browser, make sure FDS is running. The default address would be http://localhost:8700/samples/dataservice/crm/companyapp.mxml and make sure everything is still working fine. At this point the application is still using the custom company and employee assembler classes, not hibernate. If everything works fine, go ahead and edit the file. You'll need to find all the comments that pertain to Hibernate and then comment out the line preceding it, while uncommenting the line the line that follows, as per the comment instructions. Save your changes.

Now go ahead and reload the companyapp.mxml page in the browser. Keep the FDS console open and if everything went well, you can watch as hibernate generates and logs query statements.

Why Hibernate with Flex Data Services 2?

FDS 2 does not come without a learning curve, especially for those of us new to the Java world. I've been trying to find a way to speed things up, and at first I kind of ignored the whole Hibernate side of the equation. But eventually I got curious and I have to say, after tinkering around extensively... I'm pretty excited.

Hibernate has some pretty cool plugin tools for Eclipse/Flexbuilder . With these tools you can reverse-engineer all your hibernate xml mapping files and even the java object classes. What that means is that you can just focus on getting your db design done, and the tools will do the rest. Flex Data Services comes with the HibernateAssembler class, and with it they've done all the java coding for you. At least enough to get you started. What's even better is that in the fds2\resources\camples\assemblers, Adobe has thrown in the source code, so down the line you can modify and enhance it as needed.

In the end, all you need is a database with an Employee table, the hibernate.cfg.xml, the samples/crm/Employee.java and the samples/crm/Employee.hbm.xml files for the HibernateAssembler to work. Create the destinations in your data-management-config.xml and away you go - no Java required!

Flex to .Net via Flex Data Services - it is Possible!

When I first looked at Flex Data Services, I was a little disappointed to find that there was no built-in way to interface with .Net. Sure you can consume webservices directly from a Flex application however, you don't get the added conflict resolution, data push to client, etc stuff that comes with FDS. After toying around for a while I figured it had to be possible to access webservices through FDS, and eventually I did get it working.

Now there's no way I can cover all this in one blog entry. So I am going to try and split it up nicely:

Part one will only deal with coding the webservice in .Net in such a way that makes it interop-friendly. I will build a service that provides the basic CRUD and list functionality for a contacts table hosted in SQL server.

Part two will cover Apache Axis and the wsdl2java tool, and we will look at what code gets generated and hurdles other .Net folks might run into. Once we have our basic java console application up and running, and successfully consuming the .Net webservice, we'll move on to part 3.

In part three I will build a custom Assembler (extending the flex.data.assemblers.AbstractAssembler class. Then we'll create a destination for our new .Net webservice Assembler class.

In the fourth and final part of the series, I will build a Flex application with full list, modify, delete and add functionality, and takes advantage of the data management features of Flex Data Services 2.

Related Flex Tutorials