by admin

I didn’t know you could use XML for DataProvider items in AS3!

March 4, 2011 in Actionscript/Flash, Intermediate by admin

I have been manually creating DataProviders for Actionscript 3 for ages!  Or doing it in the Flash Properties area manually as well.  I am a big fan of using XML and am glad there's a way to build combo boxes, and a bunch of other components by using XML for the DataProvider.

import fl.controls.ComboBox;
import fl.controls.Slider;
import fl.data.DataProvider;
import fl.events.SliderEvent;

var items:XML = <items>
        <item label="Item 1" />
        <item label="Item 2" />
        <item label="Item 3" />
        <item label="Item 4" />
    </items>;

var dp:DataProvider = new DataProvider(items);

var mySlider:Slider = new Slider();
mySlider.liveDragging = true;
mySlider.tickInterval = 1;
mySlider.snapInterval = 1;
mySlider.minimum = 0;
mySlider.maximum = dp.length - 1;
mySlider.width = 100;
mySlider.move(10, 10);
mySlider.addEventListener(SliderEvent.CHANGE, changeHandler);
addChild(mySlider);

var myComboBox:ComboBox = new ComboBox();
myComboBox.dataProvider = dp;
myComboBox.move(10, 30);
addChild(myComboBox);

function changeHandler(event:SliderEvent):void {
    myComboBox.selectedIndex = event.value;
}

by admin

Mod rewriting tools for dynamic static URLs

November 28, 2010 in Coding, Concepts, SEO by admin

While trying to mod-rewrite my website at http://theothersun.com, I ran into a tool that helps, it's a tool at this url:

http://www.webconfs.com/url-rewriting-tool.php

You submit a url like so: http://www.widgets.com/product.php?categoryid=1&productid=10 , and it will give you an .htaccess file code that you can save on your server.  It will convert that sample url to something like this: http://www.widgets.com/product/categoryid/1/productid/10/ or http://www.widgets.com/product-categoryid-1-productid-10.htm

Not only does that increase SEO traffic to your site, but it will allow for easy to remember dynamic urls.

by admin

Late Static Bindings in PHP 5.3.0+

November 24, 2010 in Advanced, Concepts, PHP by admin

What are late static bindings?

Late static bindings in PHP are when you  have a parent class with a self keyword and it's trying to communicate that self with a subclass, usually used with static class methods.  It causes problems with early static bindings, that the subclass cannot look at the parent class's self as itself.

Example:

class ParentClass {

static protected $table_name = 'users';

static protected function test() {

print self::$table_name; // to fix late static bindings over PHP 5.3.0, change self to static.
}

}

class SubClass {

function __construct() {

print self::$table_name; // wont work.  Error.

}

}

To use late static bindings, PHP 5.3.0 + must be installed.

Change all your self:: to static::
for example,
self::find_by_sql("SELECT * FROM table_name");

static::find_by_sql("SELECT * FROM table_name");

Instead of using $object = new self; , in a parent class, to make it work, use:

$class_name = get_called_class();
$object = new $class_name;

by admin

A bunch of issues I had when creating The Other Sun

November 8, 2010 in Coding, Concepts by admin

These are some notes on issues that I incurred while working on my “The Other Sun” (my comic strip, http://www.theothersun.com) website:

  • I like to use transparenct Flash backgrounds by using the params in SWFobject, and apparently Safari doesn’t support it.., so unfortunately in Flash i have to make the stage background nearest to my website background and hope that it doesnt look sucky.
  • Make sure you put *. or www. even as well in your domain names in any crossdomain.xml files (should be like , and NOT just , which is what I was doing before.

by admin

When Embedding a Flash Font, select Bitmap text

July 17, 2010 in Actionscript/Flash, Beginner, Coding by admin

While embedding a flash font the other day when coding an advertisement Flash rotator for http://www.theothersun.com, I noticed that by selected "Bitmap text" when embedding a special font into Flash, saves your KB size of the Flash file itself by a good amount. My file was 169 KB, then when I changed it to "Bitmap text", it became 155 KB, a noticeable jump which could save you a lot in the long run.

Upon doing a thorough Google search, I found no disadvantage at using this option, nor is there any visible disadvantage in my program. Post comments if you have conflicting information or information that could help.

155kb Flash Actionscript SWF File by using Bitmap Text

155kb Flash Actionscript SWF File by using Bitmap Text

Bitmap embedded font flash actionscript saves Bandwidth

Bitmap embedded font flash actionscript saves Bandwidth

by admin

How Live HTTP Headers saved me hours of nuisance coding errors

May 23, 2010 in Actionscript/Flash, Coding, XML by admin

So I was working on this Flash application where I had to use a custom built Loader to load external text files and images. It was working great on my local server, but when deploying on a hosted server on the internet, it just wasn't working. I spent hours trying to tweak the code.. no avail. I then turned on Live HTTP headers to see what the heck was it loading on the browser, and viola.. here comes a 500 error from the GET /crossdomain.xml HTTP/1.1 . AH! That was the error, a crossdomain policy file is missing. So I threw up a sample crossdomain policy file looking like this: (for those of you that don't know what a crossdomain.xml policy file is, its a policy XML file that allows certain domains to use your swfs from the list that you type in)

<cross-domain-policy>
<allow-access-from domain="*"/>
</cross-domain-policy>

What that is doing is allowing any access from any domain, such as my localhost server, and now the code is working, loading things from the hosted server correctly. What a bother! But lesson learned,

by admin

Creating an RSS Feed (Really Simple Syndication)

May 5, 2010 in Coding by admin

RSS feeds is a way for websites to provide listings of the site's content.

RSS feeds are just XML files that already have established tags, they begin with a rss root element, witha  mandatory attribute called "version".  So, an RSS document starts with:

<?xml version="1.0"?>

<rss version="2.0">

<channel>

<title>Name of the RSS feed</title>

<description>Description of the RSS feed</description>

<link>Link to the Web site</link>

Those 3 elements are required within channel, there are lots of optional ones such as language, copyright, managingEditor(email address), webMaster, etc.  Formal specs are talked about at http://www.rssboard.org/rss-specification.

You can use a combination of PHP and Mysql to pump out the data to those xml tags needed (explained on one of the articles in this site).  Afterwards, check your feed at http://feedvalidator.org/ to validate if it is a correct RSS feed.  There is another RSS format offshoot called Atom.  Atom is an open standard unlike RSS.  Many of the largest sites still use RSS, and I recommend using RSS to display a feed from your website.

by admin

PHP simple OOP tutorial

May 2, 2010 in Beginner, Coding, PHP by admin

Some simple OOP for PHP:

Instantiation, a lot of methods in PHP are accessed using $instance -> methodName();. If you want to access a method inside the same class, you can substitute the instance variable and use $this. $this->helloWorld();, or you can use the Scope Resolution Operator to access methods and properties, instead of using $this, you would actually use the actual Class name.
Speak::helloWorld(); .. it would make the code easier to read.

PHP allows a class script to handle a bunch of classes in one file.  Do not put too many classes in one file or it will result in bloated up code and harder to manage, but will make it easier to distribute.

Here's your usual code example:

<?php

class Animals
{
	function Animal()
	{
	}
	public function speak($word)
	{
		print $word;
	}
}

class Dog extends Animals
{
	function Dog($word)
	{
		$this->speak($word);
	}
}

class Poodle extends Dog
{
	function Poodle($bark)
	{
		Poodle::speak($bark); // using Scope Resolution Operator
	}
}

// create a new Dog

$dog = new Dog("Hello.. Woof!");
echo '\n';
$pooDiddy = new Poodle("I am p00Diddy!");
?>

Notice when you have several classes the Scope Resolution Operator will def. come in handy.

by admin

Java Client Server Programming : pt 2 Concurrent servers

March 28, 2010 in Coding by admin

Coninuing off of part 1:

What is a concurrent server?

A server that can handle multiple client requests at the same time, makes multiple copies of itself.

Java threads can be used:  Every time a client establishes a connection with the server, the accept() call with return.  At this time a new thread is created to handle the client connection.  The main thread will go back and wait for the next connection.

Java language supports this thread manipulation, a thread is called a lighted process, the overhead of handling a thread is less processor intensive.

import java.io.*;
import java.net.*;
class ThreadHandler extends Thread
{
Socket newsock;
int n;
ThreadHandler(Socket s, int v)// serves a purpose of initializing the variables
{
newsock = s;
n = v;
}
public void run()
{
try
{
DataInputStream inp = new DataInputStream(newsock.getInputStream());
PrintStream outp = new PrintStream(newsock.getOutputStream());
outp.println("Hello :: enter QUIT to exit");
boolean more_data = true;

while (more_data)
{
String line = inp.readLine();
if(line == null) more_data = false;
else
{
outp.println("From server: " + line + "\n");
if(line.trim() equals("QUIT"))
more_data = false;
}
}
newsock.close();
}
catch(Exception e)
{ System.out.println("IO error " + e); }
}
}

class ConcurrentServer
{
public static void main(String args[])
{
int nreq = 1;
try
{
ServerSocket sock = new ServerSocket(7500);
for (;;) // infinite loop
{
Socket newsock = sock.accept();
System.out.println("Creating thread...");
Thread t = new ThreadHandler(newsock, nreq);
t.start();
nreq ++;
}
}
catch(Exception e)
{ System.out.println("IOerror " + e); }
}
}

Connectionless Servers:

The examples shown so far are based on connection-oriented transfers.  Provides reliable, bidirectional, point-to-point stream based connections between two hosts.  Based on the TCP Protocol.

Java also supports connectionless transfers using datagrams, based on the UDP Protocol.

May be used in situations where optimal performance is required, and the overhead of explicit data verification is justified.

Java implements datagrams on top of the UDP protocol using 2 clases.  The DatagramPacket class acts as the data container.  The DatagramSocket class is the means for sending and receiving datagrams.

Datagram packets can be created using one of two constructors, with prototypes:

DatagramPacket (byte buf[], int size);

DatagramPacket (byte buf[], int size, inetAddr addr, int port);

The first form is used to receive data, while the second form is used to send data.

Connectionless Server example:

Both the client and the server are combined into the same program.  The server program must be invoked as :

java DatagramDemo server

The client program must be invoked like so:

java DatagramDemo client

by admin

Client Server Programming in Java Pt 1 : Iterative server

March 24, 2010 in Coding, Concepts, Java by admin

These are some notes I was writing while viewing an amazing youtube video series from IIT Khanpur: Client Server Programming in Java Lesson # 30.  I thought I should share it with you for those who do not have an hour to watch the entire lecture:

Recap on client/server process: Remember, a client and a server: A service is providing services to entities that are called clients, requesting the service, may be run on different machines, servers wait for requests from clients.  Iterative servers know how much time between a request, & can handle the service itself, because it knows how long it would be pre-occupied with a request, one client at a time (server is busy), other clients have to wait. In concurrent servers you cannot predict the time to handle a request, it will create another process, and thee server itself will go back and wait.  For example, if there are 100 concurrent client requests, it can provide 100 different copies of the server catering to a client request in a dedicated fashion, no sharing or making other clients wait.  In a typical secnario, the server initializes and goes in a sleep state waiting for a client request.

A client process starts, either on same machine or other, and sends request to the server.  When the server process has finished, it will go back to sleep waiting for the next request.

Using TCP or UDP?

Before start of communication, a connection has to be established between the two hosts.  If you want protocol itself should handle reliability, flow control, guaranteed order of delivery of packets, then use TCP.  But if you have some app where if some packets are lost, you dont care, you want to provide all these services that TCP provides normally, you want to provide them in your application layer, then possibly you can use UDP, because in general UDP is faster, it will try to deliver packets as fast as the network can, it will use best parts of network.

5 components in a connection: Protocol used, Source IP address, Source port number, Dest. IP address, Dest. port number.

What is a Socket?

A socket is a term which was initially coined by the BSD (Berkeley Software Distr.) method for achieving inte-process communication (IPC).

It is used to allow one process to speak to another on the same or diff machine.  Good analogy: In a telephone conversation (you, the client), you are speaking and the other person (server) is listening, then will respond.

Using a socket is convenient because once you have opened the socket by speciying all the relevant info, you can treat the network connection the same way you are reading or writing a file, the same way you can read or write to a socket.  Socket is an abstraction you can use at the "transport" layer level, to make developing your tasks similar.

The basic idea when two processes located on two machines communicate with each other, we define association and socket, association: Protocol, Local IP address, Local port number, Remote IP Address, Remote Port Number.  Socket: also called "half-association" as a 3-tuple, Protocol , local IP address, local port number & the other side, the protocol, remote IP address, remote port number.

With the summary of what sockets are, lets get into Networking Programming with Java.

Networking Programming with Java : Sockets

In Java & C, as well as other programming languages, the way we write network programs is similar to how we access and read files.

Real programs have to access external data to accomplish their goals, which Java provides a number of ways for accessing external data.  Java provides a number of libraries and classes to facilitate accessing data.  It's handled in a very uniform way, does not make the distinction whether we are reading from a file, reading from a keyword, or reading from a socket.

Important: An object from which we can read a sequence of bytes is called an input stream (example, a file, keyboard, Scanner, a network socket).  An object to which we can write a sequence of bytes is called an output stream (example, the scren, file, network socket, etc).  Whenever developing a network app in Java, we are actually concerned with I/O streams and how to handle them.

Input and output streams are implemented in Java as part of the abstract classes InputStream and OutputStream .  Java provides a large number of concrete subclasses of InputStream and OutputStream to handle a wide variety of input-output option.  InputStream and OutputStream are generic classes for inputs and outputs of bytes, there can be separate subclasses for console i/o, networks, files, etc.

Using DataInputStream

Many applications need to read in an entire line of text at a time.

DataInputStream class and its readLine() method can be used (readLine() can read one line of text from some input source at a time, it will read the characters up to the end of the end line character, when its written back it depends on the way you store it, whether you actually store the end line character or not.

The readLine() method reads in a line of ASCII text & converts it to a Unicode string (16-bit unicode characters).

The following example shows how we can read a line of text from a given file:

DataInputStream inp = new DataInputStream (new FileInputStream("student.dat"));

String line = inp.readLine();

We create a new object of DataInputStream of variable inp, we then tell it the kind of Input Stream inside with FileInputStream.  FileInputStream is a subclass of InputStream, and takes a parameter of the name of the file.  It assumes the file you are opening, will be opened for input and you can start reading the characters from there, you can use FileInputStream or FileOutputStream, as input/output.

The java.net package uses networking.  It supports the TCP and UDP protocol families.

An example is shown next:  Connecting to a specified host over a specified port, and printing out whatever is returned.  There are two things to remember when connecting to a server:  The IP address of the server and the port number which the particular processes on the server needs to be contacted.  After the connection is established, the server will be responding back with some string and it will be displayed on your screen.

In the following example, the socket class is to be used by the client program because when the client program starts, it should start by trying to connect to the server.  All networking code should be encased in a try.. catch block, & most of the network-related methods throw IOException whenever some errors occur.

import java.io.*;
import java.net.*;
class ConnectDemo
{
	public static void main(String args[])
	{
		try
		{
			Socket s = new Socket("10.5.18.213", 225);
			DataInputStream inp = new DataInputStream(s.getInputStream());
			boolean more_data = true;
			System.out.println("Established connection");
			while (more_data)
			{
				String line = inp.readLine();

				// if line == null means no more text to come
				if (line == null) more_data = false;
				else System.out.println(line);
			}
		}
		catch (IOException e)
		{
			System.out.println("IOerror " + e) ;
		}
	}
}

Implementing Servers

We will now show an implementation of a server program in Java, when a client program connects to this server, it sends a welcome message and echoes client input one line at a time.  When you are writing the program and sequencing, there will be an asymmetric relationship, the coding is a bit different.

In this server, we are creating a ServerSocket object a different class.  We do not need to specify an IP address, because we are not connecting to other servers, a single parameter (7500 here) , is the port number it should be continuously listening to.  sock.accept() is the function call or method that makes the server wait for the client request to come, otherwise blocked.  It will move on to the next line only after the client request come, a newsocket descripter will contain detailed information about the client request at newsock, and the server creates a new input stream.  Then we will echo it to the screen with PrintStream with get the newsock.getOutputStream().

import java.io.*;
import java.net.*;
public class SimpleServer // If this were looping, example of an iterative server
{
	public static void main(String args[])
	{
		try
		{
			ServerSocket sock = new ServerSocket(7500);
			Socket newsock = sock.accept();
			DataInputStream inp = new DataInputStream(newsock.getInputStream());
			// will take in input from client?

			PrintStream outp = new PrintStream(newsock.getOutputStream());
			outp.println("Hello :: enter QUIT to exit");
			// client will receive outp on the other side.

			boolean more_data = true;
			while (more_data)
			{
				String line = inp.readLine();
				if (line == null) more_data = false;
				else
				{
					outp.println("From server: " + line + "\n");
					if (line.trim().equals("QUIT"))
						more_data = false;
				}
			}
			newsock.close();
		}
		catch (Exception e)
		{ System.out.println("IO error " + e);	}
	}
}

Some points:

Once accept() call returns a Socket object newsock, the getInputStream() and getOutputStream() methods are used to get an input stream and an output stream respectively from that socket.

Everything the server program sends to the output stream will become the input of the client program.  Outputs of the client program become the input stream of the server.

Part 2: Concurrent Server