Code I/O

A topnotch WordPress.com site


1 Comment

5 Minutes on Adobe Flex – Accordion as Menu

Handling menus is cool in flex, with all the animations and affects, user experience can be lavish, but i’ll leave it to the beholder to enhance them as they want to.

Consider the listing, where we create an accordion with the menu items as shown below:

accordion_demo

The following listing creates the accordion:

<?xml version="1.0" encoding="utf-8"?>
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" width="100%" height="100%"
	xmlns:flexlib="http://code.google.com/p/flexlib/"
	xmlns:component="component.*"
	verticalGap="0" horizontalGap="0">
	<mx:Script>
		<![CDATA[
			import utility.Application;
			import mx.events.IndexChangedEvent;
			import mx.events.ItemClickEvent;
			import mx.events.MenuEvent;
			import mx.controls.Alert;

			[Bindable] private var menuItems:Array = ["Home", "Accounts", "Categories", "Activity", "Tools", "Help"];

			[Bindable] private var catalogMenuXML:XMLList = <>
                    <menuitem label="Register New Account">
                        <menuitem label="Automobile" data="Automobile"/>
                        <menuitem label="Bank Account" data="Bank Account"/>
                        <menuitem label="Commodity" data="Commodity"/>
                    </menuitem>

                    <menuitem label="Explore">
                    	<menuitem label="Accounts" data="Accounts"/>
                    	<menuitem label="Categories" data="Categories"/>
                    </menuitem>
                </>;

            private function catalogMenuHandler(event:MenuEvent):void
            {
                Alert.show("Label: " + event.item.@label + "n" +
                    "Data: " + event.item.@data, "Clicked menu item");
            }

            private function onVAccordionClick(event:MouseEvent):void
            {
            	var ai:MxAccordianItem = event.target.data as MxAccordianItem;

            	if(ai != null)
            	{
            		trace("Title --> " + ai.title);
// Put your code here to perform some actions.
            	}
            }
		]]>
	</mx:Script>

	<flexlib:VAccordion id="accordion"
		headerLocation="above" width="100%" creationPolicy="all"
		resizeToContent="true" headerRenderer="component.MxAccordianHeader"
		click="onVAccordionClick(event)"
		verticalGap="0" horizontalGap="0">

		<component:MxAccordianItem title="Home"
			description="Home for your personal financial intelligence"
			/>

		<component:MxAccordianItem title="Catalog"
			description="Manage your accounts and categories"
			menubarXML="{catalogMenuXML}" menuHandlerFunction="{catalogMenuHandler}"/>

		<component:MxAccordianItem title="Activity Log"
			description="Your activities log book" />

		<component:MxAccordianItem title="Retrospect"
			description="Analyze your finances" />

		<component:MxAccordianItem title="Insight"
			description="" />

		<component:MxAccordianItem title="Bingo!"
			description="" />

	</flexlib:VAccordion>
</mx:VBox>

The following listing is about AccordianItem


<?xml version="1.0" encoding="utf-8"?>
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml"
    width="100%" height="100%"
    verticalAlign="middle" horizontalAlign="center"
    showEffect="Fade"
    verticalScrollPolicy="off" horizontalScrollPolicy="off"
	creationComplete="initCollections()"
	xmlns:flexlib="http://code.google.com/p/flexlib/">

    <mx:Script>
        <![CDATA[
            import mx.collections.XMLListCollection;
	    import mx.events.ItemClickEvent;

            [Bindable] public var description:String;
            [Bindable] public var title:String;

            public var menubarXML:XMLList = null;
			[Bindable] private var menuBarCollection:XMLListCollection;

			public var menuHandlerFunction:Function;

			private function initCollections():void {
				menuBarCollection = new XMLListCollection(menubarXML);

				if(menubarXML != null)
				{
				}
			}

			// This is put in place to ensure that the accordion does not show empty space when
			// a menu does not exist
			private function onResize(event:Event):void
			{
				if(menubarXML == null)
				{
					vmb.height = 0;
					vmb.width = 0;
				}
			}
        ]]>
    </mx:Script>

	<flexlib:VerticalMenuBar id="vmb"
		resize="onResize(event)"
		width="100%" height="100%"
		direction="right"
		labelField="@label"
		itemClick="menuHandlerFunction(event);"
		dataProvider="{menuBarCollection}"
		showEffect="Fade" />
</mx:VBox>


Leave a comment

5 Minutes on Adobe Flex – A reusable XMLFile class

Handling files in Flex is something each application will do, I hope this XMLFile class can be useful out there.  Further this class can be extend to handle specific objects like Application preferences.   The listing of PreferencesFile source is here

XMLFile.as


package foss.afxtionlib.files
{
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;

	public class XMLFile
	{
		protected var _directory:File = null;
		protected var _file:File = null;
		protected var _data:XML = null;

		public function XMLFile(fileName:String, storageDirectory:File=null)
		{
			if(storageDirectory == null)
			{
				_directory = File.documentsDirectory;
			}
			else
			{
				_directory = storageDirectory;
			}

			if(_file == null)
			{
				_file = _directory.resolvePath(fileName);
			}

			if (_file.exists) {
			    _data = readXML();
			}
		}

		public function get file():File
		{
			return(_file);
		}

		public function set file(file:File):void
		{
			_file = file;
		}

		public function get data():XML
		{
			return(_data);
		}

		public function set data(xml:XML):void
		{
			_data = xml;
		}

		public function set directory(storageDirectory:File):void
		{
			_directory = storageDirectory;
		}

		public function get directory():File
		{
			return(_directory);
		}

		public function saveXML():void
		{
			var outputString:String = '<?xml version="1.0" encoding="utf-8"?>n';
			outputString += data.toXMLString();
			outputString = outputString.replace(/n/g, File.lineEnding);

			var stream:FileStream = new FileStream();
			stream.open(file, FileMode.WRITE);
			stream.writeUTFBytes(outputString);
			stream.close();
		}

		public function readXML():XML
		{
			var stream:FileStream = new FileStream();
			stream.open(file, FileMode.READ);

			data = XML(stream.readUTFBytes(stream.bytesAvailable));
			stream.close();

			return(data);
		}
	}
}

PreferencesFile.as


package foss.afxtionlib.files
{
	import flash.filesystem.File;

	public class PreferencesFile extends XMLFile
	{
		private var _templateXML:XML = null;

		public function PreferencesFile(tx:XML)
		{
			_templateXML = tx;
			super("Preferences.xml", File.applicationStorageDirectory);

			if(file.exists == false || data == null)
			{
				setPreferences();
			}
			trace("PSP=" + file.nativePath + "ndata=" + data);
		}

		public function setPreferences(d:XML=null):void
		{
			if(d == null)
			{
				data = _templateXML;
			}
			else
			{
				data = d;
			}
		}

		public function getPreferences():XML
		{
			if(data == null)
			{
				return(_templateXML);
			}

			return(data);
		}
	}
}


Leave a comment

5 Minutes on Adobe Flex – Binding XML to DataGrid

I’ve been curious to bind XML directly to a data-grid, and here is a way I found to do so.

Assume the following XML data which is defined using attributes as.

var baXml:XML = new XML("<BankAccounts />");
baXml.appendChild(XML('<BankAccount bankName="Bank ABC" accountNumber="12345" />'));
baXml.appendChild(XML('<BankAccount bankName="Bank 123" accountNumber="66666" />'));
baXml.appendChild(XML('<BankAccount bankName="Bank XYZ" accountNumber="77777" />'));

baDG.dataProvider = (xml.BankAccount);

The easiest way to bind this XML directly is better such that I don’t have to build any intermediate arrayCollection or other data structure.

Since we know that the rows are of interest in this scenario, we can bind data directly as data provider elements.

Once it is done, the datagrid uses the XML attribute names directly to render the values

<mx:DataGrid id="baDG" x="25" y="20" width="544" height="156" >
    <mx:columns>
        <mx:DataGridColumn headerText="Bank Name" dataField="@bankName"/>
        <mx:DataGridColumn headerText="Account Number" dataField="@accountNumber"/>
    </mx:columns>
</mx:DataGrid>

The same is not possible when the XML data is defined as elements.  Lets describe the above data as elements now.

var baXml:XML = <BankAccounts>
    <BankAccount>
        <bankName>Bank ABC</bankName>
        <accountNumber>12345</accountNumber>
    </BankAccount>
    <BankAccount>
        <bankName>Bank 123</bankName>
        <accountNumber>66666</accountNumber>
    </BankAccount>
    <BankAccount>
        <bankName>Bank XYZ</bankName>
        <accountNumber>77777</accountNumber>
    </BankAccount>
</BankAccounts>;

Once the elements are defined, the datagrid uses the element names directly to render the values

<mx:DataGrid id="baDG" x="25" y="20" width="544" height="156">
    <mx:columns>
        <mx:DataGridColumn headerText="Bank Name" dataField="bankName"/>
        <mx:DataGridColumn headerText="Account Number" dataField="accountNumber"/>
    </mx:columns>
</mx:DataGrid>

All of this can be done in just 5 minutes 🙂


12 Comments

5 Minutes on Java – A quick tutorial on JAXB

New: You can get entire source code for this post from git-hub: http://github.com/udy/lifencode-samples/tree/master/java/jaxb-in-5-minutes/

This is my first post on 5 minutes series of articles on technology and it’s on JAXB.

Read about JAXB at:

http://java.sun.com/developer/technicalArticles/WebServices/jaxb

http://en.wikipedia.org/wiki/JAXB

My simple approach: Create the XML using bottom up approach, once you know how the XML representation is, things can be easy. Let’s say we want to process a email list and take some actions.

&lt;items&gt;
	&lt;item&gt;
		&lt;firstname&gt;George&lt;/firstname&gt;
		&lt;lastname&gt;Cross&lt;/lastname&gt;
		&lt;email&gt;George.Cross@somedomain.com&lt;/email&gt;
	&lt;/item&gt;
	&lt;item&gt;
		&lt;firstname&gt;Lisa&lt;/firstname&gt;
		&lt;lastname&gt;Monroe&lt;/lastname&gt;
		&lt;email&gt;Lisa.Monroe@somedomain.com&lt;/email&gt;
	&lt;/item&gt;
	&lt;item&gt;
		&lt;firstname&gt;Udy&lt;/firstname&gt;
		&lt;lastname&gt;Udy&lt;/lastname&gt;
		&lt;email&gt;Udy@somedomain.com&lt;/email&gt;
	&lt;/item&gt;
	&lt;item&gt;
		&lt;firstname&gt;Nitha&lt;/firstname&gt;
		&lt;lastname&gt;Udy&lt;/lastname&gt;
		&lt;email&gt;Nitha.Udy@somedomain.com&lt;/email&gt;
	&lt;/item&gt;
	&lt;item&gt;
		&lt;firstname&gt;Balaji&lt;/firstname&gt;
		&lt;lastname&gt;Krishna&lt;/lastname&gt;
		&lt;email&gt;Balaji.Krishna@somedomain.com&lt;/email&gt;
	&lt;/item&gt;
&lt;/items&gt;

Once you know the data, you can submit it to some online tools to generate XML schema.  The one that’s cool and fast is

http://www.xmlforasp.net/CodeBank/System_Xml_Schema/BuildSchema/BuildXMLSchema.aspx

For the above above XML the following XSD schema is generated

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-16&quot;?&gt;
&lt;xsd:schema attributeFormDefault=&quot;unqualified&quot;
	elementFormDefault=&quot;qualified&quot; version=&quot;1.0&quot;
	xmlns:xsd=&quot;http://www.w3.org/2001/XMLSchema&quot;&gt;

	&lt;xsd:element name=&quot;items&quot; type=&quot;itemsType&quot; /&gt;
	&lt;xsd:complexType name=&quot;itemsType&quot;&gt;
		&lt;xsd:sequence&gt;
			&lt;xsd:element maxOccurs=&quot;unbounded&quot; name=&quot;item&quot; type=&quot;itemType&quot; /&gt;
		&lt;/xsd:sequence&gt;
	&lt;/xsd:complexType&gt;
	&lt;xsd:complexType name=&quot;itemType&quot;&gt;
		&lt;xsd:sequence&gt;
			&lt;xsd:element name=&quot;firstname&quot; type=&quot;xsd:string&quot; /&gt;
			&lt;xsd:element name=&quot;lastname&quot; type=&quot;xsd:string&quot; /&gt;
			&lt;xsd:element name=&quot;email&quot; type=&quot;xsd:string&quot; /&gt;
		&lt;/xsd:sequence&gt;
	&lt;/xsd:complexType&gt;

&lt;/xsd:schema&gt;

AFter the schema definition is generated, JAXB plugin can be bought into action to generate code.

Install the JAXB plugin for eclipse from https://jaxb-workshop.dev.java.net/plugins/eclipse/xjc-plugin.html (looks like this plug-in is no longer supported).  I recommend you try it from http://sourceforge.net/projects/jaxb-builder/

Ccreate a XSD file under a eclipse project, and generate code using JAXB (the above URL should show you how to do so).  Make sure you choose the right package names and folder to put the code in.  The package name given here will be used later, I chose “org.onesun.blog.jaxb” as the package name, and chose “src” folder as the destination to generate JAXB classes.  The following source files should now be generated:

ItemsType.java, ItemType.java and ObjectFactory.java

I personally prefer writing an accessor to work the elements generated.  This way working with your email list becomes easy.   Lets examine the EmailListManager.java

While creating JAXB context, just make sure that the package name generated above is the one used, failing which, the application will fail during runtime.  The purpose of this class is just to load the file and unmarshall it, after which you can process the list and take some concrete actions.  Lets discuss about that in another post (say for instance using JavaMail to send HTML email to this users).

EmailListManager.java

package org.onesun.blog;

import java.io.InputStream;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.onesun.blog.jaxb.*;

public class EmailListManager {
	private ItemsType items = null;
	private JAXBContext jaxbContext = null;
	private Unmarshaller unmarshaller = null;

	public EmailListManager(String packageName) {
		try {
			jaxbContext = JAXBContext.newInstance(packageName);
			unmarshaller = jaxbContext.createUnmarshaller();
		} catch (JAXBException e) {
		}
	}

	@SuppressWarnings(&quot;unchecked&quot;)
	public List loadXML(InputStream istrm) {
		try {
			Object o = unmarshaller.unmarshal(istrm);
			if (items == null) {
				items = (ItemsType) (((JAXBElement) o).getValue());
				return (items.getItem());
			}
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		return null;
	}
}

Finally the application can be validated with the xml document used for generating XSD, which will parse through the list of items and print them to stdout.
Main.java

package org.onesun.blog;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.onesun.blog.jaxb.*;

public class Main {
	public static void main(String[] args) {
		EmailListManager xmgr = new EmailListManager(&quot;org.onesun.blog.jaxb&quot;);
		File file = new File(&quot;etc/data.xml&quot;);
		List rtList = new ArrayList();
		try {
			FileInputStream fis = new FileInputStream(file);

			if(fis == null) {
				return;
			}
			rtList = xmgr.loadXML(fis);
			Iterator rtItr = rtList.iterator();
			while (rtItr.hasNext()) {
				ItemType item = (ItemType) rtItr.next();
				System.out.println(&quot;First Name = &quot; + item.getFirstname().trim()
						+ &quot;ttLast Name = &quot; + item.getLastname().trim()
						+ &quot;ttEmail = &quot; + item.getEmail().trim());
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
}

With this you’re set to use XML you generated for anything you like to do.  Hope this was helpful to you in some way, and believe that you enjoyed the simplicity of it


Leave a comment

Money and common sense …

To achieve a goal one needs a strategy, and every strategy needs a plan.  To plan, one needs to understand what is important and what is not.

How rich are you?

It does not matter how much one inherited, how much money one makes per month, because I have seen some people loose that money inherited or earned in bizarre ways.  What really matters is how one manages money they have to make it grow with time and use it to satisfy personal needs and help others in need, which is in my opinion called being rich.

What’s your priority?

  • Feel Secure
  • Live in comfort
  • Become rich

You guessed it right, “Becoming Rich” is the best option, it will not only make you feel secure and live in comfort but make one wealthy too, it is not impossible however it needs comprehensive and continuous planning fueled by perseverance and focus.

Why Plan?

Anyone who has financial challenges to solve or financial goals to achieve needs financial planning. Financial Planning can help to achieve both greater wealth and financial security. Inadequate or improper planning can be financially disastrous. An uninsured loss can wipe out accumulated wealth; insufficient savings for retirement can force a reduced lifestyle and/or postponement of retirement; and improper tax planning can result in higher than necessary taxes causing money to be lost to an accumulation plan or to one’s heirs.

How to plan?

  • Identify goals and objectives (must be realistic, specific and measurable)
  • Gather necessary data (establish budget, monitor cash flow)
  • Analyze present situation and consider alternatives (asses net worth, prepare financial statement)
  • Develop strategies to achieve goals
  • Implement the strategies
  • Review and revise periodically

Choosing investment tools?

There are plenty of tools in the market (stocks, mutual funds, bonds, real estate and so on), they are just tools one could use to reach a goal, what suits one might not suite the other, as needs of each is unique. One can choose all of the tools to be a part of a strategy.

Timing?

I often hear from friends that they will time the market to make money, I say that’s wrong!  Just remember that it is never too late to start, and time never waits, the earlier you start, the better it is.  By trying to time, one looses time, as the old saying goes, time is precious, time lost is never found again.

Making money or getting rich?

If your idea is just to make money, trust me that is just temporary, you might earn X today, and loose Y tomorrow.  Getting rich is a broader perspective, so ones mind must be constantly planning to be rich, this way you will be an exceptional investor and planner instead of becoming just a trader.

Manage risk!

If you consider investments are risky, try to manage risks.  Without taking risks, it is difficult to achieve anything.  Do not compete, you want to become rich, so there is no point in competing with another one to get rich, as it leads to more ups and downs.  Remember, needs are unique.

Being financially literate

Understand that investing is a plan, know about the different avenues available to invest.  Know what is really an asset, liability or an expense.  To me, asset is something that can generate money to manage my expenses incurred in a month without the need for me to work, this is indeed a state of being rich.  If you own a house on which you have mortgage to pay; it is taking money out of your pocket, so it will be a liability, it does not become an asset if you’ve occupied it (even after paying back the mortgages).

Team Work

Investing is team work, Communication with your financial adviser (being open and honest), legal adviser is important.  Sharing ones experiences with other investors (learn to differentiate the investor from others) enhances knowledge, learning from others mistakes and correcting the course of your action is always helpful.

Gaining Control

Self Control: This determines your success in the long run.  It takes time and one should learn that there are multiple right answers.  Each decision one makes impacts the future course of action.

Control over income, expense, asset, liability ratio: The way one manages cash flow, personal expenditure.  Liabilities should not become expenses.  Expenses should not increase with raise in income.  Remember not to get into rat race.  Being an investor simply means acquiring assets that put money in your pocket, just that simple.

Control over management of investments and taxes: Know where the tax advantage is, what tax laws are.

Control over when to buy and when to sell: Delayed gratification is important.  Timing does not help in most of the time, patience however pays.

Samprathi (The present!)

The world has changed in few years, the way things are presented have changed so will these common sense make sense now?

Yes, it’ll make sense, frugal living and increasing saving booty will help in a long run, but the tools (avenues) for investment have just changed.  So you need to go with the tide, find the right tools now, the old tools may pave way for new ones (just as one will recycle them).  Choosing the right tools are just as subjective as this subject of money is, hence I’ll let that be taken up individually.


1 Comment

Preventing a personal dooms day …

Aaaaahhhhhhhhhhhh! what’s this post about?

Scary? yes of course … who doesn’t talk about dooms day? well what is interesting is the way things are turning around this financial crisis (2008-2009) everywhere.

Somehow my gut feeling is that the hole is just been dug deeper! What just happened, lets see …

  1. There was the money gone! where did it go, no one knows
  2. In accounting, if there is a credit into some account, it must also debit somebody else, right? then, who was benefited in this recession, no one knows?
  3. And how much is need to recover the giants from collapsing? … plenty of billions! how do you get them? … Borrow them again  … ah! ah!
    1. I guess we got into a smaller hole by borrowing and defaulting in smaller scale, now to get out the smaller hole, one just dug a little bigger one, use the dirt from the bigger hole to fill up the smaller hole.
    2. What do you see? the small hole is covered, there is lots of extra dirt left which can be used to give to all the needy to cover up each of the small holes they got into personally …
    3. What you don’t see is that where did this extra dirt came from? what is happening? who is providing it? just ponder about it and you’ll see a big drama unfold ;

What is funny, no body cares, life has to just go on, we’ll forget the past as we all are busy in a materialistic world and have to survive somehow to see a better future … but where is the better future? where is it? what is it?

Anyways, sitting on a pile of tissue papers whose value locally inflates, but elsewhere it appreciates due to all the global economic entanglement, one can benefit only a short term, but in long term … it’s just a tissue paper.  Oh wait, I’m just talking about the money here … yes money (the paper) is just a tissue paper over time.

For instance, Indian Rupee is getting weaker each day, due to lots of factors, but who is happy, exporters and those who want to send Funds from US to India; so what happens the cash reserve with India just increases, just making the Rupee weaker (just one of the factors).  And how is the recession being controlled, by borrowing from others.

With a pile of US$ just sitting and the money from borrowers coming as US$ (presumably) the $ reserve just increases, not just with India, the same could be happening in each country, thus making the $ look stronger.  But what’s in the future of dollar? only god knows about it.  When that days arrives, what will happen to $ is simple, just use it as tissue paper.

So how to take care of it?

  1. keep only a minimum amount in the form of money (just to make one last for next six months)
  2. convert everything else to assets in the form of land, precious metals, art-in-demand.
  3. Keep options open, stay away from common greed, don’t buy shares and other money market instruments, they make the selling entity rich by using your money, not you.
  4. Insurance … I don’t believe this concept, so it’s left to you … but to me, it’s just a waste of money.  Instead put aside some asset that you can cash when needed for emergencies.

I guess thats enough for now … we’ll talk more as things unfold as we go forward.

Help yourself avert global doomsday becoming a personal dooms day.