Monday, October 18, 2010

How to include captcha in flex

Process of creating simple captcha in flex

1) Create a flex project - 'mycaptcha'
2) create a module - 'CCaptcha.mxml'
3) create a canvas inside CCaptcha.mxml
4) create a folder inside the project and name it as "Fonts"
5) copy some font files(.ttf file) inside Font folder
it is better to use entirely different font styles, like ( arial, comic, Impact ,etc)
6) Create a style tag inside the ccaptcha.mxml module

@font-face { src:url("../Font/arial.ttf"); fontFamily: arial; } @font-face { src:url("../Font/arial.ttf"); fontFamily: Fear; } @font-face { src:url("../Font/comic.ttf"); fontFamily: comic; } @font-face { src:url("../Font/Impact .ttf"); fontFamily: Impact ; }

7) create 5 label box , and Fill each label with random charachter
8) add the labels inside canvas object
9) create some line object with random x,y coordinate and add inside the canvas , like line object you can use circle , polygon

you can use this module inside your project by adding it from "custom" components view

Sample Code :



<?xml version="1.0" encoding="utf-8"?>
<mx:Module xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="init();" width="250" height="60">
<mx:Canvas x="0" y="0" width="250" height="60" backgroundColor="#FFFFFF" id="CaptchaCanvas" borderStyle="outset">
</mx:Canvas>
<mx:Style>
@font-face {
src:url("../Font/ka1.ttf");
fontFamily: ka1;
}
@font-face {
src:url("../Font/Fear.ttf");
fontFamily: Fear;
}
@font-face {
src:url("../Font/DimWitRight.ttf");
fontFamily: DimWitRight;
}
@font-face {
src:url("../Font/CornFed.ttf");
fontFamily: CornFed;
}
@font-face {
src:url("../Font/Backto1982.ttf");
fontFamily: Abbeyline;
}
@font-face {
src:url("../Font/Abbeyline.ttf");
fontFamily: Backto1982;
}
@font-face {
src:url("../Font/Advert-Regular.ttf");
fontFamily: AdvertRegular;
}
@font-face {
src:url("../Font/AeroviasBrasilNF.ttf");
fontFamily: AeroviasBrasilNF;
}
@font-face {
src:url("../Font/arial.ttf");
fontFamily: Arial;
}
</mx:Style>
<mx:Script>
<![CDATA[
import mx.formatters.SwitchSymbolFormatter;
import flash.sampler.NewObjectSample;
import mx.effects.Rotate;
import flash.net.sendToURL;
import mx.controls.Alert;
import mx.controls.Label;
import mx.core.UIComponent;
import mx.core.UIComponent;
import flash.geom.ColorTransform;

private var CAPTCHA_WIDTH:Number;
private var CAPTCHA_HEIGHT:Number;
private var alphaU:String="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public var alphaUpper:Boolean=true;
public var alphaLower:Boolean=true;
public var numbers:Boolean=false;
public var specialChar:Boolean=false;
private var alphaL:String="abcdefghijklmnopqrstuvwxyz";
private var numeric:String="0123456789";
private var specialC:String="@#$%&*?";
private var randomSource:String;
public var code:String;
public var caseSensitive:Boolean=false;
public var hLine:Boolean=true;
public var vLine:Boolean=true;
public var dots:Boolean=true;
public var randomBGColor:Boolean=true;
public var backColor:String="0xFFFFFF";

//DOTS
public var DOTS_COUNT:Number=500;

//TEXT
public var fontface:Array = new Array("ka1", "Fear", "DimWitRight", "CornFed", "Abbeyline", "Backto1982", "ActionIs", "AdvertRegular", "AeroviasBrasilNF","Arial");

public var LINE_COLOR_ARRAY:Array = new Array("0x000066","0x006666","0x660000","0x006600","0x660066","0x663366","0x666066");
public var BACK_COLOR_ARRAY:Array = new Array("0x357EC7","0x9172EC","0xF778A1","0xB93B8F","0x817679","0x999900","0xFF3399");

public var CHAR_MINSPACE:int;
public var CHAR_MIN_Y:int;
public var CODE_LENGHT:int=5;

private function init():void{
CAPTCHA_WIDTH=CaptchaCanvas.width;
CAPTCHA_HEIGHT=CaptchaCanvas.height;
CHAR_MIN_Y=12;
//DOTS_COUNT=500;
CHAR_MINSPACE=40;
//CODE_LENGHT=5;
CaptchaCanvas.verticalScrollPolicy="off";
CaptchaCanvas.horizontalScrollPolicy="off";
}

private function drowHline(maxLnwidth:int, colorArray:Array, maxLnAlpha:Number, LnCount:int, canvas:UIComponent){
var line:Sprite = new Sprite();
var lcount:int;
var c1:UIComponent = new UIComponent();
for(lcount=0;lcount<LnCount;lcount++){
line.graphics.lineStyle(Math.random()*maxLnwidth, LINE_COLOR_ARRAY[Math.ceil(Math.random()*LINE_COLOR_ARRAY.length -1 )], maxLnAlpha);
line.graphics.moveTo(1,Math.random()*CAPTCHA_HEIGHT);
line.graphics.lineTo(CAPTCHA_WIDTH,Math.random()*CAPTCHA_HEIGHT);
}
c1.addChild(line);
CaptchaCanvas.addChild(c1);
}
public function generateCaptcha():void{
ClearCanvas();

if(dots)
generateDots(CaptchaCanvas);
if(vLine)
drawLines(0, 0, (CAPTCHA_WIDTH)-1, (CAPTCHA_HEIGHT)-1, 5, 5,CaptchaCanvas);
if(hLine)
drowHline(5,LINE_COLOR_ARRAY,.2,5,CaptchaCanvas);
if(randomBGColor)
CaptchaCanvas.setStyle("backgroundColor",BACK_COLOR_ARRAY[Math.ceil(Math.random() * BACK_COLOR_ARRAY.length - 1)].toString());
else
CaptchaCanvas.setStyle("backgroundColor",backColor.toString());

var chr1:Label = new Label();
var chr2:Label = new Label();
var chr3:Label = new Label();
var chr4:Label = new Label();
var chr5:Label = new Label();

randomSource="";
if(alphaUpper)
randomSource=randomSource+alphaU;
if(alphaLower)
randomSource=randomSource+alphaL;
if(numbers)
randomSource=randomSource+numeric;
if(specialChar)
randomSource=randomSource+specialC;
if(randomSource.length<5)
randomSource=alphaL+alphaU;

code=randomSource.charAt(Math.ceil(Math.random()*randomSource.length-1)) +
randomSource.charAt(Math.ceil(Math.random()*randomSource.length-1)) +
randomSource.charAt(Math.ceil(Math.random()*randomSource.length-1)) +
randomSource.charAt(Math.ceil(Math.random()*randomSource.length-1)) +
randomSource.charAt(Math.ceil(Math.random()*randomSource.length-1));

chr1.text=code.charAt(0);
chr1.x=40;
chr1.y=Math.random() * CHAR_MIN_Y;
chr1.rotation = Math.random() * 50;
chr1.setStyle("fontFamily",fontface[9].toString());
chr1.setStyle("color","#000000");
chr1.setStyle("fontSize","40");
CaptchaCanvas.addChild(chr1);

chr2.text=code.charAt(1);
chr2.x=chr1.x + CHAR_MINSPACE;
chr2.y=Math.random() * CHAR_MIN_Y;
chr2.rotation = Math.random() * 50;
chr2.setStyle("color","#000000");
chr2.setStyle("fontSize","40");
chr2.setStyle("fontFamily",fontface[9].toString());
CaptchaCanvas.addChild(chr2);

if(CODE_LENGHT>=3){
chr3.text=code.charAt(2);
chr3.x=chr2.x + CHAR_MINSPACE;
chr3.y=Math.random() * CHAR_MIN_Y;
chr3.rotation = Math.random() * 50;
chr3.setStyle("color","#000000");
chr3.setStyle("fontSize","40");
chr3.setStyle("fontFamily",fontface[9].toString());
CaptchaCanvas.addChild(chr3);
}

if(CODE_LENGHT>=4){
chr4.text=code.charAt(3);
chr4.x=chr3.x+CHAR_MINSPACE;
chr4.y=Math.random() * CHAR_MIN_Y;
chr4.rotation = Math.random() * 50;
chr4.setStyle("color","#000000");
chr4.setStyle("fontSize","40");
chr4.setStyle("fontFamily",fontface[9].toString());
CaptchaCanvas.addChild(chr4);
}

if(CODE_LENGHT>=5){
chr5.text=code.charAt(4);
chr5.x=chr4.x+CHAR_MINSPACE;
chr5.y=Math.random() * CHAR_MIN_Y;
chr5.rotation = Math.random() * 50;
chr5.setStyle("color","#000000");
chr5.setStyle("fontSize","40");
chr5.setStyle("fontFamily",fontface[9].toString());
CaptchaCanvas.addChild(chr5);
}
}

private function generateDots(canvas:UIComponent):void
{
for (var a:int=0; a < DOTS_COUNT; a++) {
var tmpComponent:UIComponent = new UIComponent();
var X:int = Math.ceil(Math.random()* (CAPTCHA_WIDTH-10))+5;
var Y:int = Math.ceil(Math.random()* (CAPTCHA_HEIGHT-10))+5;
tmpComponent.graphics.lineStyle(Math.floor(Math.random()*5),
RGBToHex(Math.floor(Math.random()*255),
Math.floor(Math.random()*255),
Math.floor(Math.random()*255)),
100);
tmpComponent.graphics.moveTo(X, Y);
tmpComponent.graphics.lineTo(X+1, Y);
canvas.addChild(tmpComponent);
}
}
private function RGBToHex (r:uint, g:uint, b:uint):uint {
var hex:uint = r << 16 ^ g << 8 ^ b;
return hex;
}

private function ClearCanvas():void{
CaptchaCanvas.removeAllChildren();
}

private function generatePolys(no:uint,canvas:UIComponent):void{
for (var i:uint = 0; i < no; i++) {
var tmpComponent:UIComponent = new UIComponent();
var tmpRadius:int = Math.floor(Math.random()*40)+10;
tmpComponent = generateOnePoly(Math.floor(Math.random()*6)+3, tmpRadius,
RGBToHex(Math.floor(Math.random()*255),
Math.floor(Math.random()*255),
Math.floor(Math.random()*255)));
tmpComponent.x = Math.floor(Math.random()*CAPTCHA_WIDTH);
tmpComponent.y = Math.floor(Math.random()*CAPTCHA_HEIGHT);
tmpComponent.rotation = Math.floor(Math.random()*360);
tmpComponent.alpha = 0.3;
canvas.addChild(tmpComponent);
}
}

private function generateOnePoly(sides:uint, radius:uint, color:uint):UIComponent {
var tmpCmp:UIComponent = new UIComponent();
var DSides:uint = Math.floor(360/sides);
//Highest transparency is 100 - default is 50
tmpCmp.graphics.beginFill(color, 50);
var cnt:int = -1;

while (++cnt < sides) {
var X:int = Math.floor(radius*Math.sin(DSides*cnt/180*Math.PI));
var Y:int = Math.floor(radius*Math.cos(DSides*cnt/180*Math.PI));
if (!cnt) {
tmpCmp.graphics.moveTo(X, Y);
} else {
tmpCmp.graphics.lineTo(X, Y);
}
}
return tmpCmp;
}

private function drawLines(x:int, y:int, wi:int, hi:int, r:int, c:int, canvas:UIComponent):void {
var tmpComponent:UIComponent = new UIComponent();
tmpComponent.graphics.lineStyle(1, 0x333333, .8);
var i:int = 0;
var xd:Number = wi/c;
var yd:Number = hi/r;
for (i=0; i<= r; i++) {
var yy:Number = y+i*yd;
tmpComponent.graphics.moveTo(x+wi, yy);
tmpComponent.graphics.lineTo(x, yy);
}
for (var j:int=0; j < c; j++) {
var xx:Number = x+j*xd;
tmpComponent.graphics.lineTo(xx, y);
tmpComponent.graphics.lineTo(xx+xd, y+hi);
}
tmpComponent.graphics.lineTo(x+wi, y);
canvas.addChild(tmpComponent);
}
public function checkcaptcha(targetCode:String):Boolean{
if(targetCode.length<2)
return false;
if(caseSensitive){
if(code.substr(0,CODE_LENGHT)== targetCode.substr(0,CODE_LENGHT))
return true;
else
return false;
}
else{
if(code.substr(0,CODE_LENGHT).toLocaleLowerCase()== targetCode.substr(0,CODE_LENGHT).toLocaleLowerCase())
return true;
else
return false;
}
}
private function radiansToDegrees(radians:Number):Number {
var degrees:Number = radians * (180 / Math.PI);
return degrees;
}
private function degreesToRadians(degrees:Number):Number {
var radians:Number = degrees * (Math.PI / 180);
return radians;
}
]]>
</mx:Script>
</mx:Module>

ScreenShot:



Wednesday, April 29, 2009

How to load Youtube videos in Flex

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="prepareBridge()">
<mx:VBox horizontalAlign="center">
<mx:Button
label="Load Youtube"
click="load()"
height="10%" width="130"/>
<mx:Box
id="panel"
width = "100%"
height = "90%"/>
</mx:VBox>
<mx:Script>
<![CDATA[
import mx.controls.SWFLoader;

private var counter:Number = 0;
private var outBox:LocalConnection;
private var outBoxName:String;

private function load():void {
outBox.send(outBoxName, "dispose");
outBox.send(outBoxName, "loadMovie", "hZ9VHzTMwr8");
}

private function prepareBridge():void {
outBox = new LocalConnection();
outBox.addEventListener(StatusEvent.STATUS, function(event:StatusEvent):void {
switch (event.level) {
case "status":
trace("LocalConnection.send succeeded");
break;
case "error":
trace("LocalConnection.send failed");
break;
}
});

var swfLoader:SWFLoader = new SWFLoader();
swfLoader.addEventListener(Event.COMPLETE, onInitialize);
swfLoader.addEventListener(flash.events.IOErrorEvent.IO_ERROR , onLoaderIoError);
swfLoader.autoLoad = true;
swfLoader.percentWidth = 100;
swfLoader.percentHeight = 100;
swfLoader.scaleContent = true;
swfLoader.maintainAspectRatio = true;
outBoxName = String(new Date().getUTCMilliseconds());
swfLoader.load("youtubebridge.swf?boxName=" + outBoxName);
panel.addChild(swfLoader);
}

private function onInitialize(event:Event):void {
}

private function onLoaderIoError(event:IOErrorEvent):void {
trace( 'onLoaderIoError: ' + event );
}
]]>
</mx:Script>
</mx:Application>



Two more file to be included in the working directory

youtubebridge.fla
youtubebridge.swf

Sunday, March 15, 2009

How to play mp3 from Flex

<?xml version="1.0" encoding="utf-8"?><mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" >
<mx:Button x="221" y="181" label="Play" width="99" height="26" click="playSound()"/> <mx:Button x="221" y="281" label="Stop" width="99" height="26" click="stopSound()"/> <mx:Script>
<![CDATA[
import flash.trace.Trace;
import mx.core.SoundAsset;
import flash.media.*;
import mx.controls.Alert;

[Embed(source="media/KissfromaRose.mp3")]
[Bindable] public var Song:Class;

public var mySong:SoundAsset = new Song() as SoundAsset;
public var channel:SoundChannel;

public function playSound():void {
// Make sure we don't get multiple songs playing at the same time
stopSound();
// Play the song on the channel channel = mySong.play();
}

public function stopSound():void {
// Stop the channel, but only if it exists
if ( channel != null )
channel.stop();
}
]]>
</mx:Script>
</mx:Application>


How to call Webservice from flex

<![CDATA[
import mx.rpc.events.FaultEvent;
import mx.managers.CursorManager;
import flash.trace.Trace;
import mx.controls.Alert;
import mx.rpc.events.ResultEvent;
import mx.rpc.soap.WebService;

private function callSOAP():void{
var service:WebService = new WebService();
service.wsdl = "http://localhost:8080/webproject/services/UserLogin?wsdl";
service.getUserdetails.addEventListener("result",userDetailsResultfunction);
service.loadWSDL();
service.getUserdetails("argument1","argument2");
}
private function userDetailsResultfunction(event:ResultEvent):void{
var xmlResult:XML;
xmlResult = XML(event.result);
Alert.show("Result : " + xmlResult.toString());
}
]]>

Monday, February 9, 2009

Flex Basic components - source code

How to use Basic components, like button, combo box, grid, MessageBox(Alert Box), Radio Button, CheckBox, Text Box etc in Adobe Flex.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="632" height="291" creationComplete="init()">
<mx:Button x="479" y="25" label="Add to Grid" click="btn_Click()"/>
<mx:CheckBox x="37" y="36" id="chk_box" label="Checkbox" click="checkbox_Click()"/>
<mx:ComboBox x="267" y="25" width="189" id="combo_id" prompt="select">
<mx:dataProvider>
<mx:String>data 1</mx:String>
<mx:String>data 2</mx:String>
<mx:String>data 3</mx:String>
<mx:String>data 4</mx:String>
<mx:String>data 5</mx:String>
<mx:String>data 6</mx:String>
<mx:String>data 7</mx:String>
<mx:String>data 8</mx:String>
<mx:String>data 9</mx:String>
<mx:String>data 10</mx:String>
</mx:dataProvider>
</mx:ComboBox>
<mx:RadioButtonGroup id="radiogroup1" change="radiobtn_Click()"/>
<mx:RadioButton x="37" y="66" label="Button 1" groupName="radiogroup1"/>
<mx:RadioButton x="37" y="92" label="Button 2" groupName="radiogroup1"/>
<mx:ProgressBar x="267" y="213" width="247" id="prg_id"/>
<mx:TextInput x="37" y="122" id="text_id" change="{label_id.text ='InputBox Value =' + text_id.text}"/>
<mx:DataGrid x="267" y="54" id="datagrid1">
<mx:columns>
<mx:DataGridColumn headerText="Column 1" dataField="slno"/>
<mx:DataGridColumn headerText="Column 2" dataField="cdata"/>
</mx:columns>
</mx:DataGrid>
<mx:Label x="37" y="152" text="Input box value" id="label_id"/>

<mx:Script>
<![CDATA[
import mx.messaging.messages.ErrorMessage;
import mx.collections.ArrayCollection;
import mx.controls.List;
public var arr:ArrayCollection=new ArrayCollection();
private var i:int;


import mx.controls.Alert;
private function init():void{
i=0;
prg_id.maximum=10;
}
private function checkbox_Click():void{
//if(chk_box.selected
Alert.show("Check box " + chk_box.selected);
}

private function radiobtn_Click():void{
Alert.show(" Radio " + radiogroup1.selectedValue + "selected");
}
private function btn_Click():void{
if(combo_id.selectedIndex==-1)
Alert.show("Please select a value from ComboBox" , "Flex Tutorial");
else{
var obj:Object=new Object();
Alert.show(combo_id.selectedItem.toString());
obj.cdata=combo_id.selectedItem;
obj.slno=i;
arr.addItem(obj);
datagrid1.dataProvider=arr;
prg_id.setProgress(i,10);
if(i < 11)
i++;

}
}
]]>
</mx:Script>

</mx:Application>

Output File

Monday, February 2, 2009

How to Start First Flex Application

Before starting the first program
Install latest JDK and Tomcat/Jboss Server
Install the Eclipse open source
Install flex 3 builders or Flex plug-in for eclipse

add flex plug-in to eclipse

Open eclipse
Select Help>>software updates>>Find and install

Select "Search for new features to install" proceed to next
click on "New local site" and select the Flex 3 plug-in path

eg:"X:\Program Files\Adobe\Flex Builder 3 Plug-in\com.adobe.flexbuilder.update.site"

goto file and create new "Flex project" name the project "Helloworld"

now a new file will be created
Helloworld.mxml

the file contain the following code
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">

</mx:Application>

goto "Design" mode
insert button to the project , then click on "source" mode
now the code is

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Button x="382" y="148" label="Button"/>

</mx:Application>

Create an id for the button and change its caption
and then add a function to the button, now the code become

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Button x="382" y="148" label="Click me" id="btn" click="clickedme()"/>
<mx:Script>
<![CDATA[
import mx.controls.Alert;
private function clickme():void{
Alert.show("Hello world");
}
]]>
</mx:Script>
</mx:Application>


now your first project is finished

to build the project, goto Project>>build Project
to run the project, goto Run>>Run as>> Flex Application

Friday, January 30, 2009

Adobe Flex Introduction

Adobe Flex is a cross platform rich internet application technology based on adobe flash platform. Flex technology released on March 2004, Flex 1.0.
in last of 2008 Abobe released the latest version of flex,- Flex 3.2.

Flex is a cross-platform development framework for creating Rich Internet Applications (RIAs), a component based tool that can use to develop apps that run using the Flash Player or Adobe Air. Flex is almost same as AJAX, JavaFX, Silverlight ( not exactly).flex can support data handling and GUI.

The flex source files are in the form of mxml and actionscript(as) file.it also support
cascading stye sheet(css).Flex offers both Remote Procedure Call (RPC) asynchronous communication and real-time communication features.

Example code

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">

<mx:Label x="10" y="10" text="Output" id="output"/>

<mx:Button x="10" y="36" label="Click Me" click="{output.text = 'Hello World'}"/>

</mx:Application>



The Flex framework proposes three RPC classes for communicating with the application server


1.HTTPServices

The HTTPService class makes HTTP(S) requests (mostly GET or POST) which may transport various content types, from simple URLencoded variables to more complex data like XML. Basically, this is the choice for Representational State Transfer (REST) web services architecture. Most of the time, an HTTPService object is used to communicate with a simple script or page like a JSP page, an ASP page or a PHP script. Obviously, the value of the HTTPService url property is the URL of this page.

The transported data is sent and received as plain text, meaning that you'll have to map the received data to the corresponding ActionScript data type on the Flex side, and to the corresponding server-side technology data type on the server side. Therefore, it may be a good idea to use a special data exchange format like JSON.

2.WebServices

The WebService class sends and receives SOAP messages over HTTP. Naturally, this is what you'll use to communicate with SOAP WebServices. To connect to this WebService and call its operations (i.e. its methods), you'll have to hook this object to the WebService's Web Service Definition Language (WSDL) by setting its URI as the wsdl property value.
All ActionScript primitive types and some built-in ActionScript complex types are automatically mapped from and to SOAP/XMLschema data. This process is handled on the Flex side, by the WebService class. This is quite an improvement over HTTPService-based communications where you have to do that job by yourself, or use third party libraries.


3.RemoteObjects

The RemoteObject class is responsible for sending and receiving ActionScript Message Format (AMF) data. This technique is also called Remoting.

AMF is not a transfer protocol: it is binary ActionScript. AMF3 is the binary format for AS3, whereas AMF0 was the binary format for AS1 and AS2