Archive

Archive for the ‘Advanced’ Category

Augmented Reality and my tough times

February 13, 2010 Leave a comment

Hi everybody! I have been trying my hands on flar-toolkit (flex based augmented reality libarary) for quite some time. Initially i went through some of the examples in web to get started but once i got in to it, i felt it was not much easier as i thought. The app which i have been working demanded me to work with multiple markers and i have tried to accomplish with flar manager which is a framework of augmented reality for flash based on saqoosha flar-toolkit library and it had bunch of examples which helped me to pass through the first puzzle thrown at me.

The next one was detecting the markers in the order in which it has been placed. I had examples and references in web to got through my first puzzle but this time i realized that i was on my own. But the year of experience in flex helped me to got through this one. Yes I managed to achieve it by ordering the markers based on its x and y coordinate which would be the first thing strike in your mind if you have been part of flash platform.

The last one was the worst nightmare i went through in my recent times. Actually what i wanted to do was, had to do computation with detected markers and show my result as 3D object which doesnt have any corresponding marker. I just wanted to add it to the scene but it was not so easy as i have been telling. The reason was whenever markers were detected, computation would be done followed by 3D model would be added to scene. Just imagine how many times it would get executed and how many children would get added in a second. Further more what if it would be, if you could not clear up the old 3D models ? . Yes thats what i went through actually and my app started to respond as my old girl friend (sorry i dint have one)  i.e. i would have to wait indefinitely to get her reply.

But in my case it was not necessary to show up 3D model as i needed to show an integer value as result but we were decided to use 3D model earlier as it would bring 3D feel. When we had been looking for alternate solution i stumbled upon Text3D class in papervision 3D but it dint help me to bring what was expected. Then i tried to fix the issue in 3D model until i found TextField3D class in away 3D which was more look alike what i have been looking for.

Finally I have created only one instance of TextField3D class and used to update the result by setting its text property. Yup i told myself i got escaped and completed the task successfully. However i would have been more happy if i have found the fix for 3D model memory leaking  but i dint have patience and perseverance to get it done thats where I realized i am easily giving up instead of fighting for it and felt myself that i must develop so called ” never say die attitude” to stay alive in the race.  Thank you reading my horrible experience. lolz!!!

Disclaimer : Hereby i am not criticizing  anyone library, in fact i admire them and seeing them as my ideal. So whatever i have been posted here it was personal experience and even you may call it as my inability to get it done.

Augmented Reality (or) Computer Generated Reality

January 23, 2010 Leave a comment

Are you the one who amazed when you have watched the alien warship dashboard in films ? Are you the one who asked yourself “is it possible in real time ?” when arnold was scanning environment as he was walking, in the Terminator sequel. Some of you might not be, but i am really longing to develop like these ?. Imagine, how would it be interacting with web without computer and you  just sees the data in virtual screen ?. Yes we can make it possible all of these  using  Augmented reality (AR).

What does it mean ?

It superimpose graphics, audio and other sensory enhancements over real world environment in real time and allows to interact with three dimensional computer generated graphics.It blurs the line between what is real and what computer program gives you to feel, smell and hear which is actually not real. In short, it combines the physical world and three dimensional virtual world.

Where was it started-off ?

It is originated from virtual reality also known as user’s physical reality. Its an virtual environment that is generated by program and rendered to the user in such a way that the user ignores belief and accepts it as a real environment. VR  is primarily experienced through two of the five senses: sight and sound.

At first augmented reality applications found his way in to mobile platform especially IPhone and Android OS based mobiles. One of the applications is Layar, which examines the real world environment,  process it and projects the relevant information in computer generated graphics. The other worth mentioning application is Wikitude which retrieves the information from Wikipedia.

Later MIT Media Lab came with brilliant device named sixth sense which processes the image, gathers GPS coordinates and pulls data from the Internet and then projecting information onto the surface in front of the user.

Where would it go from here ?

Now augmented reality is getting adopted in all the possible areas ranging from gaming to military devices all around the globe. It will surely redefine all the gadgets so far invented, in the way it looks and works. Because it provides rich user interface by adding colors and effects and make the users to experience reality and also the computer generated graphics (sorry!!! computer generated reality) is less expensive with current technology so it would not find any barrier in its way.

I hope, few years down the line we don’t need multiple gadgets to make our life easier, all in one would become reality with the help of augmented reality. Thank you for reading this post.

Simple CSV Exporter

December 27, 2009 1 comment

Hi guys, when i wanted to write a  post about this topic i was clear that i am not gonna do something which no one would have done before but it will at least save others time who doesn’t familiar with CSV export. Unfortunately we doesn’t have enough example available for CSV export in web and that’s what compromised myself to write a post about it.

Now check out the simple CSV exporter utility class pasted below. Its a singleton class and  has method named exportCSV which writes the object from the collection to a chosen CSV (string delimited file) file. But when i wrote the class, i had two things in mind that not always developers want to write all the properties of an object, most of the times it will be only few so i wrote this method which receives array of properties of an object in the order it has to be written. And also the string delimiter will different from the requirements of an application so one can also pass the string delimiter they would like to use against the default string delimiter (“\t”) .

package
{
  import flash.filesystem.File;
  import flash.filesystem.FileMode;
  import flash.filesystem.FileStream;

  public class CSVExporter
  {
    protected var file : File;
    protected var dataProvider : Array;
    protected var columnFields : Array;
    protected var fileStream : FileStream;
    protected var columnSeparator : String;

    protected static var NEW_LINE : String = "\n";
    private static var instance : CSVExporter;

    public static function getInstance():CSVExporter
    {
      if(instance == null)
        instance = new CSVExporter();
      return instance;
    }

    public function exportCSV(file : File,
                              dataProvider : Array,
                              columnFields : Array,
                              columnSeparator : String = "\t")
    {
      this.file = file;
      this.dataProvider = dataProvider;
      this.columnFields = columnFields;
      this.columnSeparator = columnSeparator;

      fileStream = new FileStream();
      fileStream.open(file, FileMode.WRITE);
      writeHeaderRow();
      parseDataProvider();
      fileStream.close();
    }

    protected function writeHeaderRow():void
    {
      for(var index = 0; index < columnFields.length; index++)
      {
        fileStream.writeUTFBytes(columnFields[index].toUpperCase());

        if(index != columnFields.length - 1)
          fileStream.writeUTFBytes(this.columnSeparator);
      }
      fileStream.writeUTFBytes(NEW_LINE);
    }

    protected function parseDataProvider():void
    {
      for(var index : int = 0; index < this.dataProvider.length; index++)
      {
        writeDataRow(dataProvider[index] as Object);
        if(index != dataProvider.length-1)
          fileStream.writeUTFBytes(NEW_LINE);
      }
    }

    protected function writeDataRow(data : Object):void
    {
      for(var index : int = 0; index < columnFields.length; index++)
      {
        var property : String = columnFields[index] as String;

        if(data[property] != null)
          fileStream.writeUTFBytes(data[property] as String);

        if(index != columnFields.length-1)
          fileStream.writeUTFBytes(columnSeparator);
      }
    }
  }
}

Here it goes, the method which invokes CSV Exporter :-

protected function writeCollection():void
{
  var dataCollection : ArrayCollection = new ArrayCollection();
  dataCollection.addItem({name : "Sachin", age : 35, role : "All-rounder", state : "Mumbai"});
  dataCollection.addItem({name : "Sehwag", age : 30, role : "All-rounder", state : "Delhi"});
  dataCollection.addItem({name : "Gambhir", age : 25, role : "Batsmen", state : "Delhi"});
  dataCollection.addItem({name : "Yuvraj", age : 28, role : "All-rounder", state : "Punjab"});
  dataCollection.addItem({name : "Virat", age : 24, role : "Batsmen", state : "Delhi"});
  dataCollection.addItem({name : "Dhoni", age : 25, role : "Wicket-keeper",state : "Jharkand"});

  var  file : File = File.desktopDirectory.resolvePath("friends.csv");
  CSVExporter.getInstance().exportCSV(file, dataCollection.toArray(), ["name","role","state"]);
}

I hope you would have got brief insight about CSV exporting at the end of this post. If this post dint impress you for what you have looked for, please drop your comments i try to look out a solution for your need. Thank you for reading this post.

Prompt TextInput with ignore text

November 15, 2009 5 comments

There are cases in which we need more than text input, which should let the user to notify with some custom text  in text input whenever it is empty. i.e. prompt text input. But there are special cases in which we should even treat some text as empty and should show the prompt text in text input. I went through this need when my client asked me to show a prompt text in text input whenever it is zero. We could restrict zero in text input by using conditional expression in text property, provided we must ensure wherever we are setting the text input.

So i have decided to extend the text input component so that i could restrict zero in one place called set text(value : String) method. when i wanted to implement, i needed prompt text input and i asked myself why should not i do that too. I went ahead did at last.

You can find the implemented component code below which allows you to set ignore text (the text you want to treat as empty text) and you can also enable/disable the prompt text input. If it is disabled, it would function as normal text input.

Click here to download sample application

package
{
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.FocusEvent;

	import mx.controls.TextInput;
	import mx.utils.StringUtil;
	[Style(name="promptStyleName", type="String")]
	public class PromptIgnoreTextInput extends TextInput
	{
		[Bindable] private var textEmpty : Boolean;
		public function PromptIgnoreTextInput()
		{
			super();
			this.addEventListener(FocusEvent.FOCUS_IN, handleFocusIn);
			this.addEventListener(FocusEvent.FOCUS_OUT, handleFocusOut);
			this.addEventListener(Event.CHANGE, handleChange);
		}
		[Bindable] private var _prompt : String;
		public function set prompt(value : String):void
		{
			_prompt = value;
		}
		public function get prompt():String
		{
			return _prompt;
		}
		[Bindable] private var _ignoreText : String;
		public function set ignoreText(value : String):void
		{
			_ignoreText = value;
		}
		public function get ignoreText():String
		{
			return _ignoreText;
		}
		[Bindable] private var _enablePrompt : Boolean;
		public function set enablePrompt(value : Boolean):void
		{
			_enablePrompt = value;
		}
		public function get enablePrompt():Boolean
		{
			return _enablePrompt;
		}
		override public function set text(value:String):void
		{
			value = StringUtil.trim(value);
			if(value != null && value != "")
			{
				if(value == ignoreText)
				{
					textEmpty = true;
				}
				else
				{
					textEmpty = false;
				}
			}
			else
			{
				textEmpty = true;
			}

			super.text = value;
			invalidateDisplayList();
		}
		override public function get text():String
		{
			return super.text;
		}
		override protected function updateDisplayList(unscaledWidth:Number,
		unscaledHeight:Number):void
		{
			if(_enablePrompt)
			{
				if(textEmpty && !isCurrentlyFocussed())
				{
					super.text = prompt;
					this.styleName = getStyle("promptStyleName");
				}
				else if(textEmpty && isCurrentlyFocussed())
				{
					super.text = "";
					this.styleName = "";
				}
				else
				{
					this.styleName = "";
				}
			}
			super.updateDisplayList(unscaledWidth, unscaledHeight);
		}
		protected function isCurrentlyFocussed():Boolean
		{
			var focussedComponent : DisplayObject;
			focussedComponent = focusManager.getFocus() as DisplayObject;
			if(focussedComponent)
			{
				if(focussedComponent == this || this.contains(focussedComponent))
					return true;
			}
			return false;
		}
		protected function handleFocusIn(event : FocusEvent):void
		{
			invalidateDisplayList();
		}
		protected function handleFocusOut(event : FocusEvent):void
		{
			text = super.text;
			invalidateDisplayList();
		}
		protected function handleChange(event : Event):void
		{
			textEmpty = (super.text.length == 0 || super.text == _ignoreText) ?
			            true : false;
		}

	}
}

Please let me know if you find any problem or have any suggestion about this component so that i could refine this code when i find time. Thank you for reading this post.

Dont re-invent Datefield when it needs to be editable

November 14, 2009 6 comments

Hi guys, we always look for customization if the feature we are looking,  is not available in the flex framework. But  if the same thing is possible with  minor tweaks, what is the need of re-inventing the wheel. I have experienced this scenario when i needed to implement a DateField which should allow the users to edit it as well as it has to display a DateChooser when they edit it, which is not quite possible even if you make editable property of  DateField is true.  As usual i went for google search and found couple of developers created their own component using Grid. I dint have enough time to test and use their component, i stumbled upon dateField public functions named open() and close().

Atlast I found the way of how to show a DateField dateChooser when i make editable property to true ( normally DateChooser wont show up if we make editable true). I extended the DateField component , invoked open() in focus-in event handler and i have done what i wished to be done without spending much time. further if you are not compromised with the position in which DateChooser shows up, you could change the x and y values of dateChoooser of DateField in  its open event.

Check out the below code for reference.

package
{
import flash.events.FocusEvent;
import flash.geom.Point;

import mx.controls.DateField;
import mx.events.DropdownEvent;

public class EditableDatefield extends DateField
{
public function EditableDatefield()
{
super();
this.addEventListener(DropdownEvent.OPEN, onOpenDropDown);
this.addEventListener(FocusEvent.FOCUS_IN, onFocusIn);
}

protected function onFocusIn(event : FocusEvent):void
{
this.open();
event.stopImmediatePropagation();
}

protected function onOpenDropDown(event : DropdownEvent):void{
var point : Point = new Point(this.textInput.x, this.textInput.y);
var targetCoordinates : Point = this.localToGlobal(point);
dropdown.x = targetCoordinates.x - dropdown.width/2 + textInput.width/2;
dropdown.y = targetCoordinates.y + textInput.height + 5;
}
}
}

I hope this post would atleast help one flex developer and would save his/her time. If you find any problem with above code, please let me know i will try to resolve it as much as possible. Thank you for reading this post!

How to deploy flex application in Tomcat

May 15, 2009 32 comments

Hi everybody, deploying flex application is not a big deal and it is very very simple using flex builder. Once you have configured your server settings when you created flex project in flex builder then whenever you compile the flex application, it will automatically deploy your flex application in application server and whenever you run your flex application it will run from the tomcat server and not from the actual location of the flex application.

To deploy flex application you must have two servers and they are follows.

  • BlazeDS server
  • Tomcat application server

I dont want to tell much about Tomcat server because you all know that its application server where we used to deploy our flex application so i do want to concentrate on BlazeDS server. BlazeDS is a open source server which provides set of services which allow flex application communicate with server side java classes and it also helps multiple flex clients communicate with each other. It provides pre-configured web application which does most of our task and help us to easily integrate flex application with server side technologies. So whenever flex application request Java class, blazeDS will interpret, redirect to  corresponding java class and return response to the flex application.

Now its time to explain how to deploy flex application. First create a new web application in the webapps directory of tomcat home directory. ie create new folder in the webapps directory of tomcat home directory. Extract blazeDS.war and will get two folder META_INF & WEB-INF,  copy those folders in to your web application.

Open the flex builder and create a new project. In the new project wizard, dont forget to select application server type as J2EE  and click next. In the configure j2ee server wizard, please uncheck the “use default location for lifecycle data services server” check box and in the “root folder” please specify the root location of your web application you have created in the webapps directory of tomcat home directory. similarly specify your web application name in root URL and context root

Eg :  root URL : http://localhost:8080/{web application name}

Context root : /{web application name}

Now click the validate configuration button before that please ensure that whether the tomcat server is running in your machine or not.  If you have followed all the steps i have described above then it will show that the web root and URL are valid, then as usual click finish. Thats it !!!, you have integrated flex application with tomcat. hereafter whenever you compile flex application it will be updated in tomcat server and when you run the application it will run from the tomcat server and definitely not from the actual location of the flex application.

At last i do have a confession that i have tried my best to make you understand how to deploy flex application in tomcat. If you have any doubt or if i go wrong anywhere please drop as your comments, i will try to fix it as soon as possible. Thank you !!!