Monday, September 17, 2012

How to implement "Remember Me" or "Keep Me Signed In" option for your Web Application - JAVA Example

Most of the web applications that we see these days, have the "Remember Me" option, that keeps the user signed in. If you "check" this option, and do not log-out from the application, you will automatically be signed-in without being prompted to enter the username and password.

People usually believe that it is the browser related thing and need not be written in your application code.
It is true that it is related to the browser, but at the same time your application can interact with the browser properties to retrieve the useful data.

Suppose I have a web application, where-in the log-in page, there is an option for the user to command us to keep him signed in. In the html form where you ask the user his log-in credentials, add a checkbox with id and name as "rememberMe". If the user selects it, then a non-null value will be passed with your form for that field.

Put the following code in the jsp to which you are submitting the form:

if(request.getParameter("rememberMe")!= null){
    bytes [] bytes = request.getParameter("username") + ":" + request.getParameter("password")).getBytes();
    String encodedCredentials = Base64.encode(bytes, 0, bytes.length);
    Cookie cookie=new Cookie("myCookieName", encodedCredentials);
    cookie.setMaxAge(60 * 60 * 24 * 15);
    response.addCookie(cookie);
}

Get the values of the username and password, and encode them using an encoder(in my case I used a Base64 encoder), so that the username and password are not saved as a naive string. Then I create an instance of Cookie class, and pass my cookie name and the encoded credentials (key-value mapping), which I want to save. I set the maximum validity of this cookie as 15 days (you can set it for even longer time). After this I add this cookie instance to my HTTP response. This cookie is now saved in my browser.


Now I will write the following piece of code on my home page.


try{
    Cookie[] cookies = request.getCookies();
    for (int i = 0; i < cookies.length; i++) {
        Cookie cookie = cookies[i];
        if (cookie.getName().equals("myCookieName")) {
        if(cookie.getValue()!= "" && cookie.getValue().length() > 0){
            try{
            response.sendRedirect("your_authentication_page.jsp?cookieEnabled=" + cookie.getValue());
            }catch(Exception e){
            e.printStackTrace();
            }
        }
        }
    }
    }catch(Exception e){
     e.printStackTrace();
}

This code tries to read the name all the cookies saved in the browser. If the name matches with the one that you have given for your application, then you know that some user credentials are already saved. You pass on the value of the cookie to your authentication page. Write the following code snippet in your authentication page.

if(request.getParameter("cookieEnabled")!=null){
    boolean bAuthenticated = false;
    String credentials = request.getParameter("cookieEnabled");
    if (credentials != null) {
        String decodedCredentials = new String(Base64.decode(credentials));
        String credArray[] = decodedCredentials.split(":");
        bAuthenticated = function_to_authenticate_user(credArray[0], credArray[1]);
    }
}


You have passed encoded credentials (as your cookie value, which you have saved previously), to your authentication page. You can now decode those credentials and call your function that authenticates the user and automatically land him to your logged-in home page. Easy!

Shoot your doubts right here!

Monday, May 28, 2012

How to Implement File Download in JAVA

The files that appear on your web-app are part of the JSP and HTML pages. If you want to download them, you need to make a request to the servlet. The servlet reads the bytes of the files from an input stream, and writes them to the output stream. The output stream is nothing but a ServletOutputStream suitable for writing binary data in the response.

Check out the following code snippet:


BufferedOutputStream out =  new BufferedOutputStream(response.getOutputStream());

File f = new File("Path of the file on the server");
InputStream is = new FileInputStream(f);
BufferedInputStream in = new BufferedInputStream(is);
response.setHeader( "Content-Disposition", "attachment; filename=somefile.txt");
byte [] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = in.read(buffer))>0){
    out.write(buffer, 0, bytesRead);
}

is.close();
in.close();
out.close();


Since you need the response as an attachment to the browser, you need to set the response header accordingly as follows:

response.setHeader("Content-Disposition", "attachment; filename=somefile.txt"; 

Thursday, May 24, 2012

How to use Google Login for your App

You need to register your app on Google first to get identified by it.
Register here !

Steps to Register Your App.

1. Click on "Create Project"
2. It takes you to the Services Tab. Skip that step ans instead select the "API Access" Tab.
3. Click on "Create an OAuth 2.0 client ID"
4. Fill in the pop-up form with the info associated with your app, like your App name (Product Name), email id to which you want to associate this app, and the app logo url. Click Next.
5. Select the App type, give your site url. For development phase, you are allowed to give the site url as http://localhost:8080/ (or any other relevant port) as well.
6. If you click on more options link, you can enter the redirect url also for your app. The JavaScript origin becomes your site url.
7. Click on "Create Client ID"

Your App is registered now!

Google generates an App ID, or the Client ID for your app. It also generates a App Secret which should not be disclosed and an email address for the app.

In the log-in page of your application, open the following request url (either by button-click, href, ajax, get request, or window.open)

"https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&redirect_uri=http%3A%2F%2Fwww%2Eyourappdomain%2Ecom%2F&response_type=token&client_id=YOUR_APP_ID"
                               
You will be prompted by Google to permit the app to access your Google account. If you reject, Google will send you an error, else it will send you an access token along with the return url separated by a #. Since your scope was "email" in the above request url, you will get to know user's basic account details, like his username, email, first name, last name.

You must provide a redirect url for a file where you want to start a proper user session (as when the user is logged in). There you should check whether Google has provided you an access code or not in the return url.

Once you have received an access code it means you have permitted the app to use your Google account to access your basic details. Write the following code in your return url file.

Because the access token comes along with a # separator you need to extract it for the next request. Check the sample code below:

var params = {}, queryString = location.hash.substring(1),
    regex = /([^&=]+)=([^&]*)/g, m;
    while (m = regex.exec(queryString)) {
      params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
    }
    var queryStringArray = queryString.split("&");
    if(queryStringArray[0].split("=")[0] == "access_token"){
    // make a Get request to 'https://www.googleapis.com/oauth2/v1/userinfo?' + queryStringArray[0]
    // i used an ajax call to open the url from the servlet as follows:

    $.ajax({
                    type : 'GET',
                    url : '/servlet',
                    contentType: "text/xml; charset=utf-8",
                    dataType : 'xml',
                    data: {
                        action : 'googleLogin',
                        apiURL : 'https://www.googleapis.com/oauth2/v1/userinfo?' + queryStringArray[0]

                    },
                    success : function(xmlData){
                           
                    }
        });
    }else if(queryStringArray[0].split("=")[0] == "error"){
        alert("You haven't approve the app to access your account info");
        location = "your_login_page";
    }

    In your Servlet, handle the ajax action in a method as follows:

    public void getUserData() {

    URL url = new URL(request.getParameter("apiURL"));
    URLConnection conn = url.openConnection ();
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuffer sb = new StringBuffer();
    String line;
    while ((line = rd.readLine()) != null)
    {
        sb.append(line);
    }
    rd.close();
    String result = sb.toString();
    String userData = parseUserInfoOAuthResponse(result);
}

The "result" string will contain all the user profile information, like his first name , last name, email. You need to parse this data from the string.

It is obvious that Google will never allow you to access user's password, hence you will have to create a random password for the user account, which he can change anytime later.

Friday, May 11, 2012

How to use FaceBook Login for your App

You need to register your app on FaceBook first to get identified by FaceBook.
Register here !

(App Registration procedure is discussed in http://bashwithflash.blogspot.in/2012/05/photo-sharing-on-facebook-using-graph.html)

In the login page of your application, open the following request url (either by button-click, href, ajax, get request, or window.open)

"https://www.facebook.com/dialog/oauth/authorize?client_id=YOUR_APP_ID&redirect_uri=http%3A%2F%2Fwww%2Eappdomain%2Ecom%2F&scope=email,read_stream"

You will be prompted by Facebook to permit the app to access your FB account. If you reject, FB will send you an error, else it will send you an access code along with the return url. Since your scope was "email" in the above request url, you will get to know user's basic account details, like his username, email, first name, last name.

You must provide a redirect url for a file where you want to start a proper user session (as when the user is logged in). There you should check whether FB has provided you an access code or not in the return url.

Once you have received an access code it means you have permitted the app to use your Facebook account to access your basic details. Write the following code in your return url file.


<div id="fb-root"></div>
<script src="https://connect.facebook.net/en_US/all.js" type="text/javascript"></script>

<script>
    $(document).ready(function () {
        FB.init({
          appId      : 'YOUR_APP_ID', // App ID
          channelURL : 'URL_TO_CHANNEL_FILE', //must be in your domain
          status     : true, // check login status
          cookie     : true, // enable cookies to allow the server to access the session
          oauth      : true, // enable OAuth 2.0
          xfbml      : true  // parse XFBML
        });

        FB.getLoginStatus(function (response) {
            if(response.status == "unknown")
            {
                //user is not logged in to FaceBook
            }
            else if (response.status == "not_authorized")
            {
                //user has not authorized the app to access his account
            }
            else if (response.status == "connected")
            {
                if (response.authResponse) {
                    FB.api('/me', function(response) {
                        //user first name = response.first_name
                        //user last name = response.last_name
                        //user email = response.email
                        alert("Welcome " + response.first_name + " " + response.last_name);
                    });
                } else {
                    // can show a login prompt
                }
            }
        });
   });
</script>


If FB returns the login status as connected, you can retrieve the user details as response.first_name, response.last_name, response.email, which you can use to create the user's account on your app.

It is obvious that FB will never allow you to access user's password, hence you will have to create a random password for the user account, which he can change anytime later.

Wednesday, May 9, 2012

Album Sharing on Facebook using Graph API - Javascript Implementation

Single photo sharing was discussed in the previous post where the photos were posted to the default "Your_registered_app_name Photos" album.

There may be a case, when your app has multiple photo albums and the user wants to retain the album structure while sharing them. This is achieved by first creating an album, and then posting photos to it.

The API calls remain almost the same here except for creation of albums, retrieving their id's and posting photos to those ids.

Step 1: Create an Album

To post the photos into an album, you first need to have an album created on Facebook.

Add an OnClick event to the album you want to post to your Facebook account. Write the following code in the function where you are handling the OnClick event.

FB.api('/me/albums', 'post',
{
    name: 'Your_Album_Name'
}, function(response) {
    if (!response || response.error) {
        alert('Error! Please Try Again');
    } else {
        alert("Album Id ::" + response.id);
    }
    }
);

'response.id' returns you the ID of the Album created. If you check it over Facebook account, you will find an empty album 'Your_Album_Name'.

Step 2: Posting Photos To The Album

var imgURL = "YOUR_IMAGE_URL";
FB.api('/' + ALBUM_ID +'/photos', 'post', {
    message: 'photo_description',
    access_token: accessToken,
    url: imgURL
}, function (response) {
    if (!response || response.error) {
        alert('Error! Please Try Again');
    } else {
        alert('Photo Posted');
    }
    }
);

The photo is posted to the album created in your Facebook account.

Friday, May 4, 2012

Photo Sharing on Facebook using Graph API - Javascript Implementation

For quite some time I have been working on the Graph APIs by Facebook, and have so far successfully conquered to integrate them to an app I am working on.

An initial quick read is must whoever wants to use the Graph APIs. Understanding the APIs is important before you start making use of them for your applications.

How to implement Facebook Photo Sharing using Graph API in Javascript?

I am discussing sharing of photos alone in this post. Sharing of photos along with the album will be posted soon.

Register your app on Facebook and get your app credentials.

Step 1: Register your app on Facebook here.
Step 2: When you provide an app name, an App ID and App Secret Key is generated for your app. You are not suppose to disclose your app key and app secret key with any one.
Step 3: You are now required to provide your site domain. For Facebook to act as an OpenID url for your app users, you have to provide you site url as well. For testing/development phase you can provide your app domain as localhost and your site url as http://localhost:80 (or the appropriate server port).

*Even a small discrepancy in the site domain/url will not give proper results on using the Graph APIs. Hence you have to be very careful when providing the app details.

Seek user's permission to authorize the app for sharing your photos on Facebook.

Step 1: In your JSP file, add the following code:

<div id="fb-root"></div>
<script src="https://connect.facebook.net/en_US/all.js" type="text/javascript"></script>
<script>
  $(document).ready(function () {
      FB.init({
      appId      : 'YOUR_APP_ID', // App ID
      channelURL : 'URL_TO_CHANNEL_FILE', //must be in your domain
      status     : true, // check login status
      cookie     : true, // enable cookies to allow the server to access the session
      oauth      : true, // enable OAuth 2.0
      xfbml      : true  // parse XFBML
    });
 });
</script>

Note: The channelURL points to a file that you add to your local directory which helps improve communication speed in some older browsers. Without the channelURL , we are forced to use workarounds such as loading a second copy of the webpage in a hidden iframe to properly load social plugins. The workarounds increase load times and inflate referral traffic from Facebook.

Once you have initialized your Facebook APIs, it is time for the user to know that he can share his photos on Facebook if he permits your app to do so.

Step 2: Write the following Javascript code to know that user->app->facebook authorization status.

FB.getLoginStatus(function (response) {
       
        if(response.status == "unknown")
        {
            //user is not logged into facebook
         }
        else if (response.status == "not_authorized")
        {
            //user has not authorized the app to access his account
        }
        else if (response.status == "connected")
        {
            if (response.authResponse) {
                alert(response.authResponse.accessToken);
                setAccessToken(response.authResponse.accessToken);
            }
        }
    });


If you get the login status as "unknown", it means that no user is logged-in to Facebook on the current browser. So, the user is suppose to log-in.

If you get the login status as "not_authorized", it means that a user is logged in to Facebook on the same browser, but has not authorized the app to share photos. Hence you should prompt the user to a url which will allow your app to share the photos. The url looks like:

https://www.facebook.com/dialog/oauth/authorize?client_id=YOUR_APP_ID&redirect_uri=http%3A%2F%2Fwww%2Esomedomain%2Ecom%2Fdomainpage%2Ejsp&scope=user_photos,read_stream"

If you get the login status as "connected", it means that a user is logged in and has authorized the app for photo sharing. Along with the status "connected" you will receive an access token from Facebook, which will allow the user to post photos to his Facebook account.


Final step to Photo Sharing

Once login/authorization is done and the access token is received, you can go ahead and post your photos using the following Graph API:

<script>

var accessToken = "";

function setAccessToken(at){
   accessToken = at;
}

function sharePhoto( ) {

var imgURL = "http://www.someimageurl.com";
    FB.api('/photos', 'post', {
        message: 'some photo description',
        access_token: accessToken, // response.authResponse.accessToken
        url: imgURL
    }, function (response) {
        if (!response || response.error) {
            alert('Error!' + response.error.message);
        } else {
            alert('Photo Posted');
        }

    });
}

</script>


And your photo is posted on Facebook!

Facebook creates an album called "Your_app_name" Photos. Any photo sharing request from your app posts the photo by default into this album.

If you open your Facebook account, you will not see the photos immediately in your album list. You have to check your albums, approve these photos posted from your app to be shared by your Facebook account, for your friends to view. Any unapproved photo is not visible to public. This is a security check by Facebook, so as to prevent any leakage of private data by the app.

Shoot an email/comment for any queries!

Wednesday, April 18, 2012

Replacing Library Items In Flash!

Whenever you try to copy an item to the fla library, which already has one with the same name, you get the following window and are prompted to check any one of the follwoing option


Let us assume a case where any one of your symbol/movie clip, say "Symbol 1", has become corrupted, or may be there are some issues with that, so you need to either replace it, or copy it afresh to the library. Also assume that due to some reasons you had already created one copy of the symbol in the library. So we have two similar items now, "Symbol 1" and "Symbol 1 copy". If you copy the same item from somewhere else it displayes the above window. If you select the first option," Don't replace existing item", it creates a copy of it as "Symbol 1 copy". Note that this existing symbol was already there. So both the items will be same and both will be corrupted. Even the freshly copied item becomes corrupted.

If you had selected the other option, what I experienced was that even after that, the copied item was corrupted. But in most of the cases it has worked for me. So the safest option was, that I deleted all the items by that name and all the copies of that, and copied the correct item afresh from a different file.

*****Please note that corrupted item here means that its not the desired movie/symbol or something has been changed in it which you do not need anymore.

Sunday, December 18, 2011

More Flash Inteview Questions

Q11. Can you read a remotely placed sound file? Where will you store the location of the sound file?
Ans: Yes, the server will store the location of the sound file, and will send it to the client whenever required.

Q12. How do you use Tweening?
Ans: Refer to the post: http://bashwithflash.blogspot.com/2011/01/tweening-part-i.html

Q13. How do you use drag and drop in action script?
Ans: The following piece of code starts the drag for myMC display object when mouse is clicked over it, and stops the drag when the mouse is released up.

    myMC.addEventListener(MouseEvent:CLICK, onMouseClick, false, 0 , true);
    myMC.addEventListener(MouseEvent:MOUSE_UP, onMouseClick, false, 0 , true);

    function onMouseClick(e:MouseEvent)
    {
        startDrag(this);
    }
   
    function onMouseUp(e:MouseEvent)
    {
        stopDrag();
    }

Q14. What is the use of preloader? How can you create one?
Ans: Refer to the post: http://bashwithflash.blogspot.com/2011/01/creating-your-own-flash-preloader.html

Q15. What are the different design patterns available in flash?
Ans: 

    1) Factory Method Pattern
    2) Singleton Pattern
    3) Decorator Pattern
    4) Adapter Pattern
    5) Command Pattern
    6) Observer Pattern
    7) Strategy Pattern
    8) Template Method Pattern
    9) State Pattern
    10) ModelViewController Pattern
    11) Symmetric Proxy Pattern
    12) Composite pattern
   

Q16. What is the purpose of bitmap caching?
Ans: Refer to the post: http://bashwithflash.blogspot.com/2010/12/when-does-it-make-sense-to-use-bitmap.html

Q17. Which ActionScript method should be used to bring a component from the library to the stage?
Ans: attachMovie

Q18. Describe Event Flow in flash.
Ans: The event flow is conceptually divided into three parts.
    1) Capture phase: This phase comprises all of the nodes from the Stage to the parent of the target node.
    2) Target phase: This phase consists solely of the target node.
    3) Bubbling phase: This phase comprises the nodes encountered on the return trip from the parent of the target node back to the Stage.

Q19. How do you create pop-up window in flash?
Ans: The following piece of code opens up a new window on the click of "myMC" display object.

    myMC.addEventListener(MouseEvent:CLICK, onMouseClick, false, 0 , true);

    function onMouseClick(e:MouseEvent):void {
            ExternalInterface.call("window.open", "http://bashwithflash.blogspot.com/", "win", "width=500,height=500");
        }

Q20. Explain the difference between Stream Sound and Event Sound.
Ans: Refer to the post: http://bashwithflash.blogspot.com/2010/12/sound-bound.html

Thursday, December 15, 2011

Flash Interview Questions

This post mainly deals with the most popular flash interview questions that we come across now. Hope it fulfills the purpose.

Q1. What is the default frame rate?
Ans: The default frame rate is 24 frames per second (fps) for the new versions. In previous versions of Flash, the default frame rate is 12 fps.

Q2. From which version of Adobe flash player, you see the compatibility of AS 3.0?
Ans: Flash Player Version 9

Q3. How many types of symbols can be there in any flash application? Name them.
Ans: 3, namely, Button, Movieclip and Graphic.

Q4. How does the it affect the frame rates of a swf file when it is loaded into another?
Ans: The new swf file takes the frame rate of the parent swf file and runs with that.

Q5. How can you change the frame rate with the help of code, with and without using the stage property?
Ans: Refer to the post: http://bashwithflash.blogspot.com/2011/09/frames-and-frame-rates.html

Q6. Why do we need to embed fonts to a dynamic text field?
Ans: Refer to the post: http://bashwithflash.blogspot.com/2010/12/dynamic-text-look-and-feel.html

Q7. How are _root and _level different?
Ans: Refer to the post: http://bashwithflash.blogspot.com/2011/08/root-and-level.html

Q8. How are _root and parent different?
Ans: "_root" is the main timeline of the currently active movie. "parent" is the container movie of the currently active movie clip.

Q9. Write a code sample to draw line between the given two points?
Ans: We use the "lineTo(x,y)" API. Here is the example code:

    var mc:Sprite = new Sprite();
    mc.x = 50;
    mc.y = 50;
    this.addChild(mc);
    mc.graphics.lineTo(100,100);

This sample code defines a movie clip at (50,50), and draws a line from this point to (100,100). Now line is the mc. We can further draw more lines to other points also.

Q10. How do you add listener to a particular display object? What are the arguments that you need to pass to the listener?
Ans: Refer to the post: http://bashwithflash.blogspot.com/2011/01/capturing-events-in-flash-as3-part-ii.html


Apart from the above questions, OOP concepts are also asked. The candidate might also be asked to make a small flash application.

Readers are most welcome to make any correction to the answers they think is wrong. Also keep adding the questions too.

*More questions to follow soon in the next post.

Saturday, September 24, 2011

Working with BUTTONS in Flash

Buttons are a very common element of any application. Be it an e-game, an online submission form, or even a page navigator, usually the buttons control the flow of the application. This post mainly deals with creation of button, and a hands-on example of it.

Why do we need buttons in our application?
Buttons are mainly "event dispatchers". A dispatched event always has some purpose and so does the click of a button. Some action is always associated with a button click. Let us take a very common example. All of us use google search engine very often. After typing our search words, we either press "Enter" key or press the "Search" button. What does this button do? The button notifies the engine that the search entries are done, so perform the next action, that is, output those results which match with our search keywords. So, button dispatches a click event here. Click event is one of the mouse events (that we have already discussed in one of our previous posts).

Steps to create a simple button:

1. Open flash IDE (CS3/CS4 or whatever is the latest version that we are using)
2. Select a text tool and write some text on the stage.


3. Right click on the text, select "Convert to Symbol"



4. Select Button from the drop-down and give some name to the symbol.


5. Give some instance name to this symbol.



6. Double click on this newly created button. You would observer that there are 4 frames in it namely "Up", "Over", "Down" and "Hit". These are default fields for any button. As the name suggests, all of them are button states. Notice that only the "Up" frame has some content in it.



7. Click on "Over" frame, press F6 key. A keyframe gets created with the content same as the "Up" frame. Change the text to distinguish between the two frames.



8. Similarly, create a keyframe in the "Down" state and keep a different text with a different color there.



9. The last frame "Hit" defines the hit area of the button which is sensitive to the mouse click, or the area of the button which we want to respond to any click.

10. Publish the file and you see a simple button, in hovered, hit, and released states. Your file, when published, would replicate the following:



Once your button is created, you can associate multiple mouse events to it (as buttons actions are mostly mouse sensitive). The mouse events are already discussed in one of the earlier posts : Capturing Events in Flash : Part II - Creating Event Handlers

Tuesday, September 20, 2011

Frames and Frame Rates

Frames and animations are very closely related. All the animations happen in frames, or frames make the animation happen. Let us understand it like this:

I am sure all of us have watched at-least one cartoon movie. Cartoon movies have been there for like decades. Even before the time when the technological concept for animation was known to us, people have been watching them. Cartoon movies are full of animation, hence they are also called animated movies. But how were they made in those years? Animated movies were made on frames, not the flash frames, but the transparent sheets that we put under the projector machine and view on the screen. The artists use to sketch the cartoon frames on those transparent sheets, which were projected on big screens. All the movements of the cartoon characters were captured in those frames. The projector used to run the bundle of frames so fast, that it looked like a perfect animation.

Flash makes the life easy, as we can easily change any graphic image as we need. Each of these graphics are kept in successive frames, and once the file is run, we see an animation on our computer screens. The clarity of animation depends a lot on the frame rate at which we run it.

What is a Frame?
A frame, in a timeline, is the snapshot or drawing of the currently worked on instructions executed by the flash player. A frame can contain any flash symbol, it can contain action script code, and can even have a label name for the user's convenience.

There is something called Key frame. A key frame is any drawing that defines smooth transition between 2 points. The main use of key frames comes into picture with tweening effects (as explained in the older posts). If not tweening, then key frames with different pictures/graphics in a single row of a timeline can bring out a good animation.

What shall be the number of frames for a good animation?
To create an illusion of a motion we need to have a transition of the moving object from one point to another. It all depends on the intermediate frames, that how jerky or how smooth the transition happens. Usually, more number of intermediate frames give a smooth transition effect, as even the minute changes of the motion are depicted in each frame picture. This is true when we do not consider the frame rate for our animations (which is explained in the next section of this post).

Frame Rates
The frame rate determines how many frames are played per second. This value is measured in frames per second, commonly referred to as, fps. This is calculated with the formula below:

                      Frames Per Second    =    Number of Frames
                                                               -----------------------
                                                                   Time in Seconds

The higher the fps value, faster is the animation played. Low values of fps usually cause slow and jerky animations. The frame rate solely depends on the kind of animation that we make. Keeping a higher frame rate for complex image animations makes the computer to do much work as compared to the work with lower frame rate. High frame rate for simple content doesn't cause any problems usually.

In earlier versions of flash the default fps rate was 12, but in the recent versions it is 24. Means 24 frames are played in every 1 second.

Modifying the fps values with the help of UI and programmatically
The most common way to set our own fps value is by changing the value in the Properties panel and making it global for our entire application. Check the screenshot below:


As already mentioned earlier, the fps value in the latest version of flash have been kept 24, which is quite good to work with.

There may be a case when you might want to change the fps value dynamically or when you application is running. With AS 3.0 programming, we can easily access the frame rate. This is how the fps value is accessed in AS 3.0

                                             stage.frameRate

Stage property can be accessed from anywhere, hence we can change the fps value whenever we want to.

                                            stage.frameRate = 30;


We have a very common flash interview question, which talks about frame rates of our swf files.
The question says, that we have 2 swf files, A and B. A has frame rate of 20 and B has 30. B is loaded into A. How will it affect the frame rate of B.

The answer is very simple and obvious. Since B is loaded into A, A becomes the parent movie clip for B. So the global fps value for A now becomes the fps value for B as well. Hence B will also run at the same rate as A does, which is 20. This means, the file B will run at a slower rate in A, as compared to when running alone. If the fps values are reversed for A and B, and then B is loaded into A, then B would run at a faster rate (30 fps). So it all depends on the frame rate of the parent swf file.

However, it is very well possible to play the movie clip inside the parent movie clip retaining it's own frame rate. This can be achieved programmatically. Take an example, we have a parent movie clip which runs at 24 fps, there is another movie clip, B, which runs at 8 fps. When B is loaded into A, we want that B should run at it's own frame rate. We use a simple logic here. Divide the fps of A by fps of B. We get '3'. So, when A runs 3 frames, B should run 1 frame. Check the following piece of code:

                   frame_count = 0;
                   bMovie.stop( ); 
                  onEnterFrame = function( )
                  {
                               frame_count++;
                               if (frame_count >= 3 && bMovie._currentframe < bMovie._totalframes)
                              {
                                                bMovie._currentframe++;
                                                bMovie.gotoAndStop(bMovie._currentframe);
                                                frame_count = 0;
                              }
                  }
                  stop( );
 

With the encounter of every new frame of the main movie, A, the counter "frame_count" will increment by 1. When the count reaches 3, the next frame of B is played.



Thursday, September 15, 2011

Difference between a Graphic and a MovieClip

Any flash symbol can be either of the following:

1. Button
2. Movie Clip
3. Graphic

Button will be part of later posts. This post mainly deals with movie clip and graphics. First let us understand the two.

Both movie clips and graphics can be used to create animations. However, there are many differences between them. A graphic is a static object but movie clips can be dynamically worked upon. Only movie clips can have instances and instance names. Consequently they can be uniquely identified using the code. Whenever any movie clip is accessed, a copy of it is created from the flash library and the animation is performed over it. This copy so created could be blurred, slightly distorted, skewed, or can have multiple differences from the original movie clip, but only during run-time. This is just to cut down the computer memory usage by keeping the size of the swf file small.



Lets analyze the first statement, that both these symbols can contain animations.
In a movie clip, the animation is done on and by the graphics only. Here, all the parts of any animating body can be controlled independently, as they are part of separate timelines and also because we can have timeslines inside the main timesline of the movieclip. But for the graphics, all the animations happen in a single timeline. This makes the graphics less dynamic.


In other words,
The timeline of a Graphic Symbol instance is dependent on the timeline of the movie the instance is placed in.
The timeline of a Movie Clip instance is independent of the timeline of the movie the instance is placed in.
 Let us try a fun example.

Put any graphic image in the first frame of the main timeline. Place this image with slight variation in the successive frames for, say, 25 frames. If you publish this file, you would see some animation running through frame 1-25. Try deleting 10 frames from this, and the animation runs through only first 15 frames. If we delete all other frames except the first, and then publish the file, we see a static image, with no animation. In all the above cases, the animation runs in loop, from 1st frame to the last, and then back to first frame.

Suppose we convert any symbol to a movie clip, no matter, how many frames we add or subtract from the main timeline, the movie clip runs in loop in its own time line.



Friday, August 19, 2011

_root and _level

Often we get confused between the usage of _root and _level. The two are however very different from each other._root is the main timeline of the currently active swf file/movie clip whereas the _level defines the active order of the swf file. A swf file which loads a flash application is automatically treated as _level0. _root now refers to the main timeline of the _level0. Suppose the application loads another swf file, this would be addressed as _level1. When _level1 is in use, the _root will change from main timeline of _level0 to the main timeline of _level1.

Generalizing:  If a movie clip that contains _root is loaded into another movie clip, _root refers to the main timeline of the loading movie clip, and not the timeline that contains _root.

Any swf file can be loaded at any level. See an example below:

loadMovieNum("test.swf", 5);

The above code loads the "test" swf file at level 5. If we wish to

"_level" is accessed like any other movie. If we wish to stop the playhead of the main timeline of the swf file, we can add the following code:

_level5.stop()

 If we wish to execute data inside any particular frame (say frame 7), we can use the following chunk of code.

_level5.gotoAndStop(7)
 
 _root can be used similarly as follows: 
 
_root.stop() stops the Timeline of the level containing the currently executing script 
 
  
There is something what we call as _lockroot. _lockroot is used whenever we want to ensure that _root refers to the main timeline of the loaded movieclip even if another movieclip is also loaded. Setting this property to "true" does the required job.

myMovieClip._lockroot = true;

Where myMovieClip is the one to which _root should refer even if any other movieclip is loaded.

The concept of both _root and _level is absent in action script 3.0.

Saturday, January 29, 2011

Tweening: Part - I

Tweening word is the formation from the words "in between". As suggested by the meaning, tweening has something to do with whatever motion is happening "in between" 2 states. For example, a ball drops from 10th floor of a building to the ground. So here, whatever motion the ball has "in between" the 10th floor and the ground constitutes the tweening effect.

We can make use of the tweening effect in 2 ways:

1. Using time lines
2. Using code / action script

To add the tween motion using the timeline, add the first state of the object in the first frame. The state could be any property, like, color, dimensions, x-y co-ordinates etc. Leave 18 frames in between, and add a key frame to the 20th frame. Add second state of the same object (change any of the above mentioned properties). Right click on the timeline anywhere between the first and the 20th frame. There will be an option to add tween effect. Select that, and you will find the the tween motion is added to your timeline. Press enter while in the first frame, you will see how the tween effect comes out in the time line.

Tweening can be added using action script as well. The tween class is not included in the flash movie by default. It needs to be imported as follows:

import fl.transitions.Tween;
import fl.transitions.easing.*;


Tween class is to add tween motion to the desired object. Lets check what does "easing" do. "Easing" refers to gradual acceleration or deceleration during an animation, which helps your animations appear more realistic. The fl.transitions.easing package provides many easing methods that contain equations for this acceleration and deceleration, which change the easing animation accordingly.

Another class TweenEvent can be imported as follows (though not mandatory)

import fl.transitions.TweenEvent;

This class besically contains a few events, like, MOTION_CHANGE, MOTION-FINISH, MOTION_START, etc etc. Such events can be fired to handle any other changes as per the requirements. This will be explained in the next post.

Now let us see how tweening class is used. Check out the syntax below:

var myTween:Tween = new Tween(object, "property", EasingType, begin, end, duration, useSeconds);

The parameters mentioned above are mandatory to be specified whenever the Tween class is instantiated. Each of them is explained as follows:

  1. object - This is the instance name of the object which will be animated or on which tween is applied. Example: myMovie, myTxt
  2. property - This is the name of the property which will be animated, it must be specified as a string (in double quotes). Example: "alpha", "scaleX", "scaleY", "x", "y".
  3. EasingType - The easing type will determine how the tween animation will flow so that it looks natural and real. Examples: Strong.EaseIn, Elastic.EaseOut, Back.EaseInOut.
  4. begin - This is the position from which the animation will start, it must be specified as a number.
  5. end - This is the position at which the animation will stop, it must be specified at as a number.
  6. duration - This is the period for which the animation will run, the default unit for it is frames, however, the unit can be set in seconds if you set the next parameter as true.
  7. useSeconds - Set this parameter to true if you want to the duration to be measured in seconds instead of frames
For example:

var myTween:Tween = new Tween(myMovie, "x", Strong.easeOut, 25, 100, 10, true);

In the above script, observe the third parameter, Strong.easeOut. This is a function which has a property easeOut. Like "Strong" we have 5 more functions, each of them described as follows:
  1. Regular: the motion speed will gradually increase or decrease in speed as specified by the easing method.
  2. Bounce: the motion will bounce back a few steps when it reaches the end position before settling at it.
  3. Back: the motion will go beyond the end position before bouncing back into it.
  4. Elastic: a mixture of Bounce and Back effects combined.
  5. Strong: a more emphasized Regular effect.
  6. None: no easing, the motion will not speed up.
Each of these functions must be then be configured using one of the easing methods to determine at which part of the tween it shall apply the effect, i.e. at the start of it, the end of it, both, or none:
  1. easeIn: - The tween effect is applied to the start of the animation.
  2. easeOut: - The tween effect is applied to the end of the animation.
  3. easeInOut: - the tween effect is applied to the start and end of the animation.
  4. easeNone: - no tweening effect is applied, to be used with the None tween function.

Sunday, January 23, 2011

Creating your own Flash Preloader

We see preloaders in many flash applications these days. An animation, a video, or a movie, or even a game, start mostly with a preloader now. Once the preloader is shown, only then the actual animation starts playing.

What is a Preloader ?

A preloader is a horizontal bar that keeps scaling up and the intensity of the scale depends on the loaded bytes of the file. When the files are loaded completely, the bar reaches its maximum length. The intensity of the bar load-scale is calculated as per the following formula:

                          load-scale = (bytes loaded) / (total no of bytes)

How to create a simple Preloader ?

Step 1: Create a horizontal bar, and convert it into a movie clip.


Step 2: Give an instance name, say, loadMC.



Step 3: Create a dynamic text field, in the same layer (though not mandatory).



Step 4: Give instance name to this text field as well, say, loadTxt



Step 5: Create another layer for the code / script.



Step 6: Put a stop( ) to the first frame, and then add an event listener, ENTER_FRAME, so that the code is executed as soon as the first frame is encountered, and because there is no other frame, the code would keep on executing. Then the files-load percentage is calculated by the above formula, which is displayed in the dynamic text field.



Step 7: Once this is done, press Ctrl+enter. You will get the swf file, displaying the complete horizontal bar and displaying "100%" text below it. Now press Ctrl+enter again, and then the actual preloader function is observed. If not, then go to the "view" options in the swf window and select the download speed according to your requirements and convinience.

Wednesday, January 19, 2011

Capturing Events in Flash : Part III - Creating Custom Events

The way we use the in-built events in action script, similarly we can create our own events and handle them at our own requirements. The only extra thing that needs to be done is the creation of class which will hold our user-defined or custom events.

However, there are few things to be noted in case of custom events. For the in-built event handling, we have a class called "clone( )". As by the name, its clear that it is something to do with a "copy". Basically, clone( ) function creates a copy of the event instance with all the properties associated to it. This is handled implicitly for the pre-defined events. But for the custom events, we need to override this function to our custom event class. This will help duplicate the custom event instance with all the custom properties associated to it.

Why do we need clone( ) function ?

With clone( ) function, the new event object includes all the properties of the original event. Hence, if the event is re-dispatched, then it takes the properties of the already dispatched same event. If you do not set all the properties that you add in your event subclass, those properties will not have the correct values when listeners handle the re-dispatched event.

We can pass arguments as well to these custom events, which also should be cloned.

Another function that needs to be written explicitly for a custom event class is "toString( )". It returns a string containing all the properties of the current instance. This is also to be overridden in the custom event class.
  
Now, let us assume we want to dispatch an event on completion of some animation, event name say "ANIMATION_COMPLETE". We will add an event listener to the movie clip, and will dispatch the event from the last frame, after which the event is handled accordingly.

Check out the code sample below:

package 
{  
         import flash.events.Event;  

         public class CustomEventDemo extends Event  
         {  
                    public var customProperty:String = "";   

                    public var customArgs:*;

                    public static const ANIMATION_COMPLETE:String = "AnimationComplete";
 
                    public function CustomEventDemo(custom:String, custArg:*=null, type:String, bubbles:Boolean = false, cancelable:Boolean = false)  
                   {  
                                // call the constructor of the extended class  
                                 super(type, bubbles, cancelable);  
 
                                // set the customProperty property  
                                customProperty = custom;   


                                // set the customArgs arguments
                                customArgs = custArg;
                   }   


                   public function get args():*
                   {
                                return customArgs;
                   }
 
                   override public function clone():Event  
                   {  
                                return new CustomEventDemo(customProperty, args, type, bubbles, cancelable);  
                   }   


                   override public function toString():String
                   {
                                return formatToString("CustomEventDemo", "args", "type", "bubbles", "cancelable", "eventPhase");
                   }
 
         }  
 
}

Wednesday, January 12, 2011

Implementing MVC Architecture in AS3

MVC stands for Model View Controller. Each of these is an important component for any game development. Their roles are explained as follows:

1.Model: It manages the behavior of any application. It tells how the complete data is structured. It responds to any request made about the game state, mostly by the view.
2.View: It is the display of the information or data to the user.
3.Controller: It interprets the inputs from the user, informs the model to change it, making the view to display the changes accordingly.

In short, the Controller interprets the input, processes it in the Model, and gives the output to the View.


                                                  Input --> Processing --> Output
                                                  Controller --> Model --> View





Take an simple example of a calculator. Calculator is an electronic device that we use in our day to day life. Suppose we want to perform addition operation of 2 numbers. Let us see how the MVC architecture applies here.

First Number Input --> Press the number key of the View --> Input goes to the controller --> controller updates it in model --> the pressed number key is displayed by the view
Operation Input --> Press the "+" key of the View --> Input captured by the controller --> controller updates the model
Second Number Input --> Press the number key of the View --> Input goes to the controller, addition operation is performed --> controller updates the second input and the final output in the model --> the pressed number key is displayed by the view
Result --> Press the "=" key of the View --> Input captured by the controller --> view displays the result as stored in the model

With an MVC architecture, it becomes very easy to write the code in an organized way, and it can then be easily understood by the others as well.

Using MVC in AS3 programming.
Again taking a simple example, capturing data on pressing the keys from the keyboard and priting it in view.

Model will store the data (pressed key) and will be used to retrieve the same.
Hence this will have 2 functions (setter and getter). Model Interface, IModel.as, is written as follows:
package
{
         import flash.events.*;
         public interface IModel
        {
                  function setKeyId(key:uint):void
                  function getKeyId( ):uint
         }
}

The Model.as file becomes:

package
{
         import flash.events.*;
         public class Model implements IModel
        {
                 private var lastKeyId:uint = 0;
                 public function setKeyId(key:uint):void
                {
                         this.lastKeyId = key;
                         dispatchEvent(new Event(Event.CHANGE)); // dispatch event
                }

                 public function getKeyId( ):uint
                {
                         return lastKeyId;
                }
        }
}

All the keyboard events are handled in the Controller. Controller Interface will have just one function to capture the keyboard event:

package
{
         import flash.events.*;
         public interface IController
        {
                  function keyPressHandler(event:KeyboardEvent):void
        }
}

The Controller.as files implements the IController interface:

package
{
         import flash.events.*;
         public class Controller implements IController
        {
                  private var model:IModel;
                  public function Controller(aModel:IModel)
                  {
                             this.model = aModel;
                  }
                 
                 public function keyPressHandler(event:KeyboardEvent):void
                 {
                             model.setKeyId(event.charCode); // change model
                 }
        }
}

The View.as file provides the view to the user, wherein he selects the keyboard key to be pressed, and when the key is presses, View class is useful again to print the key id on the screen.

package
{
         import flash.events.*;
         import flash.display.*;

         public class View
         {
                  private var model:IModel;
                  private var controller:IController;
                  public function View(aModel:IModel, oController:IController,target:Stage)
                  {
                            this.model = aModel;
                            this.controller = oController;

                            // register to receive notifications from the model
                            model.addEventListener(Event.CHANGE, this.update);

                            // register to receive key press notifications from the stage
                            target.addEventListener(KeyboardEvent.KEY_DOWN, this.onKeyPress);

                   }

                  private function update(event:Event):void
                  {
                           // get data from model and update view
                           trace(model.getKeyId( ));
                  }

                  private function onKeyPress(event:KeyboardEvent):void
                  {
                          // delegate to the controller (strategy) to handle it
                          controller.keyPressHandler(event);
                   }
          }
}

And finally, the MainClass.as, where all the class instance are created is :

package
{
         import flash.display.*;
         import flash.events.*;
         public class Main extends Sprite
         {
                  public function Main( )
                  {
                           var model:IModel = new Model( );
                           var controller:IController = new Controller(model);
                           var view:View = new View(model, controller, this.stage);
                  }
         }
}

Let us examine how this complete MVC program work.

MainClass.as class creates the instances of the model, view and the controller classes, which implement the functions of their respective interfaces. The keyboard keys are in the user's view. So, if any key is presses, the event is captured in view and handled in the controller class. The controller updates the model about the key pressed. After which the model dispatches CHANGE event, which signifies that keyboard captured value has been changed (with respect to the previous pressed key value). This event is handled in the view and the keyboard value is displayed to the user on his screen.

References: http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/actionscript/pdfs/ora_as3_design_patterns_ch12.pdf