Search This Blog

2009-11-30

Class Inheritance in C#

using System;

public class ParentClass
{
public ParentClass()
{
Console.WriteLine("Parent Constructor.");
}

public void print()
{
Console.WriteLine("I'm a Parent Class.");
}
}

public class ChildClass : ParentClass
{
public ChildClass()
{
Console.WriteLine("Child Constructor.");
}

public static void Main()
{
ChildClass child = new ChildClass();

child.print();
}
}

Output:

Parent Constructor.
Child Constructor.
I'm a Parent Class.

using System;



public class Parent

{

string parentString;


public Parent()

{

Console.WriteLine("Parent Constructor.");

}


public Parent(string myString)

{

parentString = myString;

Console.WriteLine(parentString);

}


public void print()

{

Console.WriteLine("I'm a Parent Class.");

}

}



public class Child : Parent

{

public Child() : base("From Derived")

{

Console.WriteLine("Child Constructor.");

}


public new void print()

{

base.print();

Console.WriteLine("I'm a Child Class.");

}


public static void Main()

{

Child child = new Child();

child.print();

((Parent)child).print();

}

}
Output :
From Derived
Child Constructor.
I'm a Parent Class.
I'm a Child Class.
I'm a Parent Class.



Reference:http://www.csharp-station.com/tutorials/lesson08.aspx

2009-11-23

Introducing Windows Azure

Microsoft’s Windows Azure platform (originally known as the Azure Services Platform) is a group of cloud technologies, each providing a specific set of services to application developers. As Figure 1 shows, the Windows Azure platform can be used both by applications running in the cloud and by applications running on local systems.

Lets,look at four core scenarios for using Windows Azure:
a)creating a scalable Web application:-Windows Azure provides can handle much larger loads than more conventional Web technologies.So the application with occasional spikes can be benefitted by costing.Since Windows Azure charging is usage-based, this is likely to be cheaper than maintaining lots of mostly unused machines.
b)creating a parallel processing application:-The user might determine how many Worker instances should run.
c)creating a Web application with background processing:-For background processing, it relies on Worker role instances, passing them tasks via queues.
d)using cloud storage from an on-premises or hosted application:-A non-cloud applications can access cloud storage for storing the large amount of Past data.
A primary goal of Windows Azure for ISV is to be a platform on which (independent software vendor)ISVs can create Software as a Service (SaaS) applications. Customers are increasingly interested in having a SaaS option for the software they buy. To satisfy this demand and to keep pace with the competition, many ISVs will choose to offer a SaaS version of their current or future products. Creating a SaaS application requires building a highly scalable, highly reliable cloud-based service that can be used simultaneously by many customer organizations. Building your own foundation for this makes no more sense than would writing your own operating system for an on-premises application. Just as Windows provides a foundation for traditional on-premises applications, Windows Azure can provide a foundation for SaaS applications.
A cloud platform such as Windows Azure is different from traditional hosting. From a technical perspective, Windows Azure provides simpler administration, as well as services designed to create scalable and reliable applications. The business differences include minimal up-front commitment and easier ways to increase and decrease the computing resources your application uses. These differences mean that Windows Azure can potentially provide better technology and lower costs for ISV applications.
The components of the Windows Azure platform include:
Windows Azure: Provides a Windows-based environment for running applications and storing data on servers in Microsoft data centers.
SQL Azure: Provides data services in the cloud based on SQL Server.
.NET Services: Offers distributed infrastructure services to cloud-based and local applications.

WINDOWS AZURE:
At a high level, Windows Azure is simple to understand: It’s a platform for running Windows applications and storing their data in the cloud. Figure 2 shows its main components.

As the figure suggests, Windows Azure runs on a large number of machines, all located in Microsoft data centers and accessible via the Internet.Windows Azure has three main parts:
A.a Compute service that runs applications, .
B.a Storage service that stores data, and
C.a Fabric that supports the Compute and Storage services.

To use the Compute service, a developer creates a Windows application. This application might be written using C# and the .NET Framework, using C++ and the Win32 APIs, or in some other way. However it’s built, the application must be implemented as Web roles, Worker roles, or both.

A Web role instance accepts Web requests. It can be created using ASP.NET or
another technology that works with Internet Information Services (IIS). Whatever technology is used,Windows Azure provides built-in hardware load balancing across all Web role instances in a particular application.
A Worker role instance is just a Windows application with a main(),and it can run indefinitely. Among other things, this model allows creating scalable applications where Web role instances accept requests, then pass them to Worker role instances to be processed.
Applications usually need persistent storage, and so Windows Azure provides its own cloud-based mechanisms for storing and retrieving data. The platform offers three storage options, all accessed via standard HTTP GETs, PUTs, and DELETEs.


The three kinds of Windows Azure storage are:
Blobs: allow storing large binary objects, such as videos and images.
Tables: provide highly scalable entity-based storage (not relational tables).
Queues: allow sending and receiving messages, such as between an application’s Web role instances and Worker role instances.
All Windows Azure applications and all of the data in Windows Azure Storage live in some Microsoft data center. Within that data center, the set of machines dedicated to Windows Azure is organized into a fabric.


The Windows Azure Fabric consists of a (large) group of machines, all of which are managed by software called the fabric controller. The fabric controller is replicated across a group of five to seven machines, and it owns all of the resources in the fabric: computers, switches, load balancers, and more. Because it can communicate with a fabric agent on every computer, it’s also aware of every Windows Azure application in this fabric.

SQL AZURE:SQL Azure Database (formerly known as SQL Data Services) provides a database management system (DBMS) in the cloud.While Microsoft says that SQL Azure will eventually include a range of data-oriented capabilities, including reporting, data analytics, and others.
The second SQL Azure component announced so far is “Huron” Data Sync. Built on the Microsoft Sync Framework and SQL Azure Database, this technology synchronizes relational data across various on-premises DBMSs. The owners of that data can determine what should be synchronized, how conflicts should be handled, and more.

.NET SERVICES:Originally known as BizTalk Services, the functions provided by .NET Services address common infrastructure challenges in creating distributed applications.

The components of .NET Services are:
a)Access Control:Its identify the user and decide what this user is allowed to do based on their claims.
b)Service Bus:It expose Web services endpoints that can be accessed by other applications.

Step by Step Approach:

Now let create a sample website on Windows Azure
A great thing about working with Windows Azure is that we have a simulated environment for you for development and testing. We simulate both the Windows Azure Fabric, as well as Windows Azure Storage on you local machine so you are able to build and test applications taking advantages of these services

Development Environment
All you need to do is to install the following:
A.The Windows Azure SDK
B.Visual Studio Tools

A)For the Windows Azure SDK we need the following prerequisites (here to see details about pre-requisites for the SDK )

a)Operating System
(for x86 version of SDK) – 32-bit editions of Windows Vista SP1 or Windows Server 2008.
(for x64 version of SDK) – 64-bit edition of Windows Vista® SP1 or Windows Server® 2008
b).NET Framework 3.5 sp1
c)Sql Server
Express 2005
Express 2008
Local Instance of 2005, 2008 – See here for more details
d)Internet Information Services (IIS) 7.0 must be enabled, with ASP.NET and Windows
Communication Foundation (WCF) HTTP Activation – Click here for details how to configure

B)The prerequisites for the Visual Studio tools include everything above plus:
Microsoft Visual Studio 2008 SP1 or Microsoft Visual Web Developer 2008 Express Edition with SP1
Hotfix: Native Debugging Improvements
Hotfix: Improve Visual Studio Stability
Hotfix: Support for FastCGI on the Development Fabric

Set Up Your Windows Azure Account
With your development environment set up, you have everything you need to get started developing our Azure store sample application. However, you might want to actually deploy this code to the cloud. For that you are going to need an Azure account. We are currently in CTP, so there is no charge for this account (that will chance when we go to release). You do, however, need a token.

To Request A Token:

1.Navigate to www.microsoft.com/azure. Click on Try It Now

2.Click on Try It Now to register with Connect and Request a Token

3.Log In with your Windows Live ID (you will need to create an account if you don’t already have one)

4.You will then have to complete the registration information
5.Click on the connection directory tab

6.Scroll until you see Azure Service Invitations

7.You are registered and should see a page like this:


To Setup Your Azure Services Developer Portal
1.Navigate to https://lx.azure.microsoft.com/
2.Log In with your live id
3.Fill in your country and lanugage and press I Agree to create a new account

4.You will be re-directed to a confirmation page. Press continue

5.You will be redirected to a page where you can redeem your invitation token. This token is necessary to create a Hosted Services project, as well as a Storage project. Don’t worry about closing the page or pressing cancel. You will be re-directed here the next time you log in. As I annotated below, you may have to wait a bit to receive your token (i.e. don’t proceed directly to Outlook and continually press refresh until you receive it). We are in CTP and have a limited number of tokens to hand out at any given time.

6.Once you have your token entered appropriately, you will no longer see this page. You will instead be re-directed to a page in the portal where you can create a project. Here is what you would see if you chose ‘Cancel’ on the previous page or if you click the ‘New Project’ link under the ‘Summary Tab’.

7.Here is the view you would see if you had entered a valid token:

8.You are now ready to create your Hosted Services Project. Click on ‘Hosted Services’ to add a new Hosted Services project.
9.On the next page, enter the following information:
----Project Label – Enter a label for your Hosted Services project. This label will be exposed on the Azure Services Developer Portal
----Project Description – Enter a description of the project you will be hosting

10.On the next page, enter a service name – a unique service / domain name to create the unique DNS name. You can check on the availability of service names. After you have settled on a unique service name, press the ‘Create’ button.

11.Your project is now created and you are ready to deploy a solution.

Creating our Cloud Project in Visual Studio:
In this part, we are going to create a “Hello World” web application, test it on the local development fabric and deploy it to the cloud.

Create the Cloud Project
1.Choose File > New > Project from the Visual Studio Menu.
2.Choose Cloud Service > Web Cloud Service

3.That’s it!

The template created 2 projects. The goals of these projects are as follows:
A Cloud Service Project

Allows you to build and package your cloud application to run in the local development fabric
Allows you to debug your cloud application in the local development fabric
Allows you to build and package your cloud application to deploy to the cloud
Stores configuration settings that apply to all instances of each role
Allows you to configure the number of instances to be created for each role
A Web Role

A web role in this template is really just an ASP.NET application. We have created additional web role projects, including a Cgi Web Role which allows you to host PHP and Ruby apps. This template, however creates an ASP.NET application.

Add Some Code
1.Add a label to Default.aspx, giving it an ID and setting runat=”server”.

2.Add some code to Default.aspx.cs that executes on the server that sets the text of the label. It doesn’t matter what you put here, we just want to illustrate that the server is doing some work and this is not simply a static page.

3.Run In The Development Fabric
Press F5 or the Start Debugging button to run the application in the development fabric. Here is the result:

What Happened
The Visual Studio tool do some nice work for you. Here is what happens.
Visual studio created a Windows Azure Service Package. This is the same package that is used to deploy to the web. However, in that instance, the package is zipped and encrypted. When running in the local development fabric, the extension of the package is csx and if you are running with debug symbols, you will find this in the debug directory. (See this post by Jim Nakashima for more information on how the service package is created)

VS ensures that development storage is started
VS ensures that the development fabric is started and deploys your package to the fabric (CSRun is the exe that does this)
If you are running with debug symbols, Visual Studio will attach the debugger to a role running in the development fabric
Debug It
Set a breakpoint on our code that sets the text of the label and start with debugging. Here is what you see:


Deploy Our Application To The Cloud
1.(optional) Set the application id in the project properties from your Hosted Service Application ID
Copy the application id from the Hosted Service Project to the clipboard

---Right-Click on the cloud services project (AzureStore) > Properties > Portal
---Paste the application id


2.Right-Click on the cloud services project (AzureStore) > Publish

3.A browser will be launched and it will automatically navigate you to the appropriate project if you completed step 1. Otherwise, navigate to the Hosted Service project where you want to deploy. An explorer window also opened to the location where the cspkg (encrypted, zipped project) and the cscfg files are.
4.Click on the Deploy button under Staging

5.Click on the Browse buttons and navigate to the publish directory under your project. It is the directory the explorer opened to.

6.Click Deploy. This process may take a few minutes.
7.Press Run. This process may also take a few minutes.
8.When the WebRole reads ‘Running’, you are ready to test.
9.Click on the ‘Web Site Url’ link.

10.That is it, you are running in the cloud! You are in staging, but feel free to swap it to production.


Resource obtained from :http://www.robbagby.com/azure/azure-application-part-1-setup-and-running-hello-world/

Flex Tutorials 17-Animation and Embedding Images in Adobe Flex

Copy some pictures in your src/assets folder and write the code as follows
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
creationComplete="startTimer()">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
[Bindable]
[Embed(source='/assets/houseImages/1.jpg')]
private var family1 : Class;
[Bindable]
[Embed(source='/assets/houseImages/2.jpg')]
private var family3 : Class;
[Bindable]
[Embed(source='/assets/houseImages/3.jpg')]
private var family4 : Class;
[Bindable]
[Embed(source='/assets/houseImages/4.jpg')]
private var family6 : Class;
[Bindable]
[Embed(source='/assets/houseImages/5.jpg')]
private var family5 : Class;
[Bindable]
[Embed(source='/assets/houseImages/6.jpg')]
private var family7 : Class;
//timer
private var timer:Timer;
private function init():void {
//mx.controls.Alert.show("HI");
timer = new Timer(2000); /* 1000ms == 1second */
timer.addEventListener(TimerEvent.TIMER, onTimer);
}
private function onTimer(evt:TimerEvent):void {
var idx:uint = imageViewStackComp.selectedIndex;
var max:uint = imageViewStackComp.numChildren;
var newIdx:uint = ++idx % max;
imageViewStackComp.selectedIndex = newIdx;
}
private function startTimer():void {
//mx.controls.Alert.show("HI timer");
if (!timer.running) {
timer.start();
}
}
private function stopTimer():void {
if (timer.running) {
timer.stop();
}
}
]]>
</mx:Script>
<mx:WipeLeft id="SlowWipe" duration="200"/>
<mx:WipeRight id="ReallySlowWipe" duration="200"/>
<mx:ViewStack id="imageViewStackComp" width="100%"
creationComplete="init()" >
<mx:Canvas showEffect="{SlowWipe}">
<mx:Image source="{family1}" width="100%" />
</mx:Canvas>
<mx:Canvas showEffect="{ReallySlowWipe}">
<mx:Image source="{family3}" width="100%" />
</mx:Canvas>
<mx:Canvas width="100%" height="100%" showEffect="{SlowWipe}">
<mx:Image source="{family4}" width="100%" />
</mx:Canvas>
<mx:Canvas width="100%" height="100%" showEffect="{ReallySlowWipe}" >
<mx:Image source="{family5}" width="100%" />
</mx:Canvas>
<mx:Canvas width="100%" height="100%" showEffect="{SlowWipe}">
<mx:Image source="{family6}" width="100%" />
</mx:Canvas>
<mx:Canvas width="100%" height="100%" showEffect="{ReallySlowWipe}">
<mx:Image source="{family7}" width="100%" />
</mx:Canvas>
</mx:ViewStack>
</mx:Application>

Flex Tutorials 16-Multiple file uploader in .NET using Adobe Flex

Create an MXML application with the following code
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="myFunction();" xmlns:net="flash.net.*" xmlns:filters="flash.filters.*">
<mx:Button x="10" y="10" label="Choose Files" id="btnSelectFiles"/>
<mx:Button x="114" y="10" label="Upload" id="btnUpload" visible="false"/>
<mx:Label x="10" y="208" width="100%" id="lblFileName" fontWeight="bold"/>
<mx:List borderStyle="none" backgroundAlpha="0" x="10" y="40" width="30%" id="listSelectedFiles" visible="false" />
<mx:Label x="10" y="234" width="100%" id="lblUploadedBytes" fontWeight="bold"/>
<mx:Label x="10" y="260" width="100%" id="lblTotalBytes" fontWeight="bold"/>

<mx:Script>
<![CDATA[
import mx.messaging.AbstractConsumer;
//for Single Selection Mode use FileReference instead of FileReferenceList
public var fileReferenceList:FileReferenceList = new FileReferenceList();
public function eventResponse(Event:MouseEvent):void
{
// Set the file filters in the open dialog box
var typeFiler:FileFilter = new FileFilter("All","*.*");
// show the dialog box
fileReferenceList.browse([typeFiler]);
}
public function selectResponse(event:Event):void
{
// Create an array with the size of the selected files.
var filesSelected:Array = new Array(fileReferenceList.fileList.length);
// Loop through all the selected files and add their names to the List control
for(var i:int=0;i<fileReferenceList.fileList.length;i++)
{
var fileReference:FileReference = fileReferenceList.fileList[ i ];
filesSelected[ i ] = fileReference.name;
}
listSelectedFiles.dataProvider = filesSelected;
listSelectedFiles.visible = true;
btnUpload.visible = true;
}
public function myFunction(): void
{
// This function is called on creationComplete event of this application
// Add event handler for the mouse click on the selectFiles button
btnSelectFiles.addEventListener(MouseEvent.CLICK, eventResponse);
// Add event handler for the mouse click on the upload button
btnUpload.addEventListener(MouseEvent.CLICK, btnUploadResponse);
// Add event handler for the select action in the open file dialog box
fileReferenceList.addEventListener(Event.SELECT,selectResponse);
}
public function UploadFiles():void
{
// If the user selected 1 or multiple files
if(fileReferenceList.fileList.length > 0)
{
// For each file selected
for(var i:int=0;i<fileReferenceList.fileList.length;i++)
{
// Create a FileReference instance of each file
var fileReference:FileReference = fileReferenceList.fileList[ i ];
// Create a new URLRequest class: The parameter is the aspx handler page
var request:URLRequest = new URLRequest("http://localhost:1283/FlexUploadFles/UploadHandler.aspx");
// Add event handler for the progress
fileReference.addEventListener(ProgressEvent.PROGRESS, progressStatus);
// Set the content type
request.contentType = "application/octet-stream";
// Set the method of the request
request.method = "POST";
// Upload the file
fileReference.upload(request,fileReference.name,false);
}
}
}
public function btnUploadResponse(event:Event):void
{
// Disable the Select files button, upload button, and call the UploadFiles function
btnSelectFiles.enabled = false;
btnUpload.enabled = false;
UploadFiles();
}
public function progressStatus(event:ProgressEvent):void
{
var file:FileReference = FileReference(event.target);
// Set the name of the currently being uploaded file
lblFileName.text = "Uploading File: " + file.name;
// Set the number of bytes being uploaded
lblUploadedBytes.text = "Bytes Uploaded: " + event.bytesLoaded;
// Set the total number of bytes
lblTotalBytes.text = "Total Size: " + event.bytesTotal + " bytes";
}
]]>
</mx:Script>

</mx:Application>

In .NET side write the following code to Pass the values after embeding the SWF File in ASPX page

CS Code:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class UploadHandler : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < Request.Files.Count; i++)
{
string fileName = System.IO.Path.GetFileName(Request.Files[i].FileName);
Request.Files[i].SaveAs(Server.MapPath("~/UploadedFiles/") + fileName);
}
}
}

If you want to use filter option in your File Uploader Control write the following MXML Code

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute"
creationComplete="{init()}"
>

<mx:Script>
<![CDATA[
import mx.controls.Alert;
private var imageFilter:FileFilter;
private var htmlFilter:FileFilter;
private var fileReference:FileReference;

private function init():void{

imageFilter=new FileFilter("Image Files","*.jpg;*.gif;*.png")
htmlFilter=new FileFilter("HTML Files","*.html")
fileReference=new FileReference();
fileReference.addEventListener(Event.SELECT, fileSelectedHandler);

}

private function fileSelectedHandler(e:Event):void{
if( e.target.type.toString()!='.jpg'&&
e.target.type.toString()!='.png'&&
e.target.type.toString()!='.gif'&&
e.target.type.toString()!='.html'){

Alert.show("Unexpected File Format","Error");

}else{

Alert.show( "Name : "+e.target.name.toString()+"\n"+
"Type : "+e.target.type.toString()+"\n"+
"CreationDate : "+e.target.creationDate.toString()+"\n"+
"Size : "+e.target.size.toString()+"bites \n",
"File Informations");
}
}
private function browse(filter:FileFilter):void{

fileReference.browse([filter]);

}
]]>
</mx:Script>
<mx:Button label="Browse Images Files" click="browse(imageFilter)" x="10" y="60" width="150"/>
<mx:Button label="Browse Html Files" click="browse(htmlFilter)" y="30" x="10" width="150"/>
</mx:Application>

Flex Tutorials 15-How to Call WebService in Adobe Flex

Simple Call
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical">
<mx:WebService id="wsData" wsdl="http://localhost:8700/flex/services/SimpleService?wsdl" load="wsData.arrayOutMethod()"/>
<mx:DataGrid dataProvider="{wsData.arrayOutMethod.lastResult}"/>

<mx:Label text="{wsData.arrayOutMethod.lastResult.getItemAt(0).dessert}"/>

</mx:Application>
Another Sample call
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical">

<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.rpc.events.ResultEvent;
[Bindable]
private var sandwiches:ArrayCollection;
private function sanDataHandler(event:ResultEvent):void{
sandwiches = event.result as ArrayCollection;
}

]]>
</mx:Script>

<mx:WebService id="sanData"
wsdl="http://localhost:8500/SimpleWS.cfc?wsdl" load="sanData.getSandwichList()" result="sanDataHandler(event)"/>

<mx:DataGrid dataProvider="{sandwiches}"/>

<mx:Label text="{sandwiches.getItemAt(0).sandwichName}"/>

</mx:Application>

Fault Handling in Web Service
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical">

<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.rpc.events.ResultEvent;

[Bindable]
private var sandwiches:ArrayCollection;

private function sanDataHandler(event:ResultEvent):void
{
sandwiches=event.result as ArrayCollection;
}
private function faultHandler(event:mx.rpc.events.FaultEvent):void{
mx.controls.Alert.show(event.fault.faultCode);
mx.controls.Alert.show(event.fault.faultString);
}
]]>
</mx:Script>

<mx:WebService id="sanData"
wsdl="http://localhost:8500/SimpleWS.cfc?wsdl"
load="sanData.getSandwichLists()"
result="sanDataHandler(event)"
fault="faultHandler(event)"/>

<mx:DataGrid dataProvider="{sandwiches}"/>

<mx:Label text="{sandwiches.getItemAt(1).sandwichName}"/>

</mx:Application>

Call multiple Method in Web Service
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical">

<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
import mx.collections.ArrayCollection;

[Bindable]
private var wordBack:String;
[Bindable]
private var dataBack:ArrayCollection;

private function wordHandler(event:ResultEvent):void
{
wordBack=String(event.result);
}

private function arrayHandler(event:ResultEvent):void
{
dataBack=event.result as ArrayCollection;
}

private function faultHandler(event:mx.rpc.events.FaultEvent):void
{
mx.controls.Alert.show(event.fault.faultCode);
mx.controls.Alert.show(event.fault.faultString);
}
]]>
</mx:Script>

<mx:WebService id="wsData"
wsdl="http://localhost:8500/SimpleWS.cfc?wsdl" load="wsData.outMethod();wsData.arrayOutMethod()" fault="faultHandler(event)">
<mx:operation name="outMethod" result="wordHandler(event)"/>
<mx:operation name="arrayOutMethod" result="arrayHandler(event)"/>
</mx:WebService>

<mx:Label text="{wordBack}" fontSize="40"/>

<mx:DataGrid dataProvider="{dataBack}"/>

</mx:Application>

Pass parameter to Webservice
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical">

<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;

[Bindable]
private var wordBack:String;

private function wsHandler(event:ResultEvent):void
{
wordBack=String(event.result);
}

private function faultHandler(event:mx.rpc.events.FaultEvent):void
{
mx.controls.Alert.show(event.fault.faultCode);
mx.controls.Alert.show(event.fault.faultString);
}
]]>
</mx:Script>

<mx:WebService id="wsData"
wsdl="http://localhost:8500/SimpleWS.cfc?wsdl"
result="wsHandler(event)"
fault="faultHandler(event)">
<mx:operation name="multArgsMethod">
<mx:request xmlns="">
<oneArg>
{word1.text}
</oneArg>
<twoArg>
{word2.text}
</twoArg>
</mx:request>

</mx:operation>
</mx:WebService>

<mx:Label text="{wordBack}"
fontSize="40"/>

<mx:TextInput id="word1"/>
<mx:TextInput id="word2"/>
<mx:Button label="send data" click="wsData.multArgsMethod.send()"/>

</mx:Application>

Output:

Flex Tutorials 14-Currency Formatter in Adobe Flex

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Style>
global {
fontSize:12;
}
</mx:Style>

<mx:Script>
<![CDATA[
private function calculate():void {
var result:Number = Number(amountInput.text) * (Number(percentInput.text) / 100);
resultLabel.text = formatter.format(result.toString());
}
]]>
</mx:Script>
<mx:CurrencyFormatter id="formatter" currencySymbol="kr" decimalSeparatorTo="," thousandsSeparatorTo="." precision="2"/>

<mx:NumberValidator id="amountV"
source="{amountInput}" property="text"
trigger="{submitButton}" triggerEvent="click"
minValue="1"
requiredFieldError="Amount is required"/>

<mx:NumberValidator id="percentV"
source="{percentInput}" property="text"
trigger="{submitButton}" triggerEvent="click"
requiredFieldError="Enter a percentage"
maxValue="100" exceedsMaxError="Percentage can't exceed 100%"
domain="int" integerError="Enter percent as a whole number"/>

<mx:Panel title="Tip Calculator">

<mx:Form>
<mx:FormItem label="Bill amount:">
<mx:TextInput id="amountInput" width="60"/>
</mx:FormItem>
<mx:FormItem label="Percent tip:">
<mx:TextInput id="percentInput" width="60"/>
</mx:FormItem>
</mx:Form>

<mx:ControlBar>
<mx:Image source="@Embed('assets/calculator.gif')" width="30" height="30" />
<mx:VBox>
<mx:Button id="submitButton"
label="Calculate"
click="calculate()"/>
<mx:Label id="resultLabel"/>
</mx:VBox>
</mx:ControlBar>

</mx:Panel>

</mx:Application>

Flex Tutorials 13-Regular Expression in Adobe Flex

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">

<mx:Script>
<![CDATA[
private function validateAddress():void{
var pattern:RegExp = new RegExp("\\d+\\x20[a-z]+", "i");
var result:int=billingAddress.text.search(pattern);
if (result == -1){
billingAddress.errorString = "Please enter a valid US address";
}else{
billingAddress.errorString="";
}


}
]]>
</mx:Script>

<mx:Form>
<mx:FormHeading label="Restaurant Delivery Information"/>
<mx:FormItem label="Name">
<mx:TextInput id="billingName"/>
</mx:FormItem>
<mx:FormItem label="Address">
<mx:TextArea id="billingAddress" width="160"/>
</mx:FormItem>
<mx:FormItem label="City">
<mx:TextInput id="billingCity"/>
</mx:FormItem>
<mx:FormItem label="State">
<mx:TextInput id="billingState" maxChars="2"/>
</mx:FormItem>
<mx:FormItem label="Zip">
<mx:TextInput id="billingZip"/>
</mx:FormItem>
<mx:FormItem>
<mx:Button label="Continue" click="validateAddress()"/>
</mx:FormItem>
</mx:Form>
</mx:Application>

Flex Tutorials 12-Valiation Control in Adobe Flex

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Style>
global {
fontSize:12;
}
.valid{
color:#000000;
}
.invalid{
color:#FF0000;
}
</mx:Style>

<mx:Script>
<![CDATA[
import mx.events.ValidationResultEvent;
private function calculate():void {
var evValidAmt:ValidationResultEvent = amountV.validate();
var evValidPct:ValidationResultEvent = percentV.validate();
if (evValidAmt.type == ValidationResultEvent.VALID && evValidPct.type == ValidationResultEvent.VALID){
var result:Number = Number(amountInput.text) * (Number(percentInput.text) / 100);
resultLabel.text = result.toString();
resultLabel.setStyle("styleName","valid");
}else{
resultLabel.text="There are Form errors";
resultLabel.setStyle("styleName", "invalid");
}
}
]]>
</mx:Script>

<mx:NumberValidator id="amountV"
source="{amountInput}" property="text"
triggerEvent=""
minValue="1"
requiredFieldError="Amount is required"/>

<mx:NumberValidator id="percentV"
source="{percentInput}" property="text"
triggerEvent=""
requiredFieldError="Enter a percentage"
maxValue="100" exceedsMaxError="Percentage can't exceed 100%"
domain="int" integerError="Enter percent as a whole number"/>

<mx:Panel title="Tip Calculator">

<mx:Form>
<mx:FormItem label="Bill amount:">
<mx:TextInput id="amountInput" width="60"/>
</mx:FormItem>
<mx:FormItem label="Percent tip:">
<mx:TextInput id="percentInput" width="60"/>
</mx:FormItem>
</mx:Form>

<mx:ControlBar>
<mx:Image source="@Embed('assets/calculator.gif')" width="30" height="30" />
<mx:VBox>
<mx:Button id="submitButton"
label="Calculate"
click="calculate()"/>
<mx:Label id="resultLabel"/>
</mx:VBox>
</mx:ControlBar>

</mx:Panel>

</mx:Application>
Output :

Flex Tutorials 11-Sort Function and ICursur in Adobe Flex

<?xml version="1.0" encoding="utf-8"?>
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="simpletestFood.send();" >

<mx:Script>
<![CDATA[
import mx.collections.SortField;
import mx.collections.Sort;
import mx.collections.ArrayCollection;

[Bindable]
public var foodList:ArrayCollection;

private function sortItems():void{
var foodSort:Sort = new Sort();
foodSort.fields = [new SortField("product_name")];
foodList.sort = foodSort;
foodList.refresh();
}

]]>
</mx:Script>

<mx:HTTPService id="simpletestFood"
url="assets\foodlist.xml" result="foodList = simpletestFood.lastResult.list.food"/>

<mx:Button id="myButton"
label="Sort Items" click="sortItems()"/>
<mx:List id="cartDg"
dataProvider="{foodList}"
labelField="product_name"
width="20%"/>

</mx:Application>


Using ICursur:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="simpletestCat.send();simpletestFood.send()" >

<mx:Script>
<![CDATA[
import mx.collections.IViewCursor;
import mx.controls.dataGridClasses.DataGridColumn;
import mx.collections.ArrayCollection;
import mx.collections.SortField;
import mx.collections.Sort;
import mx.collections.ArrayCollection;


[Bindable]
public var categoryList:ArrayCollection;
[Bindable]
public var foodList:ArrayCollection;
[Bindable]
public var aItems:ArrayCollection = new ArrayCollection();
private var cursor:IViewCursor;

public function filterByCategory():void
{

foodList.filterFunction = catFilter;
foodList.refresh();
}
public function catFilter(item:Object):Boolean
{
if(categorySelect.selectedItem == "All")
{
return true;
}
else
{
return item.category_name == categorySelect.selectedItem.category_name;
}
}
private function sortItems():void
{
var sortA:Sort = new Sort();
sortA.fields=[new SortField("food_id", false)];
aItems.sort=sortA;
aItems.refresh();
}
private function manageAddItem(item:Object):void{
var temp:Object = getItemInCart(item);
if (temp !=null){
temp.quantity += 1;
}else{
item.quantity = 1;
aItems.addItem(item);
}
}

private function getItemInCart(item:Object):Object{
cursor = aItems.createCursor();
sortItems();
var found:Boolean = cursor.findAny(item);
if (found==true){
return cursor.current;
}else{
return null;
}
}
]]>
</mx:Script>

<mx:HTTPService id="simpletestCat"
url="assets\categorylist.xml"
result="categoryList=simpletestCat.lastResult.list.category;categoryList.addItemAt('All', 0);categorySelect.selectedIndex=0"/>
<mx:HTTPService id="simpletestFood"
url="assets\foodlist.xml"
result="foodList=simpletestFood.lastResult.list.food"/>

<mx:ComboBox id="categorySelect"
dataProvider="{categoryList}"
labelField="category_name"
change="filterByCategory()"/>
<mx:List id="foodListBox"
dataProvider="{foodList}"
labelField="product_name"
width="200"/>
<mx:Button id="myButton"
label="Add to Cart" click="manageAddItem(foodListBox.selectedItem)"/>
<mx:Label text="Shopping Cart"/>
<mx:DataGrid id="cartDg"
dataProvider="{aItems}"
width="50%">
<mx:columns>
<mx:DataGridColumn dataField="product_name" headerText="Product"/>
<mx:DataGridColumn dataField="product_price" headerText="Price"/>
<mx:DataGridColumn dataField="quantity" headerText="Quantity"/>
</mx:columns>
</mx:DataGrid>

</mx:Application>

Flex Tutorials 10-Filter Function in Adobe Flex

Create foodlist.xml in Src\assets\categorylist.xml folder
<?xml version="1.0" encoding="utf-8"?>

<list>
<food>

<food_id>1</food_id>
<category_name>Korean</category_name>
<product_name>Kim Chi</product_name>
<product_price>.99</product_price>
<quantity>0</quantity>
</food>
<food>

<food_id>11</food_id>
<category_name>Indian</category_name>
<product_name>Daal</product_name>
<product_price>.99</product_price>
<quantity>0</quantity>

</food>
<food>

<food_id>2</food_id>
<category_name>Indian</category_name>
<product_name>Aloo Gobi</product_name>
<product_price>1.99</product_price>
<quantity>0</quantity>

</food>
<food>
<food_id>3</food_id>
<category_name>Thai</category_name>
<product_name>Pad Thai</product_name>
<product_price>3.99</product_price>
<quantity>0</quantity>
</food>
<food>

<food_id>4</food_id>
<category_name>Japanese</category_name>
<product_name>Tempura</product_name>
<product_price>2.99</product_price>
<quantity>0</quantity>
</food>
<food>

<food_id>5</food_id>
<category_name>Ethiopian</category_name>
<product_name>Flat Bread</product_name>
<product_price>.99</product_price>
<quantity>0</quantity>

</food>
<food>

<food_id>7</food_id>
<category_name>Japanese</category_name>
<product_name>Sashimi</product_name>
<product_price>5.99</product_price>
<quantity>0</quantity>

</food>
</list>

Mxmlcode:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="simpletestCat.send();simpletestFood.send()" >

<mx:Script>
<![CDATA[
import mx.controls.dataGridClasses.DataGridColumn;
import mx.collections.ArrayCollection;
[Bindable]
public var categoryList:ArrayCollection;
[Bindable]
public var foodList:ArrayCollection;
private function filterByCategory():void{
foodList.filterFunction = catFilter;
foodList.refresh();
}
private function catFilter(item:Object):Boolean{
if(categorySelect.selectedItem == "All") {
return true;
}else{
return item.category_name == categorySelect.selectedItem.category_name;
}

}

]]>
</mx:Script>

<mx:HTTPService id="simpletestCat"
url="assets\categorylist.xml"
result="categoryList = simpletestCat.lastResult.list.category;categoryList.addItemAt('All', 0);categorySelect.selectedIndex=0"/>
<mx:HTTPService id="simpletestFood"
url="assets\foodlist.xml"
result="foodList = simpletestFood.lastResult.list.food"/>

<mx:ComboBox id="categorySelect"
dataProvider="{categoryList}"
labelField="category_name"
change="filterByCategory()"/>
<mx:List id="foodListBox"
dataProvider="{foodList}"
labelField="product_name"
width="200"/>

</mx:Application>

Output:

Flex Tutorials 9-Manipulating XML in Adobe Flex

put dishes.xml under src/xml
<?xml version="1.0" encoding="utf-8" ?>
<menu>
<type aname="From the Grill">
<category aname="Fish dishes">
<dish id="1" aname="Cajun Seafood Bouillabaisse" description="With crawfish, scallops, catfish, crab, and mussels. Served with Southern-style cornbread and honey butter." price="17.50" image="image2.jpg"/>
<dish id="2" aname="Grilled Rockfish Fillet" description="Lemon-Chive Risotto Cake, Balsamic Glaze" price="24.95" image="image2.jpg"/>
</category>
<category aname="Meat dishes">
<dish id="3" aname="Sage-rubbed Double-cut Pork Chop" description="Topped with a ragout of mushrooms and chunky pancetta. Served with griddle corn cakes." price="14.95" image="image4.jpg"/>
<dish id="4" aname="The Burger" description="Brioche Bun and your choice of Mushrooms, Bacon, Cheddar, Gruyere, Blue" price="18.75" image="image4.jpg"/>
</category>
</type>
<type aname="Healthy, Light and Vegetarian">
<category aname="Vegetarian dishes">
<dish id="5" aname="Cavatappi Pasta with Chickpea Sauce" description="Tossed with grilled eggplant, green olives, and sun dried tomatoes. Topped with Mediterranean feta." price="17.45" image="image0.jpg"/>
<dish id="6" aname="Roasted Tomato Soup" description="Served with goat cheese croutons and basil puree" price="9.95" image="image0.jpg"/>
</category>
<category aname="Light dishes">
<dish id="7" aname="Summer Salad" description="Gorgonzola, tossed with raspberry vinaigrette" price="13.25" image="image1.jpg"/>
<dish id="8" aname="Pancetta-wrapped Sea Scallops" description="Drizzled with tarragon puree. Served with baked cauliflower au gratin in a tangy Gruyere sauce" price="16.45" image="image1.jpg"/>
</category>
</type>
</menu>

Now we need the output as follows


Mxml Code:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns="*" layout="horizontal" creationComplete="dishesXML.send();">
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
import mx.collections.XMLListCollection;
[Bindable]
private var dishesDP:XMLList;
[Bindable]
private var shoppingCartXML:XML = new XML(<products></products>);
[Bindable]
private var shoppingCartData:XMLListCollection;
private function dishesXMLHandler(event:ResultEvent):void
{
dishesDP = event.result..category;
}
private function addToShoppingCart():void
{
var itemToUpdate:XMLList = shoppingCartXML.product.(@id == dishesTree.selectedNode.@id);
if(itemToUpdate.qty > 0)
{
itemToUpdate.qty=Number(itemToUpdate.qty)+1;
}
else
{
var newItem:XML =
<product id={dishesTree.selectedNode.@id}>
<aname>
{dishesTree.selectedItem.@aname}
</aname>
<price>
{dishesTree.selectedItem.@price}
</price>
<qty>
1
</qty>
</product>;
shoppingCartXML.appendChild(newItem);
}
shoppingCartData = new XMLListCollection (shoppingCartXML.children());
}
private function removeFromShoppingCart():void
{

}
private function clearCart():void
{

}
private function populateForm(event:Event):void
{
var node:XML=event.target.selectedItem;
if(node.@price != undefined)
{
prodName.text = node.@aname;
listPrice.text = node.@price;
description.text = node.@description;
theImage.source = "assets/"+node.@image;
theForm.visible = true;
}
else
{
theForm.visible = false;
prodName.text = "";
listPrice.text = "";
description.text = "";
theImage.source = "";
}
}
]]>
</mx:Script>

<mx:HTTPService id="dishesXML" url="assets/xml/dishes.xml" showBusyCursor="true"
result="dishesXMLHandler(event)" resultFormat="e4x"/>

<mx:ApplicationControlBar width="100%" height="110">
<mx:HBox>
<mx:Image source="assets/header.jpg" />
<mx:Label text="Delivery Service" fontSize="20"/>
</mx:HBox>
</mx:ApplicationControlBar>

<mx:Panel id="leftPanel" title="Our Fine Foods" width="100%" height="{centerPanel.height}">
<mx:Tree id="dishesTree"
dataProvider="{dishesDP}"
labelField="@aname"
width="100%"
height="100%"
borderThickness="0"
change="populateForm(event)"/>
</mx:Panel>

<mx:Panel id="centerPanel" title="Product Details" width="100%" height="{theForm.height+100}">
<mx:Form id="theForm" visible="false">
<mx:FormHeading/>
<mx:FormItem label="Product Name">
<mx:TextInput id="prodName"/>
</mx:FormItem>
<mx:FormItem label="Price">
<mx:TextInput id="listPrice"/>
</mx:FormItem>
<mx:FormItem label="Description">
<mx:TextArea id="description" width="{listPrice.width}" height="100"/>
</mx:FormItem>
<mx:FormItem>
<mx:Image id="theImage" width="200" height="50" maintainAspectRatio="true" />
</mx:FormItem>
</mx:Form>
<mx:ControlBar>
<mx:Button
id="addButton"
label="Add to Cart"
enabled="{theForm.visible}"
click="addToShoppingCart()" />
</mx:ControlBar>
</mx:Panel>

<mx:Panel id="rightPanel"
title="Your Shoppingcart"
width="100%" height="{centerPanel.height}">
<mx:DataGrid id="shoppingCart"
dataProvider="{shoppingCartData}"
width="100%" height="100%"
borderThickness="0">
<mx:columns>
<mx:DataGridColumn dataField="qty" headerText="Quantity"/>
<mx:DataGridColumn dataField="aname" headerText="Name"/>
<mx:DataGridColumn dataField="price" headerText="Price"/>
</mx:columns>
</mx:DataGrid>

<mx:ControlBar enabled="false">
<mx:Button id="removeButton"
label="Remove"
enabled="false"
click="removeFromShoppingCart()"/>
<mx:Button id="clearButton"
label="Clear Cart"
enabled="false"
click="clearCart()"/>
</mx:ControlBar>
</mx:Panel>

</mx:Application>

Flex Tutorials 8-Using Datagrid and TileList in Adobe Flex

Create a reviewlist.xml file as follows under src\assets location
<?xml version="1.0" encoding="utf-8"?>
<list>
<review>
<review_id>38</review_id>
<restaurant_id>58</restaurant_id>
<reviewer>RJ Talbot</reviewer>
<title>Nice Visit</title>
<review_text>Good food, great prices and nice staff. Worth the visit!</review_text>
<review_date>2005-03-13 14:41:54.0</review_date>
<rating>4</rating>
</review>
<review>
<review_id>23</review_id>
<restaurant_id>53</restaurant_id>
<reviewer>Bill Taylor</reviewer>
<title>Loved it!</title>
<review_text>This is an amazing place!</review_text>
<review_date>2005-03-30 15:07:05.0</review_date>
<rating>5</rating>
</review>
</list>

Inline DataBinding with Autognerated column=true
<?xml version="1.0"?>
<mx:Application backgroundColor="#FFFFFF" xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="srv.send()">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
[Bindable]
private var reviewList:ArrayCollection;
]]>
</mx:Script>
<mx:HTTPService id=" simpletest " url="assets\datagriddata.xml" result=" reviewList = new ArrayCollection(simpletest.lastResult. list. review)"/>// result=" reviewList = simpletest.lastResult. list. review"
<mx:DataGrid dataProvider="{ reviewList }"/>
</mx:Application>

Autogenerated Column=false
<mx:DataGrid id="reviewGrid" dataProvider="{reviewList}">
<mx:columns>
<mx:DataGridColumn dataField="review_date" headerText="Review Date"/>
<mx:DataGridColumn dataField="reviewer" headerText="Reviewer"/>
</mx:columns>
</mx:DataGrid>

Format Datagrid column with LabelFunction+DateFormatter
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="simpletest.send();" >
<mx:Script>
<![CDATA[
import mx.controls.dataGridClasses.DataGridColumn;
import mx.collections.ArrayCollection;
[Bindable]
private var reviewList:ArrayCollection;
private function dateFormat(item:Object, review_date:DataGridColumn):String{
return myDate.format(item.review_date);
}
]]>
</mx:Script>
<mx:HTTPService id="simpletest" url="assets\reviewlist.xml" result="reviewList = simpletest.lastResult.list.review"/>
<mx:DateFormatter id="myDate" formatString="DD-MMM-YYYY"/>
<mx:DataGrid dataProvider ="{reviewList}">
<mx:columns>
<mx:DataGridColumn dataField="reviewer" headerText="Reviewer"/>
<mx:DataGridColumn dataField="review_date" headerText="Review Date" labelFunction="dateFormat" width="150"/>
</mx:columns>
</mx:DataGrid>
</mx:Application>
N.B.LableFunction Doesn’t take () when calling AS function ,Label Function in AS always function signature will be remain same for any other application.

Editable Datagrid+ itemEditor+ itemRenderer
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="simpletest.send()" >
<mx:Script>
<![CDATA[
import mx.controls.dataGridClasses.DataGridColumn;
import mx.collections.ArrayCollection;
[Bindable]
private var reviewList:ArrayCollection;
]]>
</mx:Script>
<mx:HTTPService id="simpletest" url="assets\reviewlist.xml" result="reviewList = simpletest.lastResult.list.review;"/>

<mx:DataGrid dataProvider ="{reviewList}" editable="true">
<mx:columns>
<mx:DataGridColumn dataField="reviewer" headerText="Reviewer"/>
<mx:DataGridColumn dataField="rating" headerText="Rating" itemEditor="mx.controls.NumericStepper"/>
</mx:columns>
</mx:DataGrid>
<mx:DataGrid dataProvider ="{reviewList}" editable="true">
<mx:columns>
<mx:DataGridColumn dataField="reviewer" headerText="Reviewer"/>
<mx:DataGridColumn dataField="rating" headerText="Rating" itemRenderer="mx.controls.NumericStepper" rendererIsEditor="true"/>
/*<mx:DataGridColumn dataField="rating"
headerText="Rating" editorDataField="true">
<mx:itemEditor>
<mx:Component>
<mx:NumericStepper minimum="1" maximum="5"/>
</mx:Component>
</mx:itemEditor>
</mx:DataGridColumn>*/
</mx:columns>
</mx:DataGrid>
</mx:Application>

Output: For rendererIsEditor="true" the output will be as follows

For editorDataField="true" the output will be as follows


Custom column contain muliple row in a cell using itemrenderer +VariableRowHeight for a cell
Create mxml component “RatingDetail.mxml”
<?xml version="1.0" encoding="utf-8"?>
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300" horizontalScrollPolicy="off" verticalScrollPolicy="off">
<mx:DateFormatter id="simpleDate" formatString="DD-MMM-YYYY"/>
<mx:Label text="Rating:{data.rating}"/>
<mx:Label text="Review Date: {simpleDate.format(data.review_date)}"/>
</mx:VBox>
In the main application the MXML will be as follows
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" CreationComplete="simpletest.send()" >
<mx:Script>
<![CDATA[
import mx.controls.dataGridClasses.DataGridColumn;
import mx.collections.ArrayCollection;
[Bindable]
private var reviewList:ArrayCollection;
]]>
</mx:Script>
<mx:HTTPService id="simpletest" url="assets\reviewlist.xml"
result="reviewList = simpletest.lastResult.list.review"/>
<mx:DataGrid dataProvider ="{reviewList}" variableRowHeight="true" width="35%">
<mx:columns>
<mx:DataGridColumn dataField="reviewer" headerText="Reviewer"/>
<mx:DataGridColumn dataField="rating" headerText="Rating Info" itemRenderer="RatingDetail"/>
</mx:columns>
</mx:DataGrid>
</mx:Application>



TileList:Inbuid image controller based on the data sructure
Create photo.xml file as follows under src\assets folder
<?xml version="1.0" encoding="utf-8"?>
<list>
<food>
<food_name>Artichoke Dip</food_name>
<photo>artichokeDip.jpg</photo>
</food>
<food>
<food_name>Bread Pudding</food_name>
<photo>breadPudding.jpg</photo>
</food>
</list>

Create a Thumbnail.mxml under the folder src/ itemRenderers /
<?xml version="1.0" encoding="utf-8"?>
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Image source="{'assets/'+data.photo}"/>
<mx:Label text="{data.food_name}"/>
</mx:VBox>
In the main application file:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="simpletest.send()">

<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
[Bindable]
private var photoColl:ArrayCollection;
[Bindable]
private var photoColl:ArrayCollection;
private function tileChanged(event:Event):void{
foodName.text = event.target.selectedItem.food_name;
}
]]>
</mx:Script>

<mx:HTTPService id="simpletest" url="assets\photo.xml"
result="photoColl=simpletest.lastResult.list.food"/>
<mx:DataGrid dataProvider="{photoColl}"/>
<mx:Label id="foodName" text="Watch here"/>
<mx:TileList dataProvider="{photoColl}" itemRenderer="itemRenderers.Thumbnail" width="700" rowHeight="170" columnWidth="220" change="tileChanged(event)" >
</mx:TileList>
</mx:Application>
Output :

Flex Tutorials 7-Handling different viewstate in Adobe Flex

Adobe flex is a RIA applictaion,so our primary goal is to show different form in a single page rather than creating new pages and navigating them.To achive this,we should maintain different view state in a single page,each viewstate contain different form that will be shown in different event.

Create an Flex application with the following code:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
backgroundColor="#aaaaaa"
backgroundAlpha="0">
<mx:states>
<mx:State name="forms">
<mx:AddChild position="lastChild">
<mx:HBox>
<mx:Form>
<mx:FormHeading label="Contact Us by E-mail"/>
<mx:FormItem label="First Name:">
<mx:TextInput/>
</mx:FormItem>
<mx:FormItem label="Last Name:">
<mx:TextInput/>
</mx:FormItem>
<mx:FormItem label="E-mail Address:" required="true">
<mx:TextInput/>
</mx:FormItem>
<mx:FormItem label="Message:">
<mx:TextArea width="160"/>
<mx:Button label="Send Message" click="currentState=''"/>
</mx:FormItem>
</mx:Form>
<mx:Form>
<mx:FormHeading label="Request Menu or Brochure"/>
<mx:FormItem required="true">
<mx:CheckBox label="Menu"/>
<mx:CheckBox label="Special Events Brochure"/>
</mx:FormItem>
<mx:FormItem label="First Name:" required="true">
<mx:TextInput/>
</mx:FormItem>
<mx:FormItem label="Last Name:" required="true">
<mx:TextInput/>
</mx:FormItem>
<mx:FormItem label="Address:" required="true">
<mx:TextInput/>
</mx:FormItem>
<mx:FormItem>
<mx:TextInput/>
</mx:FormItem>
<mx:FormItem label="City & State:" direction="horizontal" required="true">
<mx:TextInput width="109"/>
<mx:ComboBox width="50">
<mx:dataProvider>
<mx:ArrayCollection>
<mx:source>
<mx:Object label="AL" />
<mx:Object label="AK" />
<mx:Object label="AR" />
<mx:Object label="AZ" />

</mx:source>
</mx:ArrayCollection>
</mx:dataProvider>
</mx:ComboBox>
</mx:FormItem>
<mx:FormItem label="Zip Code:" required="true">
<mx:TextInput width="62"/>
</mx:FormItem>
<mx:FormItem>
<mx:Button label="Send Request" click="currentState=''"/>
</mx:FormItem>
</mx:Form>
</mx:HBox>
</mx:AddChild>
</mx:State>
</mx:states>
<mx:Panel
title="Contact Cafe Townsend" backgroundColor="#ffffff" paddingBottom="15" paddingLeft="15" paddingRight="15" paddingTop="15" id="panel1">
<mx:Text width="100%" text="How to Find Us" color="#dd7142" fontWeight="bold" />
<mx:Text width="100%">
<mx:text>
We are easy to find. If you are taking public transportation, we are 2 blocks south of the bullet train stop. Located across from the famous gigantic galaxy structure.
</mx:text>
</mx:Text>
<mx:Text width="100%">
<mx:text>
If you are driving, take route 66 all the way to the coast, turn south onto Spectacular Drive, proceed 1 mile. We are pleased to provide you with complimentary valet parking.
</mx:text>
</mx:Text>
<mx:LinkButton label="Send an e-mail or request a brochure" color="#0000ff" click="currentState='forms'"/>

</mx:Panel>
</mx:Application>

Base state is a state which is not in the portion of <States>
When you run you can see the following screen

There are 2 state Base State & Form State.Clickin in “Send an e-mail…” buton form state will be visible with the content of Base State.An clicking on “send message” or “send request” in the form state,form state will be invisible & only the content of base state will be visible.if we don’t want to show the panel of base state when we are in form stare then we need to add the lines
<mx:RemoveChild target="{panel1}"/>
under the form state In the following position
</mx:Form>
</mx:HBox>
</mx:AddChild>
<mx:RemoveChild target="{panel1}"/>
</mx:State>
</mx:states>


Change the rollover image using View States
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" backgroundColor="#ffffff" backgroundAlpha="0">
<mx:states>
<mx:State name="details">
<mx:SetEventHandler target="{soup}" name="rollOut" handler="currentState=''"/>
<mx:SetProperty target="{soup}" name="scaleX" value="1.25"/>
<mx:SetProperty target="{soup}" name="scaleY" value="1.25"/>
<mx:AddChild position="lastChild">
<mx:Text text="Roasted butternut squash soup" width="200" fontWeight="bold"/>
</mx:AddChild>
<mx:AddChild position="lastChild">
<mx:Text text="Creamy, rich and silky finished with a touch of fresh basil and smoked walnuts" width="200"/>
</mx:AddChild>
</mx:State>
</mx:states>
<mx:Image id="soup" source="assets/app_butternut_soup.JPG" rollOver="currentState='details'"/>
</mx:Application>



On rollover the output will be as follows

Flex Tutorials 6-Retrieving XML Data using HTTP Service from Adobe Flex


Put an xml fime “sandwichData.xml” under src/assets
<?xml version="1.0" encoding="utf-8"?>
<sandwichMenu>

<sandwich>
<name>Dagwood</name>
<bread>Hogie</bread>
<meat>Hot Beef</meat>
<spread>Mayo</spread>
<type>Cold</type>
</sandwich>

<sandwich>
<name>Crooks</name>
<bread>Whole Wheat</bread>
<meat>Tofu Slices</meat>
<spread>Mustard</spread>
<type>Grilled</type>
</sandwich>
</sandwichMenu>

Load a simple XML + getItemAt()+result+ fault
Put the mxml in your application

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" creationComplete="sanData.send()">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.rpc.events.ResultEvent;
[Bindable]
private var sandwiches:ArrayCollection;
private function sanDataHandler (event:ResultEvent):void
{
sandwiches = event.result.sandwichMenu.sandwich;
}
private function faultHandler(event:mx.rpc.events.FaultEvent):void
{
var faultInfo:String= "fault description:" + "\n\n";
faultInfo+="fault.faultstring:" + event.fault.faultString+"\n\n";
mx.controls.Alert.show(faultInfo, "Fault Information");
var eventInfo:String="event target:" + event.target + "\n \n";
eventInfo += "event type:" + event.type + "\n\n";
mx.controls.Alert.show(eventInfo, "Event Information")
}

]]>
</mx:Script>

//<mx:HTTPService id="sanData" url="assets/sandwichData.xml"/>
//<mx:DataGrid dataProvider="{ sanData .lastResult. sandwichMenu.sandwich;}"/>
<mx:HTTPService id="sanData" url="assets/sandwichData.xml" result="sanDataHandler(event)" fault="faultHandler(event)"/>
<mx:DataGrid dataProvider="{sandwiches}"/>
<mx:Label text="{sandwiches.getItemAt(0).name}"/>
</mx:Application>





If the url of HTTPService is the url rather than a local file system we have to use the crossdomain.xml otherwise you will get the following error

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy
SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="*"/>
</cross-domain-policy>
Save it as “crossdomain.xml” & put it in the root of your application in WebServer.

Server side Communication using HTTP Service:

For Server side data sending using HTTP service requires to send query string from the flex application.
The following flex application sending two query string Zipcode & Pounds,& the .NET application receiving this two query string as the request type=GET
a.)using XML Format:
In the aspx page write the following code
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

public partial class xmlHttpService : System.Web.UI.Page
{
public string str = "";
protected void Page_Load(object sender, EventArgs e)
{
int zipcode=0;
double weight=0;
if (Request.QueryString["zipcode"] != null)
{
if (Request.RequestType == "POST")
{
zipcode = Int32.Parse(Request.Form["zipcode"].ToString());
weight = Double.Parse(Request.Form["pounds"].ToString());
}
Else//this condition is satiesfied when calling from Flex
{
zipcode = Int32.Parse(Request.QueryString["zipcode"].ToString());
weight = Double.Parse(Request.QueryString["pounds"].ToString());
}
}
StringBuilder stringBuilder = new StringBuilder("<options>");
for (int i=0;i<3;i++)
{

stringBuilder.Append("<option><service>");
stringBuilder.Append((zipcode * i).ToString());
stringBuilder.Append("</service><price>");
stringBuilder.Append((weight * i).ToString());
stringBuilder.Append("</price></option>");
}
stringBuilder.Append("</options>");
str = stringBuilder.ToString();
Response.ContentEncoding = Encoding.UTF8;
Response.Write(str);
}
}

The output of the ASPX file would be line this



MXML Code for this application:


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
backgroundColor="#FFFFFF" backgroundAlpha="0">
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
import mx.rpc.events.FaultEvent;
import mx.controls.Alert;

public function handleXml(event:ResultEvent):void
{
shippingOptionsGrid.dataProvider = event.result.option;

}
public function handleFault(event:FaultEvent):void
{
Alert.show(event.fault.faultString, "Error");
}
]]>
</mx:Script>
<mx:HTTPService id="xmlRpc" url="http://localhost:1283/FlexUploadFles/xmlHttpService.aspx"
result="handleXml(event)" fault="handleFault(event)"
resultFormat="e4x">
<mx:request>
<zipcode>{zipcode.text}</zipcode>
<pounds>{weight_lb.text}</pounds>
</mx:request>
</mx:HTTPService>

<mx:Label x="56" y="32" text="Zip Code" width="55" height="18"
textAlign="right" fontWeight="bold" />
<mx:Label x="56" y="58" text="Weight" width="55" height="18"
textAlign="right" fontWeight="bold" />
<mx:TextInput id="zipcode" x="130" y="32" width="160" height="22" />
<mx:TextInput id="weight_lb" x="130" y="58" width="160" height="22" />

<mx:Button x="130" y="95" label="Get Shipping Options"
click="xmlRpc.send()" width="160" height="22" />
<mx:DataGrid id="shippingOptionsGrid" x="80" y="141"
width="262" height="92" editable="false" enabled="true">
<mx:columns>
<mx:DataGridColumn headerText="Service" dataField="service" />
<mx:DataGridColumn headerText="Price" dataField="price" />
</mx:columns>
</mx:DataGrid>
</mx:Application>

The out put of the MXML file will be

b)Using Plain text format:
In the aspx page write the following code
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

public partial class PlainHttpService : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int zipcode=0;
double weight=0;
if (Request.QueryString["zipcode"] != null)
{
if (Request.RequestType == "POST")
{
zipcode = Int32.Parse(Request.Form["zipcode"].ToString());
weight = Double.Parse(Request.Form["pounds"].ToString());
}
else
{
zipcode = Int32.Parse(Request.QueryString["zipcode"].ToString());
weight = Double.Parse(Request.QueryString["pounds"].ToString());
}
}
for (int i = 0; i < 3; i++)
{
stringBuilder = new StringBuilder();
stringBuilder.Append((zipcode * i).ToString());
stringBuilder.Append(": ");
stringBuilder.Append((weight * i).ToString());
stringBuilder.Append(" USD" + "\n");
Response.Write(stringBuilder.ToString());
}
}
}
The output of the ASPX file will be


MXML Code:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
backgroundColor="#FFFFFF" backgroundAlpha="0">
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
import mx.rpc.events.FaultEvent;
import mx.controls.Alert;

public function handlePlain(event:ResultEvent):void
{
shippingOptions.text = event.result.toString();
}

public function handleFault(event:FaultEvent):void
{
Alert.show(event.fault.faultString, "Error");
}
]]>
</mx:Script>
<mx:HTTPService id="plainRpc"
url="http://localhost:1283/FlexUploadFles/PlainHttpService.aspx"
result="handlePlain(event)" fault="handleFault(event)"
resultFormat="text">
<mx:request>
<zipcode>{zipcode.text}</zipcode>
<pounds>{weight_lb.text}</pounds>
</mx:request>
</mx:HTTPService>

<mx:Label x="56" y="32" text="Zip Code" width="55" height="18"
textAlign="right" fontWeight="bold" />
<mx:Label x="56" y="58" text="Weight"
width="55" height="18" textAlign="right" fontWeight="bold" />
<mx:TextInput id="zipcode" x="130" y="32"
width="160" height="22" />
<mx:TextInput id="weight_lb" x="130" y="58"
width="160" height="22" />
<mx:Button x="130" y="95" label="Get Shipping Options"
click="plainRpc.send()" width="160" height="22" />
<mx:Text id="shippingOptions" x="56" y="150"
width="310" height="133" fontWeight="bold" />
</mx:Application>

The output will be as follows: