Set cursor position in the Flex Text Controls

September 19, 2012

You have a text control in flex. At some random event, you need to focus the text control. Simple, right. Just give :

txtInput.setFocus();

All is fine. So what if you need to add some text to the text control? Like the following :

txtInput.text = “@anoop_pk”;
txtInput.setFocus();

This will definitely bring the focus on the control. But hold on. The cursor will be blinking on the beginning of the text and you want it to set to the end of the text. Okay it is quite simple. Flex framework provides with method setSelection for the text controls. Which can be used to select a part of the text in the text controls programatically. The typical usage is like this :

txtInput.setSelection(1,6);

We can use this to achieve our task by giving like this :

txtInput.setSelection(txtInput.text.length, txtInput.text.length);

We are infact selecting nothing, but this will force the cursor to move to the end of the text. Thats it guys, a small tip to keep my writing active. Lots of work. See you. Happy Coding. 🙂

Advertisements

Java Optimization Tips

July 27, 2012

When writing Java code it can be easy to make simple mistakes that seem harmless on the surface but, as our applications grow larger, they can show themselves to be slow, resource intensive processes that could use a tune-up. Luckily there are some easy ways to optimize your Java code that you can begin using today. Here, we will introduce you to five of them.

1. Avoid unnecessary casting

Casting, for the new developer, is a way of converting between reference data types. Most casting is done to allow a more generic form of programming where your code will be able to work with all types of objects and classes that are descended from some type of base class.

However, new programmers do not always write these casting statements correctly and are creating a situation where they are improperly casting and creating more overhead for their application in the VM than necessary. An example:

class MyCastingClass {
    public Object myMethod() {
        String myString = "Some data";
        Object myObj = (Object) myString;
        return myObj;
    }
}

Ok, let’s examine the statement Object myObj = (Object) myString; which is violating the unnecessary casting rule. There would be no reason to explicitly cast the string to an Object type since the string class already inherits from Object. Casting also bypasses the safety checks of the Java compiler and can end up causing errors at execution. The proper way to write this code would be:

class MyCastingClass {
    public Object myMethod() {
        return "Some data";
    }
}

Clean, easy to read and maintainable while preserving the rules of the compiler and creating less memory overhead. A very simple fix.

2. Eliminating Common Sub Expressions

A common mistake is the use of the same common sub-expression repeatedly in your code, yet you continue to type it out for each calculation. An Example:

int someNumber = (someValue * number1 / number2) + otherValue;
int someNumber2 = (someValue * number1 / number2) + otherValue2;

You may not realize it but you do this all the time. Performing a calculation that has a portion repeated over and over for each calculation. Because part of the calculation changes each time, you didn’t think to loop it and save yourself some trouble. Instead you are being redundant and slowing down the speed of your calculations. Here is a fix:

final int constantCalculation = (someValue * number1 / number2);
int someNumber = (constantCalculation) + otherValue;
int someNumber2 = (constantCalculation) + otherValue2;

Bingo! By placing the repeated portion of the sub-expression into a constant we can reuse it for multiple calculations without being redundant. A deceptively simple optimization.

3. Use StringBuffer (or StringBuilder) instead of String for non-constant strings.

Since strings are immutable objects and cannot change it creates a lot of overhead when you perform actions with string objects that the compiler must transform in order to interpret. Operations that appear to change string objects are actually creating new ones behind the scenes in order to perform your operation. The overhead on this becomes higher when you use String instead of StringBuffer (or StringBuilder). For Example:

class MyStringClass {
    public void myMethod() {
        String myString = "Some data";
        for (int i = 0; i < 20; i++) {
            myString += getMoreChars();
        }
    }
}  

This is the reason that the StringBuffer class exists, to provide assistance when concatenating strings since a new object would need to be created to transform the string. The new object the compiler will create is of type StringBuffer. A new string object would then be created to copy the finished string at the end of the transformation, thus creating two new objects to perform this simple step.

The difference between StringBuffer and StringBuilder is that the former is thread-safe, which is great in some cases, and an overhead in others. All StringBuffer‘s methods are synchronized. StringBuilder isn’t thread-safe and its methods aren’t synchronized, which is much more performant when you just need to use it as a local variable.

The solution would be to cut out the StringBuffer middle-man and make our own StringBuffer object so the compiler doesn’t have to:

class MyCastingClass {
    public Object myMethod() {
        String myString = "Some data";
        StringBuffer myBuffer = new StringBuffer();
        for (int i = 0; i < 20; i++) {
            myBuffer.append(getMoreChars());
        }
        myString = myBuffer.toString();
    }
}

Voila! By creating our own StringBuffer class the compiler no longer has to create one for us to do the transformation. This means there is now only one new string object being created during this process when we call the toString() method of the buffer to transfer that data to myString.

4. Use Short Circuit Boolean Operators

When making logical checks or tests in your code, the use of short-circuit evaluation will almost always speed up the time it takes to make the evaluation because the compiler does not have to check the second condition. When two expressions are joined by an OR (||) as long as the first one is true the compiler will not check the second condition, it will assume the whole statement to be true. This also works with AND (&&) where the compiler will evaluate the first state and if false, will evaluate the whole statement to false. However, the logical OR (|) does not use the short circuit evaluation.

Using || saves the compiler time by not having to check both conditions because it wouldn’t change the outcome of the statement. Here is an example of what usually happens:

class MyShortCircuitClass {
    public void myMethod() {
        if (someValue.equals("true") | someValue.equals("false")) {
            System.out.println("valid boolean");
        }
    }
}

What ends up happening in the above example is that the compiler has to check both conditions and evaluate a true or false for each even through the OR logic would have made it true if the first condition evaluated to true. Here is a better way to write these kinds of statements:

class MyCastingClass {
    public void myMethod() {
        if ("true".equals(someValue) || "false".equals(someValue)) {
            System.out.println("valid boolean");
        }
    }
}

By using short-circuit evaluation you will speed up the time it takes for the compiler to make boolean logical decisions and thus the overall processing time of your application.

Here’s a table describing four of Java’s boolean operators:

Meaning Short circuit?
&& and yes
& and no
|| or yes
| or no

The && and || operators are short circuit operators. A short circuit operator is one that doesn’t evaluate all of its operands.

5. Use length() instead of equals() to find the length of a string

It seems to be common practice among developers that when testing for an empty string to use the equals() method, like so:

class MyStringClass {
    public boolean myTestMethod() {
        return myString.equals("");
    }
}

The problem here is the sheer overkill taking place by using equals() due to the higher overhead. The issue comes from the implementation of equals() which is designed to test if two objects reference back to the same object class. The alternative, length() (or isEmpty()), just tests to see if the references point to the same underlying object type. This is a much more efficient way if you are just testing for an empty string. You don’t care about object types or if they reference back to the same class, so quit using a sledgehammer to pound the nail. Here is how you should be testing for empty strings:

class MyCastingClass {
    public void myMethod() {
        public boolean myTestMethod() {
            // which really does myString.length() == 0 behind the schenes
            return myString.isEmpty();
        }
    }
}

Using length() provides a much more efficient method for testing for empty strings that does not require object reference overhead from the compiler.

Remember that code optimization doesn’t require fancy tricks and unreadable code. These are often simple changes that you can start making today that will speed up your processing time and make your code better. A lot of optimization is getting into the underlying processing of the compiler and understanding what is taking place in the code that you write. By learning these tips now you can begin to implement them into your solutions every time, thus making you a better developer in the process.

Courtsey : 5 Easy Java Optimization Tips/

The Ten Commandments of Egoless Programming

July 11, 2012

The Ten Commandments of Egoless Programming:

  1. Understand and accept that you will make mistakes. The point is to find them early, before they make it into production. Fortunately, except for the few of us developing rocket guidance software at JPL, mistakes are rarely fatal in our industry. We can, and should, learn, laugh, and move on.

  2. You are not your code. Remember that the entire point of a review is to find problems, and problems will be found. Don’t take it personally when one is uncovered.

  3. No matter how much “karate” you know, someone else will always know more. Such an individual can teach you some new moves if you ask. Seek and accept input from others, especially when you think it’s not needed.

  4. Don’t rewrite code without consultation. There’s a fine line between “fixing code” and “rewriting code.” Know the difference, and pursue stylistic changes within the framework of a code review, not as a lone enforcer.

  5. Treat people who know less than you with respect, deference, and patience. Non-technical people who deal with developers on a regular basis almost universally hold the opinion that we are prima donnas at best and crybabies at worst. Don’t reinforce this stereotype with anger and impatience.

  6. The only constant in the world is change. Be open to it and accept it with a smile. Look at each change to your requirements, platform, or tool as a new challenge, rather than some serious inconvenience to be fought.

  7. The only true authority stems from knowledge, not from position. Knowledge engenders authority, and authority engenders respect – so if you want respect in an egoless environment, cultivate knowledge.

  8. Fight for what you believe, but gracefully accept defeat. Understand that sometimes your ideas will be overruled. Even if you are right, don’t take revenge or say “I told you so.” Never make your dearly departed idea a martyr or rallying cry.

  9. Don’t be “the coder in the corner.” Don’t be the person in the dark office emerging only for soda. The coder in the corner is out of sight, out of touch, and out of control. This person has no voice in an open, collaborative environment. Get involved in conversations, and be a participant in your office community.

  10. Critique code instead of people – be kind to the coder, not to the code. As much as possible, make all of your comments positive and oriented to improving the code. Relate comments to local standards, program specs, increased performance, etc.

Courtsey : http://blog.stephenwyattbush.com/2012/04/07/dad-and-the-ten-commandments-of-egoless-programming

Show a default prompt in Flex Combobox

May 8, 2012

At times, you may need to show a combobox, where none of the items should be selected by default and it should show something like ‘Please Select’. One way is to add this object also to the dataprovider, as the first item. But if you think that is a burden for your dataprovider, then Flex SDK provides you a built in option. To be frank, after working in Flex for more than 4 years, I am finding out this now only. 🙂 You can use the prompt property of the combobox to show a default value. This will go away once you select one option, and you cannot bring it back. (I think so, but there are high chances that this is not true).

eg :

<mx:ComboBox id=”comboBox”  dataProvider=”{dataprovider}”
labelField=”name” prompt=”Please select an entry” />

That’s all guys. Flex Your Life. Cheers. 🙂

Calling Flex / Actionscript functions from Javascript

May 8, 2012

Nowadays I am working with Flex projects, that runs on Lotus Notes platform, which consumes data from Lotus Notes backend. Since there is no remote services like BlazeDS to connect to Notes server, am now greatly dependant on HTTPService and Javascript. Calling a javascript function from Flex is quite easy. Just use the ExternalInterface API. For those who don’t know the way, this is how it is getting called.

In AS3

if(ExternalInterface.available){
ExternalInterface.call(“openNotes”, parameter);
}

In Javascript

function openNotes(notesUrl){
window.open(notesUrl, ”, ‘width=1000,height=600’);
}

It is quite easy. But what if you need to call the reverse. ie, calling actionscript function from javascript. We can use the same ExternalInterface api for achieve this. There is a method called addCallback, available in ExternalInterface. addCallback method registers an ActionScript method as callable from the container. After a successful invocation of addCallBack(), the registered function in the player can be called by JavaScript or ActiveX code in the container. The first parameter is the name by which the container can invoke the function and the second parameter is the function closure to invoke. Below is the step-by-step configuration:

Step 1 : Register the call back from actionscript. For eg, call the below method in the creationComplete or initialize event of the component.

private function createCallBack(event:Event):void{
ExternalInterface.addCallback(“updateNotes”, getNotes);
}

private function getNotes():void{
//do whatever you want after getting the hold
}

Step 2 : Create logic in javascript to invoke the AS3 function.

//Javascript
function updateFlex(){
appName.updateNotes();
}

The appName is the name and id of the embedded swf object in the HTML. Like below :

That’s it. Now you can call the updateFlex javascript method from your HTML and it will invoke the AS3 callback function. Enjoy Coding guys. Flex Your Life. Cheers. 🙂

Flex / AS3 – Remove all children of a container

May 8, 2012

I know this is not that big thing. But still wanna scribble it down. In order to remove all the children of the container, there is no set function available. You can write a generic method, may be a static method and call that. The logic is to iterate over all the available children and remove one by one. Something like this :

static public function removeAllChildren(parent:UIComponent):void{
while(parent.numChildren > 0 ){
parent.removeChildAt( 0 );
}
}

The parent can be either UIComponent or its subclass. The best practice would be to write this method in your component itself, so that this method will become a part of the component. Then you can write something like this :

public function removeAllChildren():void{
while(numChildren > 0 ){
removeChildAt( 0 );
}
}

That’s all guys, Happy Coding. 🙂

Adding Glow Filter to Component

April 26, 2012

I got one requirement where I will draw one custom component and it should glow when we mouse hover it and remove glow when move the mouse out. This is a simple thing, though I am putting this so that you can save time. 🙂

First we need to write a function which will be triggered on both mouse hover and mouse out of the component. Obviously it will accept one MouseEvent. Inside that we need to create one GlowFilter and add this filter to the component. Set the properties for the flow filter such as color, alpha and quality. On mouse out am removing all the filters. This will work for me since I do not have any other filters for the component. If you have other filters, then iterate through the filters and remove only the glow filter. The function will look like below :

private function highLightCircle(event:MouseEvent):void{
            var glowFilter: GlowFilter = new GlowFilter();
            var circ:Object = event.currentTarget;
            if(circ.filters.length == 0){  
                glowFilter.color = 0xFFFFFF;
                glowFilter.alpha = 1;
                glowFilter.blurX = 10;
                glowFilter.blurY = 10;
                glowFilter.quality = BitmapFilterQuality.HIGH;
                circ.filters = [glowFilter];
            }else{
                circ.filters = null;
    }
}

Now we need to call this on mouse over and mouse out. Just add the event listeners to the component object on which you need to apply the filter like below.

circle.addEventListener(MouseEvent.ROLL_OVER, highLightCircle);
circle.addEventListener(MouseEvent.ROLL_OUT, highLightCircle);

Thats all guys. Flex your life. Happy Coding. 🙂

Check if an XML node or attribute exists in E4X format

April 25, 2012

E4X is the heaven when it comes to XML parsing. Since flex natively supports E4X format results, it makes our lives very easy. But there are lots of tips and tricks to play in E4X parsing.

Suppose you have an optional XML node and you need to check whether it exists in the XML. Obviously our actionscript and javascript memories will ask us to try this way if(xml.node != null) or if(xml.node). But if you try this, it is not gonna work. It will probably give you unwanted result or if your day is going too good you will get a reference error. The below are some ways you can try out :

For checking Nodes :

if(xml.someNode.length() > 0){ // Node exists }if(xml.someNode != undefined)
{ // Node exists }

For checking Attributes:

if(xml.@someAttr.length() > 0)
{ // Attribute exists }

if(xml.@someAttr != undefined)
{ // Attribute exists }

That’s it guys. Happy Coding! 🙂 Flex your life.

Why MVC? Simply Explained

March 29, 2012

Disclaimer : I collected this from one support forum. Its not my original post.

MVC (Model – View – Controller) is one of those concepts that only starts to make sense when you’re dealing with larger applications and/or when working on the same application with several developers.

Compare it with tasks, if you’ve got 3 tasks that need to be done on a certain date, you won’t feel the need to have some kind of task organization, but if you have to deal with dozens of different tasks, with various due dates you’ll start using todo-lists. Then when you start working with a team of people and you need to prioritize and sequence tasks, you realize simple todo-lists won’t suffice and you’ll end up with applying SCRUM for instance (it obviously deals with more than task management, but it is one of the core parts of the methodology)

The same applies to MVC. It’s benefits are absolutely not restricted to large-scale, team-based development, but they become most obvious in such situations.

Let’s say you need to make a web application that loads some data in a xml file, lets the user do some operations on that data and saves the users edits in a SharedObject.
Fine. It’s a small application, you can develop it pretty fast and there’s no need to start thinking about using MVC or other patterns for structuring your components (not talking about UI components here, just cogs in the machine).
The application is a huge success and your client is extremely satisfied, they ask you to change the application because they’ll be setting up a back end with which the xml file can be manipulated by them, in fact no, they want to use a database instead of the file. And since it’s 2012 they definitely need an iphone app as well.
You’ll start working on the web application and since the deadline’s not just tight, but completely insane chances are you’ll be modifying it to reflect the use case changes, make a copy of the entire project to create the iphone app and again simply making the iOS required changes in that project directly.
Now repeat this five times. The client keeps on asking modifications. expansions etc. These can be UI related changes, but even complete backend architecture swaps, going from REST to SOAP for instance.
If you didn’t structure your project using MVC, you’ll be in a world of pain. No, you’ll be in a world of pain anyway, but had you used MVC from the start you’d notice that some things would’ve been less painful:

  • 95% of the code for the web application and the iphone app will be the same, but instead of saving the user data to a Shared Object or through a web service, you’d be using a local DB for instance. Due to the separation of concerns as promoted with MVC (and even more specifically with RL) you’d notice that the only thing different in the web app and the iphone app would’ve been a single service class. Without MVC chances are pretty high you’ll be making modifications in a bunch of classes.
  • The same applies to the UI for instance. Again, the heart of the application is the same, only the way it’s presented to the user is different. Due to separation of your app into the various tiers you’ll notice that changing the UI for the iphone app, will only have an impact on view classes and you’ll spent a tremendous amount of time less of searching through your code and finding out where to change what.
  • w/o MVC 95% of both apps would still be the same, but the differences would’ve been scattered in various files, here and there some lines, with MVC the differences will be in using different classes, ie the changes are more compact and overseeable.

All in all using MVC makes your code more structured and far more flexible to accomodate change in size, platform etc. etc.

Courtsey : creynders of Robotlegs Support

Getting Oracle Version Number

March 27, 2012

Ever wondered how to know the version number of the Oracle server you are connected to. You can very well use the v$session table.

Select * from v$session;

This will give you 4-5 rows showing all the version numbers of different tools used in the database. Happy Coding Guys. 🙂


%d bloggers like this: