Googolflex!!
  • Home
  • About
  • Contracting

Recent Posts

  • Sprint’s new “Simply ‘Almost’ Everything®” Plans
  • CSS Changes in Flex 4
  • Dotted Underline LinkButton (Flex)

About The Author : jwd

This is John Dusbabek's tech blog. John is a software engineer and Flex developer in Provo, UT, where he lives with his lovely wife and four sons.

Recent Comments

  • Nikos on Flex: Binding to an Interface
  • Iain Hosking on Apache mod_proxy_balancer: No Protocol handler was valid

Archive for July, 2009

Jul
28

Single Threaded Server in C++

Posted by: jwd | Comments (0)

The versatility of the client-server architecture has always fascinated me. You can write a server once, and plug in whatever protocol you happen to be implementing. The same goes for clients.

I’m going to present here a simple server I implemented in C++. I guess if I had to give a name to the protocol I implemented, I would call it the “Echo Protocol”. There’s only one part of the code I’m going to comment on specifically in this article, and that is the process() method.

There are ample sources on the web and otherwise explaining the use of the socket, bind, listen, and accept methods – which are the basis for socket communication in C and C++.

One book I would recommend for someone serious about network programming (though it hardly needs my recommendation) is UNIX Network Programming, Third Edition by W. Richard Stevens, Bill Fenner and Andrew Rudoff. If you do read this book, be aware that they use wrapper functions throughout the book (i.e. Bind(), Listen()) to add a measure of error checking (see section 1.4 for their explanation). The wrapper functions have the same signature as the corresponding BSD functions, just make them lowercase.

Here is the code for my process() method:

void process() {
	// Read the request
	//------------------
	string request = "";

	while(! isRequestDone(request) ) {
		// Read from the client
		//-----------------------------
		char buf;
		bzero(&buf, 1);
		nread = recv(client_fd, &buf, 1, 0);
		request += buf;

		if (nread < 0) {
			if (errno == EINTR)
				continue;// Continue reading
			else
				break;	// No more
		}
		else if (nread == 0) {
			break;		// Nothing left to read
		}
	}

	// Do something with the request
	//------------------------------

	// Send the response:
	//------------------------------
	string response = request;

	int num_b = response.length();
	for (int i = 0; i < num_b; i++) {
		char cur = response[i];
		send(client_fd, &cur, 1, 0);
	}

	// Close the connection here
	close(client_fd);
}

This method is where you would implement the protocol (be it HTTP, or what have you). A crucial step in any interesting protocol would be parsing out the request (something you might do where I have the comment “Do something with the request”) and using that information to construct the response. Sometimes the request parsing is handled while the request is being received. I wanted to keep this example simple (so you’ll also notice I’m receiving and sending only 1 byte at a time… which involves a lot of overhead and I wouldn’t recommend for high load servers sending and receiving larger messages). You could increase the number being read at a time by increasing the size of buf and/or cur.

You can download the complete code for this server here: C++ single threaded server

You can compile this code on Linux with the following command:

g++ -Wall  -o bin/server single_threaded_server.cpp

Linux and Windows both use BSD sockets, but I haven’t tried compiling this code on Windows without using g++ on cygwin. You’re on your own there.

This post is part of a series, next I’m going to post a simple C++ client. Then I’m going to present a threaded server architecture, and finally I’m going to post a Flex chat client and implement a simple chat protocol. Stay tuned.

Categories : Uncategorized
Comments (0)
Jul
27

NetBeans 6.7 Impressions

Posted by: jwd | Comments (0)

I haven’t had any real need to use Java over the past 12 months or so (been working mostly with ColdFusion and PHP backends), which also means I haven’t had any real need to upgrade my Java IDE from NetBeans 6.1 either.

I needed to whip up a little Java the other day, which eventually lead me to the NetBeans site where I decided to upgrade to version 6.7. The work I was doing was pretty basic, so I didn’t have the opportunity to delve into any of the more advanced features. So I can’t comment on what’s new in the current version. What I really want to say is that I was pleasantly surprised by how quickly it loaded. I installed the full version: about 10 seconds to start up.

This is compared to over 1 minute in April 2008, when I was running the full version; and 25 seconds when I installed only the Java IDE in March 2009.

Great job, guys.

Categories : Java
Comments (0)
Jul
25

Detecting Changes in an Object

Posted by: jwd | Comments (0)

One of the projects I’m working on right now requires me to detect when changes to an object have occurred, so as to enable or disable some “OK”, “Apply” and “Cancel” buttons in the appropriate context.  For the longest time I’ve been thinking I was going to implement this with some sort of data binding, but as it’s distilled on my mind over the past few weeks I’ve decided that wasn’t the right approach.  Here are a few of the requirments/factors that played into that decision:

Background info: the gist of this app is that there’s a datagrid whose items can be loaded into a dialog for editing.

  1. The changes don’t affect the actual object in the model or database being edited until “Apply” or “OK” is pressed (i.e. they can always cancel out of the operation, regardless of any changes)
  2. If a user edits a field, I want that to register as a change.  If they change the field back to what it was, I don’t want that registered as another change, it needs to be as if it had never been changed (i.e. “OK” is not enabled).  This is why I ruled out a Binding approach.
  3. The objects being compared are pretty complex objects.  I didn’t want to have to go and manually compare each property, the properties of composed objects, and the properties of objects nested in collections.  The time to implement this, and the amount of time it would take to compare the object with its sentinel after each edit seemed to rule this option out.

I became pretty familiar with ByteArrays last year during a computer security class (I implemented my AES, RSA, etc. labs using ActionScript) and so I got the idea of serializing these objects to a ByteArray, and then comparing them.  After I came up with the idea, I googled it and realize I’m hardly the first to come up with it, but I’m still going to share it.

First, I built a method to convert an object to a ByteArray, convertToBytes:

public static function convertToBytes(m : Object) : ByteArray {
   var ba : ByteArray = new ByteArray();
   ba.writeObject(m);

   return ba;
}

The ByteArray class has lots of useful writeXXX methods depending on what you’re doing. In this case we use writeObject() which serializes an object to AMF, and writes it to the ByteArray.

Second, I built a method that compares two ByteArrays. There are several ways that this can be accomplished, I chose straight iteration. If someone knows a faster way, please let me know. The faster the better. Here it is:

public static function isByteArrayDifferent(base : ByteArray, revision : ByteArray) : Boolean {
   if (base.length != revision.length)
      return true;
   for (var i : int = 0; i < base.length; i++) {
      if (base[i] != revision[i])
         return true;
   }
   return false;
}

Obviously, if they are different lengths they’re not the same. I like that the method short circuits if a difference is detected, which will be the most common case.

Finally, I wrote the method that accepts the two objects, and returns a Boolean indicating whether a change has been detected. It’s simple, as the preceding two methods do all of the work.

public static function hasObjectChanged(a1 : Object, a2 : Object) : Boolean {
   return isByteArrayDifferent( convertToBytes(a1), convertToBytes(a2) );
}

And it works pretty well. There are a few gotchas I will point out, fortunately none of them apply to my application specifically.

First, suppose your object has a collection with two objects, 1 and 2. The order matters when the objects are serialized. An object with 1,2 will serialize differently than the same object with 2,1. Depending on your application you may have to handle this case specially (if 2,1 is considered the same as 1,2).

Second, you can’t use this method to tell if two objects are the same instance in memory. There are other ways of doing that, this isn’t one of them.

ByteArrays are very useful and have loads of other applications (see the ObjectUtil.copy() method to see how to make copies of objects using ByteArrays. I’ll include a quick method I threw together to output the contents of a ByteArray (it’s very similar to isByteArrayDifferent(), in case anyone’s interested. I used it for debugging, but it can be easily modified to return the String instead of outputting it.

public static function outputBytes(label : String, block : ByteArray) : void {
   var s : String = "";
   for (var i : int = 0; i < block.length; i++) {
      s = s + uint(block[i]).toString(16) + " ";
   }
   trace (label + ": " + s);
   trace();
}
Categories : Actionscript, Design Patterns, Flex 3
Comments (0)
Jul
22

SyntaxHighlighter Evolved (for WordPress)

Posted by: jwd | Comments (5)

I just started using the “SyntaxHighlighter Evolved” plugin for WordPress.  I didn’t think I’d like it because straight copy-and-paste operations grab the line numbers too; but I’ve decided that I do like it. It has support for most of the languages I use, and a bunch that I don’t.  And depending on your skill level with regular expressions, it may or may not be easy to add support for other languages.

You can get the plugin here: http://wordpress.org/extend/plugins/syntaxhighlighter/

It uses Alex Gorbatchev’s SyntaxHighlighter JavaScript package.

Categories : Blogging, Languages
Comments (5)
Jul
21

Changing Default Minimum Height of ScrollThumb

Posted by: jwd | Comments (0)

The default minimum height of the scroll thumb is about 10 pixels, which my client felt was a little too small (their data sets usually run into the several-hundreds, which is enough to push it to the minimum at most resolutions). So I set about trying to fix the problem.

There was no style or property I could set on the VScrollBar to control this, so I went to the ScrollThumb. There was no global style I could set on the class to control this, and if I extended the ScrollThumb and manually set it, there was no way for me to easily tell my VScrollBar to use this version of the ScrollThumb.

Long story short, I had to change the framework code. I changed line 48, where explicitMinHeight was set, to something more agreeable for my client. I was pretty disappointed about this, because it has some unfortunate side effects (which I could probably correct if I had the time). Specifically, if there’s a scroll bar that can’t fit the newly resized ScrollThumb, it doesn’t show one at all. This seems most common in short TextAreas.

Categories : Actionscript, Architecture, Flex 2, Flex 3, Monkey Patching, Scalability
Comments (0)
Jul
21

Preventing User Dragging Panel Off Screen

Posted by: jwd | Comments (0)

My most recent monkey patch to the Flex framework code took place in the Panel class.  It is possible to drag a Panel completely off the screen, such that the user has no way of dragging it back should they release the mouse button.

Panel has a private handler private function systemManager_mouseMoveHandler (event:MouseEvent) : void that gets called before any mouse event handlers you might listen for should you extend Panel or try any other object oriented approach. There are also two private variables on the Panel class, regX and regY which store the location the mouse was pressed on the Panel’s title bar, and are set in the startDragging() method. (These numbers are useful for determining if the Panel is being dragged off screen as well as for determining where the top-left corner of the Panel is).

I decided to keep it simple and only prevent the user from dragging the Panel off the left or upper edges of the browser. (You can do the same for the bottom and right edges by performing similar calculations… but I didn’t.)

Here’s the code that does the checking (inside systemManager_mouseMoveHandler():

var sx : int = event.stageX;
var sy : int = event.stageY;

var nx : int = event.stageX - regX;
var ny : int = event.stageY - regY;

if (nx < 0 && ny < 0)
  move(0,0);

else if (nx < 0 && ny >= 0)
  move(0, sy-regY);

else if (nx >= 0 && ny < 0)
  move(sx-regX, 0);

else
  move(event.stageX - regX, event.stageY - regY);

Essentially the code detects if the top or left edge of the Panel is in the negative, and if so resets it to zero. There is a stopDragging() method that I originally tried to use in my code, but gave up, because I wanted the user to be able to continue dragging their mouse back onto the browser after they dragged it off.

Adding in the right and bottom will add several more permutations, so I’ve been thinking of more creative ways to handle this, but haven’t got it working the way I want yet. I’ll update this post when I do.

Categories : Actionscript, Architecture, Design, Flex 3
Comments (0)
Jul
14

Book Review: Learning Flex 3

Posted by: jwd | Comments (0)

I enjoyed reading Learning Flex 3, by Alaric Cole… which is saying something, because there aren’t very many “Flex for beginner”-type books I can stand to read these days.  Aside from being very easy to read as far as technical books go, here are a few things that really stood out:

First, the book is very well organized, and the content is good.  The breadth and depth of material covered is perfect for a beginning level.  He even goes over several different deployment scenarios toward the end.  Off the top of my head I don’t consider deployment as a “Flex-related topic”, but as I read through it I thought about how many times I’ve answered questions on this very topic to people just starting on the journey.  It was a nice touch.

Second, tutorial based approaches are very effective for beginners.  Maybe I shouldn’t speak for everyone, but when I first start learning a new language or framework, I find tutorials to be very helpful.  Once the developer has the confidence and basic understanding (that can be obtained through tutorials) then they can apply their own style and develop their skills further.  Learning Flex 3 reads almost like the Flex tutorials on steroids.  If you’ve done the tutorials on the Flex Builder 2 startup page (which is how I started out with Flex) then you’ll know what I mean.  Just picture how those build on each other, and then stuff in about 5 times as much information, and you’ve got this book.

Third, the syntax highlighting.  Anyone who has ever read a book full of code will appreciate how much easier the syntax highlighting is on your eyes, allowing you to focus on other things.  As a side note, the Deitel & Deitel books started becoming intolerable for me when they started rushing books to press without syntax highlighting… it was hard enough to get through those books with the code highlighting and color breakouts, but without them it was just torture.

Fourth, there are color diagrams.  Simon and Garfunkel are right.  Though I definitely wouldn’t base my decision to purchase this book on the basis of color pictures, it adds a very nice touch and makes the book easier to read than an identical book with only black and white diagrams.  I didn’t do the tutorials as I read the book, I wouldn’t recommend that to a pure beginner.  Even in color, reading the code and looking at the pictures is not the same as typing it out and running it.

I highly recommend Learning Flex 3 for beginners who want to get their feet wet with Flex.  I don’t recommend it to more advanced Flex developers, unless they just want to look at the color pictures.

Categories : Actionscript, Book Reviews, Flex 3, Languages
Comments (0)
Jul
12

Private Variables and Monkey Patching

Posted by: jwd | Comments (0)

I’ve been pretty busy the past two months finishing up a project for my client.  I may have mentioned it before, but their creative vision is pretty intense (especially considering this is an in-house app… in my limited experience I’ve never seen so many resources allocated toward getting the look and feel of an in-house app to be just right).

Anyway, I’ve had to monkey patch approximately 10 Flex framework classes (for various reasons) in order to realize their vision.  In each of these cases I’ve first tried to use inheritance or composition to achieve the desired functionality, mostly in terms of interaction.  And in each of these cases I was unable to do so, and had to resort to making changes directly in a framework class which I maintain in an mx.controls.etc, etc structure with the rest of my project.  I don’t think I need to point out the many evils that this exposes the project to, suffice it to say it’s not ideal.

I just wanted to make an observation as to why I was unable to use normal OOP techniques to achieve the desired functionality.  The most common reason I have been unable to extend classes to do what I need is because there are too many private variables being used in protected functions.  So if I need to tweak one line of a protected method, I can override it.  However, assuming I don’t want to call super.methodName(), there’s no way to recreate the lines that interact with the private variables.

This leaves me two alternatives: 1) monkey patch the file to make the variable protected, or 2) monkey patch the file and just make the change directly to the method.  I make that decision depending on whether I’m fixing a bug, or just adding functionality.  Either way, it’s still a pain in the butt; and will probably be a bigger pain down the road.

Categories : Actionscript, Architecture, Design, Flex 3, Frameworks, Scalability
Comments (0)

Search

Feedburner

Subscribe to

Get the latest updates delivered via email

Calendar

July 2009
M T W T F S S
« May   Aug »
 12345
6789101112
13141516171819
20212223242526
2728293031  

Archives

  • July 2010 (1)
  • June 2010 (2)
  • May 2010 (1)
  • February 2010 (11)
  • January 2010 (3)
  • December 2009 (5)
  • November 2009 (1)
  • August 2009 (8)
  • July 2009 (8)
  • May 2009 (4)
  • April 2009 (1)
  • March 2009 (6)
  • January 2009 (1)
  • November 2008 (4)
  • October 2008 (5)
  • September 2008 (1)
  • August 2008 (5)
  • July 2008 (1)
  • June 2008 (2)
  • May 2008 (8)
  • April 2008 (5)
  • March 2008 (2)
  • February 2008 (3)
  • January 2008 (1)
  • December 2007 (6)
  • November 2007 (9)
  • October 2007 (1)
  • September 2007 (2)

Categories

Tag Cloud

adobe apache Architecture book review C++ centos client server architecture Custom Components database Design error message fedora flash catalyst flex Flex 3 Flex 4 fms iis 6 Interaction Design load balancing master-master master-slave mod_proxy_balancer Monkey Patching MySQL no protocol p2p peer to peer Perl PHP Red5 regex replication self registration selinux Shell Scripting shortcut manager skins socket policy file sockets states stored procedures stratus tools workflow

Coworkers

  • Casey Jackman
  • Sean Murphy

Family

  • Emily & CJ
  • Family Blog
  • Gary Dusbabek

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

RSS FlexExamples

  • Styling the text selection format on a Spark TextArea control in Flex 4
  • Setting the scale mode on a Spark Image control in Flex Hero
  • Setting the fill mode on a Spark Image control in Flex Hero
  • Setting a bitmap image fill on a Spark Form container in Flex Hero
  • Setting a bitmap image fill on a Spark FormHeading control in Flex Hero

Spam Blocked

847 spam comments
blocked by
Akismet

Sponsored Links

JUICE Chat

BYU Adobe Users Group


Copyright © 2010 All Rights Reserved
Flexx Theme by iThemes
Powered by WordPress