Hi,
It has been written for those who requested me to cover basic concept of AS3 so that they can learn and start development by themselves. It is a part of that series. I will cover next topic further.
About ActionScript:
ActionScript is the programming language for the Adobe Flash Player run-time environment. It enables interactivity, data handling, and much more in Flash content and applications. ActionScript is executed by the ActionScript Virtual Machine (AVM), which is part of Flash Player. ActionScript code is typically compiled into bytecode format (a sort of programming language that’s written and understood by computers) by a compiler. The bytecode is embedded in SWF files, which are executed by the Flash Player, the run-time environment. A new ActionScript Virtual Machine, called AVM2 that uses a new bytecode instruction set and provides significant performance improvements. ActionScript 3.0 is based on ECMAScript, the international standardized programming language for scripting. ActionScript 3.0 is compliant with the ECMAScript Language Specification, Third Edition (ECMA-262).
Action Script Panel can be selected from File Menu -> New when you are planning to write code externally. You can also write code on Timeline by selecting a frame and pressing F9.
Variables and constants:
Since programming mainly involves changing pieces of information in the computer’s memory, there needs to be a way to represent a single piece of information in the program. A variable is a name that represents a value in the computer’s memory. As you write statements to manipulate values, you write the variable’s name in place of the value; any time the computer sees the variable name in your program, it looks in its memory and uses the value it finds there.
In ActionScript 3.0, a variable actually consists of three different parts:
• The variable’s name
• The type of data that can be stored in the variable
• The actual value stored in the computer’s memory
When you create a variable in ActionScript 3, you must use the var keyword.
var myVariableName; // var required
var age:int=30;
When defining a variable you must only use numbers, letters, dollar signs ($) and underscores (_) and a variable cannot start with a number. Whereas age2, _age2, and $age32 are valid, 32age is not valid for a variable name since it starts with a number.
You will also have to be sure not to create naming conflicts with your variable names and any internal variable names already defined in the current scope of your script. For example, when writing code in any timeline, you are writing code that is being defined for a MovieClip instance – the MovieClip instance that is represented by that timeline. If you try to define a variable with a name that is the same as a predefined MovieClip variable (or function) you will get an error.
The Flash CS3 Actions panel can sometimes be helpful in identifying conflicts since recognized keywords are highlighted as blue.
Data types:
In ActionScript, there are many data types that you can use as the data type of the variables you create. Some of these can be thought of as “simple” or “primitive” data types:
Simple or Primitive Data type:
• String: a textual value, like a name or the text of a book chapter
• Numeric: ActionScript 3.0 includes three specific data types for numeric data:
• Number: any numeric value, including values with or without a fraction
• int: an integer (a whole number without a fraction)
• uint: an “unsigned” integer, meaning a whole number that can’t be negative
• Boolean: a true-or-false value, such as whether a switch is on or whether two values are equal.
• *: untyped; // variable can have any type
The data type will give following output when it is checked using trace() function.
• var untyped:*; // (or no typing) undefined
• var boolean:Boolean; // false
• var number:Number; // NaN
• var integer:int; // 0
• var unsignedInteger:uint; // 0
• var string:String; // null
• var object:Object; // null
Any other Object type results in default value of null. It should be noted that values of the type object (any kind of object including arrays and objects created from custom classes) have a default value of null, not undefined. In fact objects in ActionScript 3 cannot be undefined. If they have no value, then they are null. Only with untyped variables or attempting to access variables that do not exist will get a value of undefined.
Number types are now unique in that they can no longer be undefined or null. If they have no value, they are seen as NaN ("Not a Number"). NaN is a tricky value, however. You can't really compare NaN with another NaN with the equality operator (==) because they probably won't be the same. If you ever need to check to see if a number is NaN, you should always use isNaN().
if (isNaN(myNumber)) // checks to see if Number is defined
There is one other type that is also not capitalized. This is the special void type. This was capitalized in ActionScript 2 but is no longer in ActionScript 3 since, like with int and uint, there is no specific definition associated with it. This type has not been seen so far as it only applies to functions.
Complex data type:
The majority of the data types defined in ActionScript could be described as complex data types, because they represent a set of values grouped together. For example, a variable with the data type Date represents a single value—a moment in time. Nevertheless, that date value is actually represented as several values: the day, month, year, hours, minutes, seconds, and so on, all of which are individual numbers. So while we think of a date as a single value (and we can treat it as a single value by creating a Date variable), internally the computer thinks of it as a group of several values that, put together, define a single date. Most of the built-in data types, as well as data types defined by programmers, are complex data types. Some of the complex data types you might recognize are: MovieClip, Sprite, SimpleButton, Date, Object, Custom class, Array etc.
You can recognize complex references, that is, any reference that requires a dot (.) or bracket access ([]) to reference the variable.
Type conversions:
A type conversion is said to occur when a value is transformed into a value of a different data type. Type conversions can be either implicit or explicit. Implicit conversion, which is also called coercion, is sometimes performed by Flash Player at run time. For example, if the value 2 is assigned to a variable of the Boolean data type, Flash Player converts the value 2 to the Boolean value true before assigning the value to the variable. Explicit conversion, which is also called casting, occurs when your code instructs the compiler to treat a variable of one data type as if it belongs to a different data type.
Explicit conversion example
var myBoolean:Boolean = true;
var myINT:int = int(myBoolean);
trace(myINT); // 1
Syntax:
Case sensitivity: ActionScript 3.0 is a case-sensitive language. Identifiers that differ only in case are considered different identifiers. For example, the following code creates two different variables:
var num1:int;
var Num1:int;
Dot syntax: The dot operator (.) provides a way to access the properties and methods of an object. Using dot syntax, you can refer to a class property or method by using an instance name, followed by the dot operator and name of the property or method.
For example, consider the following class definition:
Public class A
{
public myName:String=”Faiz”;
function A()
{
trace(“Constructor A”);
}
public function calculate(x:int);
{
trace(x+10);
}
}
var ins:A=new A();
ins.calculate(5);
Comments: ActionScript 3.0 code supports two types of comments: single-line comments and multiline comments.
var someNumber:Number = 3; // a single line comment
/* This is multiline comment
that can span more than one line of code. */
Iteration: Following loops available in AS3.
for
var i:int;
for (i = 0; i < 5; i++)
{
trace(i);
}
for..in
The for..in loop iterates through the properties of an object, or the elements of an array. For example, you can use a for..in loop to iterate through the properties of a generic object.
var myObj:Object = {x:20, y:30};
for (var i:String in myObj)
{
trace(i + ": " + myObj[i]);
}// output: // x: 20 // y: 30
You can also hide dynamic definitions from iteration using the ActionScript 3 myObj.setPropertyIsEnumerable(“x”,false) function. Now output will show only 30.
You can also iterate through the elements of an array:
var myArray:Array = ["one", "two", "three"];
for (var i:String in myArray)
{
trace(myArray[i]);
}// output: // one // two // three
What you cannot do is iterate through the properties of an object if it is an instance of a user-defined class, unless the class is a dynamic class. Even with instances of dynamic classes, you will be able to iterate only through properties that are added dynamically.
For example create a custom class A:
package
{
public dynamic class A {
public var age:Number=30;
function A()
{
trace("const@@@@@ructor A");
}
public function checkMe():void
{
trace("check Me A");
}
}
}
var ins:A=new A();
ins.sex=”male”;
for(var prop in ins)
trace(ins[prop])// output: male
You see that only property added dynamically is displayed in output Panel.
for each..in
The for each..in loop iterates through the items of a collection, which can be tags in an XML or XMLList object, the values held by object properties, or the elements of an array.
For example, as the following excerpt shows, you can use a for each..in loop to iterate through the properties of a generic object, but unlike the for..in loop, the iterator variable in a for each..in loop contains the value held by the property instead of the name of the property:
var myObj:Object = {x:20, y:30};
for each (var num in myObj)
{
trace(num);
}// output: // 20 // 30
You can iterate through an XML or XMLList object, as the following example shows:
var myXML:XML = <users> <fname>Jane</fname> <fname>Susan</fname> <fname>John</fname> </users>;
for each (var item in myXML.fname)
{
trace(item);
}/* output Jane Susan John */
You can also iterate through the elements of an array, as this example shows:
var myArray:Array = ["one", "two", "three"];
for each (var item in myArray)
{
trace(item);
}// output: // one // two // three
You cannot iterate through the properties of an object if the object is an instance of a sealed class. Even for instances of dynamic classes, you cannot iterate through any fixed properties, which are properties defined as part of the class definition.
while
The while loop is like if statement that repeats as long as the condition is true. For example, the following code produces the same output as the for loop example:
var i:int = 0;
while (i < 5)
{
trace(i); i++;
}
do..while
The do..while loop is a while loop that guarantees that the code block is executed at least once, because the condition is checked after the code block is executed. The following code shows a simple example of a do..while loop that generates output even though the condition is not met:
var i:int = 5;
do
{
trace(i); i++;
} while (i < 5); // output: 5
Conditionals:
ActionScript 3.0 provides three basic conditional statements that you can use to control program flow.
if..else
The if..else conditional statement allows you to test a condition and execute a block of code if that condition exists, or execute an alternative block of code if the condition does not exist. For example, the following code tests whether the value of x exceeds 20, generates a trace() function if it does, or generates a different trace() function if it does not:
if (x > 20)
{
trace("x is > 20");
}
else
{
trace("x is <= 20");
}
If you do not want to execute an alternative block of code, you can use the if statement without the else statement.
if..else if
You can test for more than one condition using the if..else if conditional statement. For example, the following code not only tests whether the value of x exceeds 20, but also tests whether the value of x is negative:
if (x > 20)
{
trace("x is > 20");
}
else if (x < 0)
{
trace("x is negative");
}
else
trace("x is 0");
switch
The switch statement is useful if you have several execution paths that depend on the same condition expression. It provides functionality similar to a long series of if..else if statements, but is somewhat easier to read.
For example, the following switch statement prints the day of the week, based on the day.
number returned by the Date.getDay() method:
var someDate:Date = new Date();
var dayNum:uint = someDate.getDay();
switch(dayNum)
{
case 0:
trace("Sunday");
break;
case 1:
trace("Monday");
break;
case 2:
trace("Tuesday");
break;
case 3:
trace("Wednesday");
break;
case 4:
trace("Thursday");
break;
case 5:
trace("Friday");
break;
case 6:
trace("Saturday");
break;
default:
trace("Out of range");
break;
}
Functions:
Functions define reusable chunks of code, or custom operations in ActionScript. By creating a function you can perform the same operation multiple times without having to write the same code over again for each time you want to use it. Instead, all you do is call the function using its function name.
There are two ways to define functions in ActionScript.
// Named function
function doubleNumber(num) {
return num*2;
}// Same function defined as an anonymous function
// defined within the variable doubleNumber
var doubleNumber = function(num) {
return num*2;
}
To use the function, you call it using parentheses (()).
var x:Number = 10;
trace(doubleNumber(x)); // traces 20
As with variables, named functions cannot be defined more than once for any one given timeline in ActionScript 3. Anonymous functions can reference multiple functions over time, but cannot be redefined with var as they are essentially variables. ActionScript 2 allowed you to change any function's definition anytime. In ActionScript 3, you can only change an anonymous function's definition.
When assigning type to functions, define typing information for both the parameter list (the comma separated list of values you can supply the function) as well as the return value, or the value that the function supplies after it's executed. When using an anonymous function definition, the variable the function is being assigned to would also be typed to Function.
// Named function
function doubleNumber(num:Number):Number {
return num*2;
}// Same function defined as an anonymous function
var doubleNumber:Function = function(num:Number):Number {
return num*2;
}
If a function does not return a value, then its return type should be void. When a function typed as void is executed, or simply fails to return a value with the return statement, its return value becomes undefined.
function returnsNothing():void {
// do nothing
}
trace(returnsNothing()); // traces undefined
The returnsNothing function above not only returns nothing, but also accepts no values – it has no parameter list. If you try to pass values into the function when it has no parameter list defined for it in ActionScript 3, you will get an error.
returnsNothing(3); // Error:
Parameters vs. arguments:
The difference between parameters and arguments is that parameters are the value used to define the function. Arguments are the actual values provided to the function during use. You can see arguments as being parameter values.
With ActionScript 3, you can also now define default values for your functions.
// Here, message parameter is optional
function usesDefault(message:String = "hello"):void {
trace(message);
}
usesDefault("test"); // traces "test"
usesDefault(); // traces "hello"
By using defaults you not only get to specify values for parameters not used by the function caller, but it also lets you define functions with optional parameters, or parameters that aren't required to be used. Those parameters that do not have default values must be provided when the function is called in ActionScript 3. Because of this, all optional parameters must be defined at the end of a parameter list. You cannot have a required parameter defined after an optional.
function usesDefault(message:String = "hello", num:Number):void {
// code
}
// Error: Required parameters are not permitted after optional parameters
function usesDefault(num:Number, message:String = "hello"):void {
// code
}// Correct; usesDefault needs at least 1 argument, accepts 2 at max
What if you wanted to allow a function to be called with any number of arguments? In ActionScript 2, you could do this simply by omitting any parameter list and referencing the arguments using the arguments object in the function. In ActionScript 3, having no parameter list means the function cannot be called with any arguments. Instead, you have to use a new parameter type known as …(rest). This parameter goes at the end of your parameter list (or it can represent your entire parameter list) and indicates that any number of arguments can be used when calling the function. The …(rest) parameter is written as …argumentsArrayName where argumentsArrayName is the name of the array that will contain the arguments passed.
// Using the ...(rest) parameter
function passAnything(...statements):void {
trace(statements.length +": "+ statements);
}
passAnything(); // traces 0:
passAnything(1); // traces 1: 1
passAnything("a", true, 0); // traces 3: a,true,0
Nested functions:
function getNameAndVersion():String
{
function getVersion():String
{
return "9";
}
function getProductName():String
{
return "Flash Player";
}
return (getProductName() + " " + getVersion());
}
trace(getNameAndVersion()); // Flash Player 9
Passing arguments by value or by reference:
To be passed by value means that the value of the argument is copied into a local variable for use within the function. To be passed by reference means that only a reference to the argument is passed instead of the actual value. No copy of the actual argument is made.
In ActionScript 3.0, all arguments are passed by reference, because all values are stored as objects. However, objects that belong to the primitive data types, which includes Boolean, Number, int, uint, and String, have special operators that make them behave as if they were passed by value.
For example, the following code creates a function named passPrimitives() that defines two parameters named xParam and yParam, both of type int.
Although xParam and yParam initially contain only references to the xValue and yValue objects, any changes to the variables within the function body generate new copies of the values in memory.
function passPrimitives(xParam:int, yParam:int):void
{
xParam++;
yParam++;
trace(xParam, yParam);
}
var xValue:int = 10;
var yValue:int = 15;
trace(xValue, yValue); // 10 15
passPrimitives(xValue, yValue); // 11 16
trace(xValue, yValue); // 10 15
Within the passPrimitives() function, the values of xParam and yParam are incremented,
but this does not affect the values of xValue and yValue, as shown in the last trace
statement. This would be true even if the parameters were named identically to the variables, xValue and yValue, because the xValue and yValue inside the function would point to new locations in memory that exist separately from the variables of the same name outside the function.
All other objects—that is, objects that do not belong to the primitive data types—are always passed by reference, which gives you ability to change the value of the original variable.
For example, the following code creates an object named objVar with two properties, x and y.
The object is passed as an argument to the passByRef() function. Because the object is not a primitive type, the object is not only passed by reference, but also stays a reference. This means that changes made to the parameters within the function will affect the object properties outside the function.
function passByRef(objParam:Object):void
{
objParam.x++;
objParam.y++;
trace(objParam.x, objParam.y);
}
var objVar:Object = {x:10, y:15};
trace(objVar.x, objVar.y); // 10 15
passByRef(objVar); // 11 16
trace(objVar.x, objVar.y); // 11 16
The objParam parameter references the same object as the global objVar variable. As you can see from the trace statements in the example, changes to the x and y properties of the objParam object are reflected in the objVar object.
Total hits since 4th Jan 2010
Thursday, February 25, 2010
Monday, February 8, 2010
Webservice and Implementation
Hi Guys,
Thanks a lot for your appreciation and feedback. Much demanded topic Webservice has been covered for you. I request all of you to join as a member it will take hardly 2 mins so that you don't miss anything. We can also view your good face so Please add your image in profile.
What is a Web Service?
A Web service is a service on the web which can be parsed by Flash Player. We can invoke SOAP based Web service deployed on server. A Web service’s goal is to provide raw data in XML format to any application that makes a request to it. A Web service sits on a server much like any server-side page, and when a request is made to it, the Web service will perform a desired task, and return data in the form of XML. When using Flex Web service component, Objects returned by a web service are automatically deserialized into Action Script objects. Similarly Action Script objects passed as arguments to a web service operation are serialized according the wsdl description. Each Web service written will have a WSDL (Web Services Description Language) file that will describe Web service to anyone who intends to use it. Web services can be written in several different languages Like .net , ColdFusion etc.
Why Use Web Services?
It relies on standard Internet protocols HTTP and SOAP which are present in every system. Web services transport their messages using HTTP, which means these messages are transmitted over port 80, an open port for web server firewalls (Firewalls do not block Text information). Web service messages are transmitted as SOAP-formatted messages. SOAP messages are in XML format, meaning they are simply text, and not binary data. Any application written in any language running on any platform can process XML. Web services improve the way information flows between applications by making its information and its business logic available to other applications through an application programming interface (API). An API is a programming mechanism that allows an application to expose its functionality and to any other software application. So, API greatly supports application-to-application communication.
Let's take an example of a Web service:
It is a dictionary web service written in net. You can also view it at path below http://services.aonaware.com/DictService/DictService.asmx.
See the screenshot below:
You can see all the Web methods listed and their description if it was declared. Select the Define method and you will be taken to a new screen (see screenshot below).
Here you can invoke (run) the method to see its results. Also, you can see all the information about the method including its return value, and if we had any parameters, they would be shown here as well. Choose the Invoke button (specify any word in a text field), and another browser window will pop up with XML data as shown below in a screen shot. This is the result of the Web service.
As you see the web methods can be tested without an application. It gives enough information to a developer for its implementation.
Finally look at the WSDL screen shot below and at http://services.aonaware.com/DictService/DictService.asmx?WSDL
This tells any user of the Web service everything they need to know to use it. It shows all the methods, their return values, and their parameters.
Implementing Web Services with Flash 8:
We have already checked webs service, let’s take it a step further and bring the data into Flash.
We will begin working with the Web service and XML object to bring the data in Flash.
I have used temperature converter web service for this example. http://www.w3schools.com/webservices/tempconvert.asmx?WSDL
It has 2 methods for temperature conversion.
CelsiusToFahrenheit
FahrenheitToCelsius
Let’s have a look how to incorporate in Flash 8 using inbuilt Web service class.
import mx.services.WebService;
var wsdlURI = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";
// Creates a new web service object.
var tempConvert:WebService = new WebService(wsdlURI);
// Receives the WSDL document after loading.
tempConvert.onLoad = function(wsdlDocument) {
//trace(wsdlDocument+"****");
// Code to execute when the WSDL loading is complete and the
// object has been created.
};
tempConvert.onFault = function(fault) {
//trace("Fault"+fault);
};
cToF_btn.onRelease = function() {
var callback1 = tempConvert.CelsiusToFahrenheit(cToF_txt.text);
callback1.onResult = function(result) {
cToFresult_txt.text = result;
};
};
fToC_btn.onRelease = function() {
var callback1 = tempConvert.FahrenheitToCelsius(fToC_txt.text);
callback1.onResult = function(result) {
fToCresult_txt.text = result;
};
};
Find the process below to implement the same Web service in Flex.
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" borderStyle="solid">
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
private var btnName:String="";
private function wsdlMethodResult(event:ResultEvent):void
{
if(btnName=="btn1")
{
//trace(event.result);
cToFresult_txt.text=String(event.result);
}
else if(btnName=="btn2")
{
//trace(event.result);
FToCresult_txt.text=String(event.result);
}
}
]]>
</mx:Script>
<mx:VBox>
<mx:HBox width="100%">
<mx:Label text="CelsiusToFahrenheit"/>
<mx:TextInput id="cToF_txt"/>
<mx:Button label="Convert" click="btnName='btn1';srv.CelsiusToFahrenheit(cToF_txt.text)"/>
<mx:Text width="100" id="cToFresult_txt"/>
</mx:HBox>
<mx:HBox width="100%">
<mx:Label text="FahrenheitToCelsius"/>
<mx:TextInput id="FToC_txt"/>
<mx:Button label="Convert" click="btnName='btn2';srv.FahrenheitToCelsius(FToC_txt.text)"/>
<mx:Text id="FToCresult_txt" width="100"/>
</mx:HBox>
</mx:VBox>
<mx:WebService id="srv" wsdl="http://www.w3schools.com/webservices/tempconvert.asmx?WSDL" result="wsdlMethodResult(event)" showBusyCursor="true"/>
</mx:Application>
See the screen shot below of the above programme.
Regards,
Faiz
Thanks a lot for your appreciation and feedback. Much demanded topic Webservice has been covered for you. I request all of you to join as a member it will take hardly 2 mins so that you don't miss anything. We can also view your good face so Please add your image in profile.
What is a Web Service?
A Web service is a service on the web which can be parsed by Flash Player. We can invoke SOAP based Web service deployed on server. A Web service’s goal is to provide raw data in XML format to any application that makes a request to it. A Web service sits on a server much like any server-side page, and when a request is made to it, the Web service will perform a desired task, and return data in the form of XML. When using Flex Web service component, Objects returned by a web service are automatically deserialized into Action Script objects. Similarly Action Script objects passed as arguments to a web service operation are serialized according the wsdl description. Each Web service written will have a WSDL (Web Services Description Language) file that will describe Web service to anyone who intends to use it. Web services can be written in several different languages Like .net , ColdFusion etc.
Why Use Web Services?
It relies on standard Internet protocols HTTP and SOAP which are present in every system. Web services transport their messages using HTTP, which means these messages are transmitted over port 80, an open port for web server firewalls (Firewalls do not block Text information). Web service messages are transmitted as SOAP-formatted messages. SOAP messages are in XML format, meaning they are simply text, and not binary data. Any application written in any language running on any platform can process XML. Web services improve the way information flows between applications by making its information and its business logic available to other applications through an application programming interface (API). An API is a programming mechanism that allows an application to expose its functionality and to any other software application. So, API greatly supports application-to-application communication.
Let's take an example of a Web service:
It is a dictionary web service written in net. You can also view it at path below http://services.aonaware.com/DictService/DictService.asmx.
See the screenshot below:
You can see all the Web methods listed and their description if it was declared. Select the Define method and you will be taken to a new screen (see screenshot below).
Here you can invoke (run) the method to see its results. Also, you can see all the information about the method including its return value, and if we had any parameters, they would be shown here as well. Choose the Invoke button (specify any word in a text field), and another browser window will pop up with XML data as shown below in a screen shot. This is the result of the Web service.
As you see the web methods can be tested without an application. It gives enough information to a developer for its implementation.
Finally look at the WSDL screen shot below and at http://services.aonaware.com/DictService/DictService.asmx?WSDL
This tells any user of the Web service everything they need to know to use it. It shows all the methods, their return values, and their parameters.
Implementing Web Services with Flash 8:
We have already checked webs service, let’s take it a step further and bring the data into Flash.
We will begin working with the Web service and XML object to bring the data in Flash.
I have used temperature converter web service for this example. http://www.w3schools.com/webservices/tempconvert.asmx?WSDL
It has 2 methods for temperature conversion.
CelsiusToFahrenheit
FahrenheitToCelsius
Let’s have a look how to incorporate in Flash 8 using inbuilt Web service class.
import mx.services.WebService;
var wsdlURI = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";
// Creates a new web service object.
var tempConvert:WebService = new WebService(wsdlURI);
// Receives the WSDL document after loading.
tempConvert.onLoad = function(wsdlDocument) {
//trace(wsdlDocument+"****");
// Code to execute when the WSDL loading is complete and the
// object has been created.
};
tempConvert.onFault = function(fault) {
//trace("Fault"+fault);
};
cToF_btn.onRelease = function() {
var callback1 = tempConvert.CelsiusToFahrenheit(cToF_txt.text);
callback1.onResult = function(result) {
cToFresult_txt.text = result;
};
};
fToC_btn.onRelease = function() {
var callback1 = tempConvert.FahrenheitToCelsius(fToC_txt.text);
callback1.onResult = function(result) {
fToCresult_txt.text = result;
};
};
Find the process below to implement the same Web service in Flex.
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" borderStyle="solid">
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
private var btnName:String="";
private function wsdlMethodResult(event:ResultEvent):void
{
if(btnName=="btn1")
{
//trace(event.result);
cToFresult_txt.text=String(event.result);
}
else if(btnName=="btn2")
{
//trace(event.result);
FToCresult_txt.text=String(event.result);
}
}
]]>
</mx:Script>
<mx:VBox>
<mx:HBox width="100%">
<mx:Label text="CelsiusToFahrenheit"/>
<mx:TextInput id="cToF_txt"/>
<mx:Button label="Convert" click="btnName='btn1';srv.CelsiusToFahrenheit(cToF_txt.text)"/>
<mx:Text width="100" id="cToFresult_txt"/>
</mx:HBox>
<mx:HBox width="100%">
<mx:Label text="FahrenheitToCelsius"/>
<mx:TextInput id="FToC_txt"/>
<mx:Button label="Convert" click="btnName='btn2';srv.FahrenheitToCelsius(FToC_txt.text)"/>
<mx:Text id="FToCresult_txt" width="100"/>
</mx:HBox>
</mx:VBox>
<mx:WebService id="srv" wsdl="http://www.w3schools.com/webservices/tempconvert.asmx?WSDL" result="wsdlMethodResult(event)" showBusyCursor="true"/>
</mx:Application>
See the screen shot below of the above programme.
Regards,
Faiz
Tuesday, February 2, 2010
FLV Component and preloading problem
Most of the time We have seen the application’s preloader doesn’t appear properly. It starts after certain time interval. It is due to we are exporting the library items on Frame 1. When the application starts loading the library linkage items are given preference after that timeline frame. The screen remains blank till then. Check bandwidth Profiler, Streaming Graph from view menu and click Simulate Download to behave it like downloading from internet.
See the graph bars in above screen shot. If the First bar of a graph (that’s First Frame data) from the left is below 1 Kb then your preloader start properly otherwise you need to work around your program.
Note: If you are exporting library items in 1st Frame it will increase data size in Frame/bar 1.
So export library items on Frame 2 to avoid it.
Go to File Publish setting-> Flash Tab ->Settings and change Export Class in Frame 1 to 2. See the screen shot below.
FLV Component and preloading problem:
We faced problem when exporting FLV player in Frame 2. The preloader was not working properly. Despite Frame 2 It was loading data in Frame 1.
Check it.
Open New Fla and insert 2 blank Key Frames. Drag FLV component and Place it on Frame 2 and give it an instance name ‘flvPlayer’. Insert Following code on Frame 1 for Preloader.
function update(e:ProgressEvent):void {
var percent:Number = Math.floor((e.bytesLoaded/e.bytesTotal)*100 );
pbar_mc.scaleX=percent/100;
per_txt.text=percent+"%";
if (percent==100) {
play();
}
}
loaderInfo.addEventListener(ProgressEvent.PROGRESS, update);
stop();
You need to create 2 symbols ‘pbar_mc’ MovieClip and ‘per_txt’ TextField for showing percentage and scaling of a movieclip bar.
Insert Following Code on Frame2
stop();
flvPlayer.skinBackgroundColor=0x666666;
flvPlayer.skinBackgroundAlpha=0.5;
flvPlayer.source="http://www.helpexamples.com/flash/video/water.flv";
Open Bandwidth Profiler and check the Graph it is showing below screen shot despite Exporting on Frame 2 that’ why preloader not behaving properly.
Solutions:
Click on FLV Player in 2 Frame and convert it into a Movie Clip. Cut the Code Frame 2 and Place with in a MovieClip.
Now check Bandwidth Profiler. I hope everything will work properly now.
Friday, January 29, 2010
Optimization techniques and GC
I’m personally a big fan of coding standards and writing optimized code. I appreciate others and very happy to do it. We should pay more attention while writing code rather than spending a ton of time on GC for finding reason of performance. Continuous practices and experience make you write better and better optimized code. We should follow strictly a coding standard within a team/company while writing code. We should review others code and try to learn good things from there and implement whenever it requires.
A few practices listed below and you are welcome to add more:
Avoid the new operator when creating Array. Try to use var a=[];
Fastest way to copy an array: var copy : Array = sourceArray.concat();
Setting values in Array is slow and getting from it is 2 times faster.
Use ‘static’ for properties methods that do not require an object instance.
Use ‘const’ for properties that will never change throughout the lifecycle of the application.
Use ‘final’ when no subclasses need to be created.
Length of method/variable names doesn't matter so give it suitable name for readability.
No difference in memory usage between an if statement and a switch statement.
Use integers for iterations
Multiply vs. Divide: instead of 5000/1000 use: 5000*0.001
Avoid calculations and method calls in loops: use
var len : int = myArray.length;
Understanding Garbage Collection is also important steps for writing optimized code that ensures project runs with minimal impact on the user's computer. Thanks to Grant Skinner for his contribution on this topic.
What is Garbage Collection (GC)?
Garbage collection is a process by which the memory is freed up when any object no longer used by the application. It happens automatically. Garbage collector runs at some indeterminate point so it is not in the control of developers. AS3 garbage collector uses two methods for locating objects with no active references: reference counting and mark sweeping.
Reference counting:
Reference counting is one of the simplest methods for keeping track of active objects, and has been used in Flash since AS1. When you create a reference to an object, its reference count is incremented. When you delete a reference, its reference count is decremented. If the reference count of an object reaches zero, it is marked for deletion by the garbage collector.
Example
var a:Object = {foo:"bar"}// the object now has a reference count of 1 (a)var
b:Object = a;// now it has a reference count of 2 (a & b)
delete(a);// back to 1 (b)
delete(b);// the reference countdown is now 0 the object can now be deallocated by the garbage collector.
Reference counting is simple, it doesn't carry a huge CPU overhead, and it works well in most situations. Unfortunately, the reference counting method for garbage collection is not optimal when it comes to circular referencing. Circular referencing is the situation when objects cross-reference each other (directly, or indirectly via other objects). Even if the application is no longer actively using the objects, their reference counts remain above zero, so the garbage collector never removes them. The code below illustrates how this works:
var a:Object = {}
//create a second object, and reference the first object.
var b:Object = {foo:a};
// make the first object reference the second as well.
a.foo = b;
// delete both active application references:
delete(a);
delete(b);
In the code shown above, both of the active application references have been deleted. I no longer have any way of accessing the two objects from my application, but the reference counts of both objects are 1 because they reference each other.
Mark sweeping:
Mark sweeping introduced in Flash player 8. The second strategy employed by the AS3 garbage collector to find inactive objects is a method called mark and sweep. Flash Player starts at the root object of your application (which is conveniently called the "root" in AS3) and walks through every reference in it, marking each object it finds. Flash Player iterates through each of the marked objects. It continues this behavior recursively until it has traversed the entire object tree of your application, marking everything it can reach through an active reference. At the end of this process, Flash Player can safely assume that any objects in memory that are not marked no longer have any active references to them and can be safely deallocated.
Mark and sweep is very accurate. However, because Flash Player has to traverse your entire object structure, the process is costly in terms of CPU usage. Flash Player 9 reduces this cost by carrying out iterative mark and sweep—the process occurs over a number of frames, instead of all at once—and by running this process only occasionally.
New API:
AS3 has added many new API and changed its earlier framework so require additional responsibility than before. The biggest change in AS3 that affects resource management is the new display list model. In Flash Player 8 and earlier, when a display object was removed from the screen (using removeMovie or unloadMovie), the display object and all of its children were immediately removed from memory and code execution stopped. Flash Player 9 introduces a much more flexible display list model. The display objects (Sprites, Movie clips, etc.) are now treated the same as every other object by the garbage collector. Flash developers are now to manage resource like Java.
Display objects continue to exist in memory when you remove the object from the Stage because they no longer live and die on the display list. If you have not cleaned up all other references to the clip, including the object's listeners, it may never be removed. If you have done a good job of cleaning up all references, the clip will be removed from memory the next time the garbage collector runs a sweep, which will occur at some indeterminate point in the future. It is not in the control of developer hands. There is currently no way to force Flash Player to kill a display object and stop it from executing. It is up to the Flash developer to do this manually when the object is removed from the display.
It is very important to note that not only will the display object continue to use memory, it will also continue to execute any "idle" code, such as timers, enterFrames, and listeners that are outside its scope.
In AS3, even after you remove the Display object from the display list and null all references to it, the application continues to run that code in every frame until it is removed by garbage collection. You must remember to explicitly remove the enterFrame listener when it is removed.
Similar to other display objects, there is no way to explicitly remove a loaded SWF and its contents from memory, or to stop it from executing. Calling Loader.unload simply nulls the loader's reference to the SWF; it will continue to exist and keep executing until it has been picked up by the next garbage collection sweep. Take care of the things while loading external swf that has been developed by another team and they added listeners and external assets in this file. There is no way to remove its content and it will consume CPU resources until quits the application.
Even if the loaded content does not have any external references, it will continue to execute indefinitely until the next garbage collection sweep.
It is always a good idea to think through potential vulnerabilities in your application during the development process.
Profiling:
The System class contains methods and properties that allow you to interact with the user’s operating system and retrieve the current memory usage for Flash Player or AIR. By checking the System.totalMemory property, you can determine the amount of memory (in bytes) that Flash Player or AIR is currently using. This property allows you to monitor memory usage and optimize your applications based on how the memory level changes. It can be used as a runtime profiling tool. It's always better to throw an error and abort your application, rather than bog down the user's system. You can use this basic code for runtime profiling:
import flash.system.System;
import flash.net.navigateToURL;
import flash.net.URLRequest;
// check our memory every 5 second:
var checkMemoryIntervalID:uint = setInterval(checkMemoryUsage,5000);
var showWarning:Boolean = true;
var warningMemory:uint = 500000000// show warning
var abortMemory:uint =600000000;// Abort when it has exceeded
function checkMemoryUsage()
{
if (System.totalMemory > warningMemory && showWarning) {
// show an error to the user warning them that we're running out of memory and might quit
// try to free up memory if possible
showWarning = false; // so we don't show an error every second
}
else if (System.totalMemory > abortMemory) {
// save current user data if required.
abort();
}
}
function abort() {
// send the user to a page explaining what happpened:
navigateToURL(new URLRequest("help.html"));
}
It is important to note that totalMemory is a shared value within a single process. A single process may be just one browser window, or all open browser windows, depending on the browser, the operating system, and how the windows were opened.
Conclusion: There is no longer any way to explicitly remove a display object from memory and stop its code from executing—which means all Flash developers have a responsibility to clean up properly after objects are no longer used in an application.
Regards,
Faiz
A few practices listed below and you are welcome to add more:
Avoid the new operator when creating Array. Try to use var a=[];
Fastest way to copy an array: var copy : Array = sourceArray.concat();
Setting values in Array is slow and getting from it is 2 times faster.
Use ‘static’ for properties methods that do not require an object instance.
Use ‘const’ for properties that will never change throughout the lifecycle of the application.
Use ‘final’ when no subclasses need to be created.
Length of method/variable names doesn't matter so give it suitable name for readability.
No difference in memory usage between an if statement and a switch statement.
Use integers for iterations
Multiply vs. Divide: instead of 5000/1000 use: 5000*0.001
Avoid calculations and method calls in loops: use
var len : int = myArray.length;
Understanding Garbage Collection is also important steps for writing optimized code that ensures project runs with minimal impact on the user's computer. Thanks to Grant Skinner for his contribution on this topic.
What is Garbage Collection (GC)?
Garbage collection is a process by which the memory is freed up when any object no longer used by the application. It happens automatically. Garbage collector runs at some indeterminate point so it is not in the control of developers. AS3 garbage collector uses two methods for locating objects with no active references: reference counting and mark sweeping.
Reference counting:
Reference counting is one of the simplest methods for keeping track of active objects, and has been used in Flash since AS1. When you create a reference to an object, its reference count is incremented. When you delete a reference, its reference count is decremented. If the reference count of an object reaches zero, it is marked for deletion by the garbage collector.
Example
var a:Object = {foo:"bar"}// the object now has a reference count of 1 (a)var
b:Object = a;// now it has a reference count of 2 (a & b)
delete(a);// back to 1 (b)
delete(b);// the reference countdown is now 0 the object can now be deallocated by the garbage collector.
Reference counting is simple, it doesn't carry a huge CPU overhead, and it works well in most situations. Unfortunately, the reference counting method for garbage collection is not optimal when it comes to circular referencing. Circular referencing is the situation when objects cross-reference each other (directly, or indirectly via other objects). Even if the application is no longer actively using the objects, their reference counts remain above zero, so the garbage collector never removes them. The code below illustrates how this works:
var a:Object = {}
//create a second object, and reference the first object.
var b:Object = {foo:a};
// make the first object reference the second as well.
a.foo = b;
// delete both active application references:
delete(a);
delete(b);
In the code shown above, both of the active application references have been deleted. I no longer have any way of accessing the two objects from my application, but the reference counts of both objects are 1 because they reference each other.
Mark sweeping:
Mark sweeping introduced in Flash player 8. The second strategy employed by the AS3 garbage collector to find inactive objects is a method called mark and sweep. Flash Player starts at the root object of your application (which is conveniently called the "root" in AS3) and walks through every reference in it, marking each object it finds. Flash Player iterates through each of the marked objects. It continues this behavior recursively until it has traversed the entire object tree of your application, marking everything it can reach through an active reference. At the end of this process, Flash Player can safely assume that any objects in memory that are not marked no longer have any active references to them and can be safely deallocated.
Mark and sweep is very accurate. However, because Flash Player has to traverse your entire object structure, the process is costly in terms of CPU usage. Flash Player 9 reduces this cost by carrying out iterative mark and sweep—the process occurs over a number of frames, instead of all at once—and by running this process only occasionally.
New API:
AS3 has added many new API and changed its earlier framework so require additional responsibility than before. The biggest change in AS3 that affects resource management is the new display list model. In Flash Player 8 and earlier, when a display object was removed from the screen (using removeMovie or unloadMovie), the display object and all of its children were immediately removed from memory and code execution stopped. Flash Player 9 introduces a much more flexible display list model. The display objects (Sprites, Movie clips, etc.) are now treated the same as every other object by the garbage collector. Flash developers are now to manage resource like Java.
Display objects continue to exist in memory when you remove the object from the Stage because they no longer live and die on the display list. If you have not cleaned up all other references to the clip, including the object's listeners, it may never be removed. If you have done a good job of cleaning up all references, the clip will be removed from memory the next time the garbage collector runs a sweep, which will occur at some indeterminate point in the future. It is not in the control of developer hands. There is currently no way to force Flash Player to kill a display object and stop it from executing. It is up to the Flash developer to do this manually when the object is removed from the display.
It is very important to note that not only will the display object continue to use memory, it will also continue to execute any "idle" code, such as timers, enterFrames, and listeners that are outside its scope.
In AS3, even after you remove the Display object from the display list and null all references to it, the application continues to run that code in every frame until it is removed by garbage collection. You must remember to explicitly remove the enterFrame listener when it is removed.
Similar to other display objects, there is no way to explicitly remove a loaded SWF and its contents from memory, or to stop it from executing. Calling Loader.unload simply nulls the loader's reference to the SWF; it will continue to exist and keep executing until it has been picked up by the next garbage collection sweep. Take care of the things while loading external swf that has been developed by another team and they added listeners and external assets in this file. There is no way to remove its content and it will consume CPU resources until quits the application.
Even if the loaded content does not have any external references, it will continue to execute indefinitely until the next garbage collection sweep.
It is always a good idea to think through potential vulnerabilities in your application during the development process.
Profiling:
The System class contains methods and properties that allow you to interact with the user’s operating system and retrieve the current memory usage for Flash Player or AIR. By checking the System.totalMemory property, you can determine the amount of memory (in bytes) that Flash Player or AIR is currently using. This property allows you to monitor memory usage and optimize your applications based on how the memory level changes. It can be used as a runtime profiling tool. It's always better to throw an error and abort your application, rather than bog down the user's system. You can use this basic code for runtime profiling:
import flash.system.System;
import flash.net.navigateToURL;
import flash.net.URLRequest;
// check our memory every 5 second:
var checkMemoryIntervalID:uint = setInterval(checkMemoryUsage,5000);
var showWarning:Boolean = true;
var warningMemory:uint = 500000000// show warning
var abortMemory:uint =600000000;// Abort when it has exceeded
function checkMemoryUsage()
{
if (System.totalMemory > warningMemory && showWarning) {
// show an error to the user warning them that we're running out of memory and might quit
// try to free up memory if possible
showWarning = false; // so we don't show an error every second
}
else if (System.totalMemory > abortMemory) {
// save current user data if required.
abort();
}
}
function abort() {
// send the user to a page explaining what happpened:
navigateToURL(new URLRequest("help.html"));
}
It is important to note that totalMemory is a shared value within a single process. A single process may be just one browser window, or all open browser windows, depending on the browser, the operating system, and how the windows were opened.
Conclusion: There is no longer any way to explicitly remove a display object from memory and stop its code from executing—which means all Flash developers have a responsibility to clean up properly after objects are no longer used in an application.
Regards,
Faiz
Subscribe to:
Comments (Atom)

