Friday, January 21, 2011

Passing arguments to SWC using flashVars


·         If you are using the generated wrapper from Flash Builder, then you add flashVars variables by creating an object called flashvars,
·         Setting properties on that object, and then passing that object to the swfobject.embedSWF() method of SWFObject.
Main Topics
·         Normal Method.
·         Passing through JSP page (two cases).
·         Passing through PHP page.
·         Passing via browser.
·         Retrieval from Flex end.

Normal Method.
·         Here I explain an example which add two properties to flashvars object (name,home) directly.
·         Then passes that object to the embedSWF() method.


<script type="text/javascript">
    var swfVersionStr = "10.0.0";
    var xiSwfUrlStr = "playerProductInstall.swf";
    var flashvars = {};
    flashvars.name = "Rohit";
    flashvars.home = "Sunshine";
    var params = {};
    params.quality = "high";
    params.bgcolor = "#ffffff";
    params.allowscriptaccess = "sameDomain";
    var attributes = {};
    attributes.id = "TestProject";
    attributes.name = "TestProject";
    attributes.align = "middle";
    swfobject.embedSWF("FlashVarTest.swf", "flashContent", "100%", "100%",  
    swfVersionStr,xiSwfUrlStr, flashvars, params, attributes);
    swfobject.createCSS("#flashContent", "display:block;text-align:left;");
</script>

·         If your wrapper uses the <object> and <embed> tags, you can pass variables to your applications by using the flashVars properties in the <object> and <embed> tags in your wrapper.
·         You do this by adding ampersand-separated sets of name-value pairs to these properties.
·         Here is an example with the flashvars properties mentioned above.
<html>
<head>
<title>code/wrapper/SimplestFlashVarTestWrapper.html</title>
<style>
    body {
        margin: 0px;
        overflow:hidden
    }
</style>
</head>
<body scroll='no'>
<table width='100%' height='100%' cellspacing='0' cellpadding='0'><tr><td valign='top'>
<h1>Simplest FlashVarTest Wrapper</h1>
 
    <object id='mySwf' classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' height
='100%' width='100%'>
        <param name='src' value='FlashVarTest.swf'/>
        <param name='flashVars' value='name=Rohit&home=Sunshine'/>
        <embed name='mySwf' src='FlashVarTest.swf' height='100%' width='100%' 
        flashVars='name=Rohit&home=Sunshine'/>
    </object>
 
</td></tr></table>
</body>
</html>

Passing through JSP page (case 1).
·         In this case we are passing the value via JSP page. (ie, use JSP to return the wrapper)
·         The value of the flashVars properties do not have to be static.
·         Here we add the property ‘variableInFlexSide’ to flashvars object.
·         In this case JSP expression for the value of the flashVars properties that can be evaluated to a String.

<script type="text/javascript">
    var swfVersionStr = "10.0.0";
    var xiSwfUrlStr = "playerProductInstall.swf";
    var flashvars = {};
    flashvars.variableInFlexSide = ${variableName};
    var params = {};
    params.quality = "high";
    params.bgcolor = "#ffffff";
    params.allowscriptaccess = "sameDomain";
    var attributes = {};
    attributes.id = "TestProject";
    attributes.name = "TestProject";
    attributes.align = "middle";
    swfobject.embedSWF("SampleProject.swf", "flashContent", "100%", "100%", 
    swfVersionStr,xiSwfUrlStr, flashvars, params, attributes);
    swfobject.createCSS("#flashContent", "display:block;text-align:left;");
</script>


    <object id='SampleProject' classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000    ' height='100%' width='100%'>
        <param name='src' value=' SampleProject.swf'/>
        <param name='flashVars' value='variableInFlexSide = ${variableName}'/>
        <embed name='SampleProject' src='SampleProject.swf' height='100%' 
         width='100%' flashVars='variableInFlexSide = ${variableName}'/>
    </object>


Passing through JSP page (case 2)..
·         Another case using JSP to return the wrapper.
·         The following example uses the values stored in the HttpServletRequest object.
·         In this case, you can use form or query string parameters

<%
  String variableName = (String) request.getParameter("firstname");
%>
 
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
    <head>
        <title>DynamicFlashVarTestWrapper.jsp</title>
        <script type="text/javascript" src="swfobject.js"></script>
 
<script type="text/javascript">
    var swfVersionStr = "10.0.0";
    var xiSwfUrlStr = "playerProductInstall.swf";
    var flashvars = {};
    flashvars.variableInFlexSide = "<%= variableName %>";
    var params = {};
    params.quality = "high";
    params.bgcolor = "#ffffff";
    params.allowscriptaccess = "sameDomain";
    var attributes = {};
    attributes.id = "TestProject";
    attributes.name = "TestProject";
    attributes.align = "middle";
    swfobject.embedSWF("SampleProject.swf", "flashContent", "100%", "100%",  
    swfVersionStr,xiSwfUrlStr, flashvars, params, attributes);
    swfobject.createCSS("#flashContent", "display:block;text-align:left;");
</script>

</head>
    <body>
        <div id="flashContent"/>
   </body>
</html>

Passing through PHP page.
·         Here we use PHP expressions to pass query string parameters in a wrapper.

<html lang="en"> 
<head> 
<?php 
    @ $variableName= $_GET['firstname']; 
?> 
<script type="text/javascript" src="swfobject.js"></script> 
 
<script type="text/javascript">
    var swfVersionStr = "10.0.0";
    var xiSwfUrlStr = "playerProductInstall.swf";
    var flashvars = {};
    flashvars.variableInFlexSide = "<?php echo $variableName; ?>"  
    var params = {};
    params.quality = "high";
    params.bgcolor = "#ffffff";
    params.allowscriptaccess = "sameDomain";
    var attributes = {};
    attributes.id = "TestProject";
    attributes.name = "TestProject";
    attributes.align = "middle";
    swfobject.embedSWF("SampleProject.swf", "flashContent", "100%", "100%", 
    swfVersionStr,xiSwfUrlStr, flashvars, params, attributes);
    swfobject.createCSS("#flashContent", "display:block;text-align:left;");
</script>

</head> 
<body > 
    <div id="flashContent"> 
</body> 
</html>
 
 
Passing via browser.
·         If we requests the SWF file directly in the browser, without a wrapper,
·         We can access variables on the query string without providing additional code in the wrapper (because there is no wrapper).
·         The following URL passes the value of variable
        http://localhost:8100/flex/SampleProject.swf?variableInFlexSide=Rohit
 
·         If we want to pass more than one variable.
 

Retrieval from Flex end.
·         To access the values of the flashVars properties, we want to use FlexGlobals object’s topLevelApplication.parameters property.
·         We want to assign the values of these properties after the Application’s creationComplete event is dispatched.
·         Otherwise, the run-time properties might not be available when we try to assign their values to local variables.
·         The following example defines the variableInFlexSide and binds them to the text of Label controls in the initFlashVars () method:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                     xmlns:mx="library://ns.adobe.com/flex/mx"
                     xmlns:s="library://ns.adobe.com/flex/spark"
                     creationComplete="initFlashVars()">

      <fx:Script>
            <![CDATA[
                  import mx.core.FlexGlobals;

                  /**
                   * Declare bindable properties in Application scope.
                   */
                  [Bindable]
                  public var localVariable:String;

                  /**
                   * Assign values to new properties.
                   */
                  private function initFlashVars():void
                  {
                        localVariable 
                   =FlexGlobals.topLevelApplication.parameters.variableInFlexSide;
                  }
            ]]>
      </fx:Script>

      <s:HGroup>
            <s:Label text="Varible Value : "/>
            <s:Label text="{localVariable}"
                         fontWeight="bold"/>
      </s:HGroup>
</s:Application>



Multiple Language Support-SDK 3.5


Flex 3 / Flex 4 allow switching among multiple languages in flex application.
Here I explain how this makes possible in a flex 3 application.
The following steps need to be followed.
·         Step 1: Add unsupported locale in the folder structure.
·         Step 2: Creating my-resources, a flex project
·         Step 3: Creating my-library, a flex library project
·         Step 4: Creating my-application, a flex project
So let us build a small flex application, from which we can switch from US English to French at run time and vise-versa.  
For the purpose of this exercise, we create an assumption that the language switching is implemented in the main application while the contents are coming from the project library.
Step 1: Add unsupported locale in the folder structure.
By default flex sdk ver. 3.0 supports the resources US English (en_US), Japanese (ja_JP).These 2 are already configured. We are trying to add a new language resource French (fr_FR).
For this the flex framework needs to be configured to recognize the locale.
·         First go to the command prompt.
·         Then change the directory to {Flex SDK Path}     (for e.g.: C:\Program Files\Adobe\Flash Builder4\Adobe Flash Builder 4\sdks\4.0.0\bin).
·         Then execute the command copylocale en_US fr_FR
·         Refer the following image.



Executing copylocale command
Step 2: Creating my-resources, a flex project
We are creating this project in terms of reusable scenario. Now create a project named my-resources in your default flex workspace. So we can refer this common project via ‘${DOCUMENTS}/my-resources’.
·         Add the folders ‘locale’, ’en_US’ and ‘fr_FR’ as shown in the following image.
                                                                                             
·         Add ‘resources.properties’ file in both folders ’en_US’ and ‘fr_FR’ as shown in the above image.
·         Copy the following code & paste to the file {Flex local folder path} \locale\en_US\ resources.properties.

       # ${DOCUMENTS}/my-resources/locale/en_US/resources.properties
       ENGLISH=English
       FRENCH=French – Français
       TEXT=Let's switch languages!
·         Copy the following code & paste to the file {Flex local folder path} \locale\fr_FR\ resources.properties.
      # ${DOCUMENTS}/my-resources/locale/fr_FR/resources.properties
      ENGLISH=Anglais - English
      FRENCH=Français
      TEXT=Changeons de langue !
Step 3: Creating my-library, a flex library project
                                                       
·         Create a library project named ‘my_library’.
·         Then select the properties of the project ‘my_library’.
·         Select the option ‘Flex Library Build Path’.
·         Select the tab ‘Source path’.
·         Click Add Folder…
·         Paste the line to the text area
      “ ${DOCUMENTS}/my-resources/locale/{locale} “ and click OK.
                                              
·         Then set the additional compiler arguments for the library project.
·         Select the properties of the project ‘my_library’.
·         Select the option ‘Flex Library Compiler’.
·         Replace the Additional compiler arguments with the following string 
       “-locale=en_US,fr_FR -include-resource-bundles resources “ 
        and click Apply then OK.

                                                        
·         Add a folder inside src folder named ‘il8n’.
·         Create a new mxml file inside the new folder named ‘MyComponent’.
                                     
·         Replace the file contents with the following code.
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Metadata>
[ResourceBundle("resources")]
</mx:Metadata>
<mx:Label text="{resourceManager.getString('resources', 'TEXT')}"/>
</mx:Canvas>
·         Build the library project.
·         We get the output file from the ‘bin’ folder as shown in the above figure.
·         Generated ‘my_library.swc’ contains the localization for both en_US,fr_FR locales.
Step 4: Creating my-application, a flex project
                                                         
·         Create a Flex project named ‘my-application’.
·         Then select the properties of the project ‘my-application’.
·         Select the option ‘Flex Build Path’.
·         Select the tab ‘Source path’.
·         Click Add Folder…
·         Paste the line to the text area “ ${DOCUMENTS}/my-resources “ 
      and click OK.
                                                               

·         Then select the properties of the project ‘my-application’.
·         Select the option ‘Flex Build Path’.
·         Select the tab ‘Library path’.
·         Click Add Project…
·         Browse the library project already created ‘my_library’ and click OK.
                                                    

·         Then set the additional compiler arguments for the main project.
·         Select the properties of the project ‘my-application’.
·         Select the option ‘Flex Compiler’.
·         Replace the Additional compiler arguments with the following string
      " -locale=en_US,fr_FR -source-path=locale/{locale} -allow-source-path- overlap=true and click Apply then OK.

                                                                    

·         Edit the main mxml file (here it is ‘MyApplication.mxml’).

                                                                                      

·         Replace its content by the following code.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
                        layout="absolute"
                        creationComplete="handleCreationComplete();"
                        xmlns:il8n="il8n.*">
      <mx:Metadata>
            [ResourceBundle("resources")]
      </mx:Metadata>
      <mx:Script>
            <![CDATA[
                  import mx.events.ItemClickEvent;
                  private const en_US:String="en_US";
                  private const fr_FR:String="fr_FR";

                  private function handleCreationComplete():void
                  {
                        languageType.selection=english;
                  }

                  private function handleLanguageTypeClick(event:ItemClickEvent):void
                  {
                        var rbg:RadioButtonGroup=event.currentTarget as RadioButtonGroup;
                        switch (rbg.selectedValue)
                        {
                              case en_US:
                              case fr_FR:
                                    resourceManager.localeChain=[rbg.selectedValue];
                                    break;
                              default:
                                    break;
                        }
                  }
            ]]>
      </mx:Script>
      <mx:Panel title="Localized Flex Library"
                    layout="absolute"
                    horizontalCenter="0"
                    verticalCenter="0"
                    backgroundColor="#FFFFFF"
                    backgroundAlpha="0.75">
            <mx:VBox left="10"
                         right="10"
                         top="10"
                         bottom="10">
                  <mx:VBox>
                        <mx:RadioButtonGroup id="languageType"
                                                       itemClick="handleLanguageTypeClick(event);"/>
                        <mx:RadioButton id="english"
                                                value="en_US"
                                                label="{resourceManager.getString('resources', 'ENGLISH')}"
                                                groupName="languageType"/>
                        <mx:RadioButton id="french"
                                                value="fr_FR"
                                                label="{resourceManager.getString('resources', 'FRENCH')}"
                                                groupName="languageType"/>
                  </mx:VBox>
                  <mx:HRule width="100%"/>
                  <il8n:MyComponent/>
            </mx:VBox>
      </mx:Panel>
</mx:Application>

Now we created a flex project (using sdk 3.5) which can switch among multiple languages.