Native UML Module for NetBeans

UPDATE: There is a more recent post regarding the Native UML module for NetBeans here.

I have been a long time user of NetBeans IDE. I really like the simplicity and how it is almost an all-purpose IDE for virtually any language you can think of.

However, I was horrified recently when I upgraded to version 6.8, to discover that the UML module was gone, and instead NetBeans insisting I use a third-party UML generator.  So I tried it, and hated it immediately.  I considered rolling back to an earlier version, but first I thought I would try a little voodoo.

I noticed that version 6.9 was released and so I downloaded it, and installed as per normal.  I then found this page (the 6.9 release candidate zip download page) which listed a file called ‘netbeans-6.9-201005312001-ml-uml.zip’.  Ah ha.  Since I am on OSX, I opened the package contents up from Applications, unzipped the uml.zip file and dropped the new UML directory into the installation directory.  I started up NetBeans and voila:

I tested the new project, and it worked like a treat (some people who tried various other hacks reported that even though the project appeared, there was issues saving/opening them).

I hope this works for you too, and of course make sure you backup any existing projects – dont come crying to me if you destroy your work trying to implement this!

WebGAC Takes the Pain Out of .Net Dependencies

My good friend Paul Jones, has released a great tool called WebGAC to github.  WebGAC is a great way to manage .net assemblies and adding them to .Net projects from a centralised repository of binaries.  As someone who has used this tool on literally dozens of projects for nearly 2 years now, Its a must have tool for all Visual Studio developers.

Managing binary dependencies in .NET can be a complicated task. For small projects, checking the dependencies into source control tends to work just fine. So does requesting that all developers have various binaries available in their GAC. Grow much bigger, or add more projects, and managing that starts to get very difficult. The Java world has had a solution to this problem for a long time, in the form of Maven and Ivy. Remote servers store the binaries, and the build tool automatically downloads them on demand.

WebGAC adds the core of this functionality to .NET, but without requiring you to switch build tools, or maintain a separate configuration file. Dependencies are specified just the same way as normal, but if you don’t have them when building your project, WebGAC will fetch them for you automatically.

WebGAC is available at http://github.com/paulj/webgac. Browse over there for more information and installation instructions, or continue reading here for more details.

Solve uninitialized constant ApplicationController in Rails 2.3

So I am casually writing my Ruby on Rails application, like I have a million times before on the newest version of Rails (which at time of writing, was version 2.3).  So I open up an blank project with some code I use in all my Rails apps, and copy over the relevant files, and replace the application_crontroller.rb with application.rb.

But as it turns out, there were some major changes with 2.3, not the least being that the application controller is no longer called application.rb Now it’s referred to as application_controller.rb.

So it’s easy to fix, just rename the file or, it you’re into scripty goodness, run:

rake rails:update

Be sure to update your server stack before deploying. Obviously if you rename the file to get it working on Rails 2.3 and upload to a Rails 2.2 server you’ll be in trouble. Don’t forget that Rails 2.3 also requires a new version of Phusion Passenger!

Text Rotation with CSS

Thankfully, many of the popular browsers of today support the ability to rotate HTML elements. Even better? Wed can make it work in Internet Explorer (back to version 5.5 even).  For Webkit and Firefox (as of 3.5), you can take advantage of the proposed transform property to handle the rotation. Each browser requires its property prefix for now.

-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);

In order to perform a transformation, the element has to be set to display:block. In this case, just add the declaration to the span that you want to rotate.

When it comes to effects in Internet Explorer, there is a surprising amount of power (and untapped at that, I’d say) in using filters. Although misleading, there is a filter called BasicImage that offers up the ability to rotate any element that has layout.

filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);

The rotation property of the BasicImage filter can accept one of four values: 0, 1, 2, or 3 which will rotate the element 0, 90, 180 or 270 degress respectively.

Form Select Helper in Ruby on Rails

It’s crazy how little documentation there is on using selects (drop down lists) inside form-helpers in Rails.  So, it can get quite confusing when it comes to using the different select helpers; select, select_tag and collection_select.

In order to address this inadequate documentation and examples, I thought I would post here, some of the differnces between them with some examples so you can choose for yourself, the best one to use.

The selection box has some key parts, the name, which is required, and used by the browser when submitting the <select> choices to the server. The option tags, each of which are made up from a “value” and “text” pair, the “value” to identify the select item in the server, and the “text” which will be displayed to the screen.

There are three different select form helpers in ruby on rails, “Select”, “select_tag” and “collection_select”. Let’s compare them.

 

select(object, method, choices, options = {}, html_options = {})
Defined in ActionView::Helpers::FormOptionsHelper

 

<%= select( "payment", "id", { "Male" => "1", "Female" => "2"}) %>

Select can be used in conjunction with a model object as seen in this example, an instance variable is passed into choices, but is being converted into an array of arrays.

<%= f.select :gender_id, @genders.map {|r| [r.name,r.id] } %>

Use select_tag when you require a drop-down selection box populated with data not sourced from a database, and are happy to hard code the default selected option tag. Select_tag should also be used when you want to process your form as a GET, rather than a POST.

<%= select_tag "payment", options_for_select([ "Male", "Female" ], "Male") %>

or

<%= select_tag "payment", options_for_select(%w{ Male Female }) %>

You can also do multi-select boxes:

<%= select_tag 'payment[]', options_for_select(@genders),
  :multiple => true, :size => 3 %>

(where the controller defines @genders as a hash of values).

In this example the gender methods are being added to the select box via a model object, notice how we use the option, :prompt to add an additional option tag to the select box, which will be selected by default. Note that if @object.method matches one of the option tags, this will be selected by default, and :prompt wont appear in the list.

<%= collection_select(:gender, :id, @genders, :id, :name,
  options ={:prompt => "-Select a gender"}, :class =>"gender") %>

In sum:

Use select when you require a basic drop-down selection box populated with data not sourced from a database.

  • The object is the name of an instance variable. This is typically a model object (singular name of the table whose data your displaying, or in other words, the table record).
  • The method is the attribute of that instance variable. This is typically a field/column of the table whose data your displaying (really an ActiveRecord method).
  • Together the object and method specify the name of the select statement in the generated html choices can be any enumerable object e.g arrays and hashes and results of database queries, and contains the option tags for the select box.
  • The optional options argument takes various “options” some of which are listed below in the examples.
  • The optional html_options argument allows css to be used for styling the select box.
  • If one of the option tags in choices matches @object.method, that option tag will be selected.

Use collection_select when you require a drop-down selection box, whose source is a model/object

  • The object is the singular name of the table whose data your displaying (the table record).
  • The method is the field/column of the the relevant data (really an ActiveRecord method).
  • Together the object and method specify the name of the select statement in the generated html collection takes the option tags for the select box, this can be a hash or array.
  • The value_method is the field/column to use for the value of the option tags in your html.
  • The text_method is the field/column to use for the visible text of the option tags in your html.
  • The optional options argument takes various “options” some of which are listed below in the examples.
  • The optional html_options argument allows css to be used for styling the select box.
  • If one of the option tags in collection matches @object.method, that option tag will be selected.

Some of the content for this post came from here – check it out for a more detailed explaination of the differences between the 3 select form helpers.

Extracting Specific Date-time Components in Postgres

When programming, sometimes it’s useful to extract various time components from a Date-time field in SQL queries.  For example, you might want to filter the date field by, hour, or year (or both).  Fortunately, Postgres has a easy way to pull this data out within the query itself:

SELECT EXTRACT(hour FROM a_datetime_field) FROM a_table;

If the field was the value ‘4/5/2009 13:09:00’ then that above query would return “13” in the select.

In a stranger, practical example, I was moving a database from one server to another and for some unknown reason, all the dates in a table were fudged so that instead of being the year 2009, it was 142009, and the seconds were also stuffed up – the result being that any queries I ran against the table threw ADO.NET exceptions because the dates couldn’t be parsed properly.  I needed to run a query like this one to set things right again:

update atable
  set datetimeadded = cast( '2009-' || EXTRACT(month FROM datetimeadded) || '-' ||
    EXTRACT(day FROM datetimeadded) || ' ' || EXTRACT(hour FROM datetimeadded) || ':' ||
    EXTRACT(minute FROM datetimeadded) as timestamp),
  datetimeupdated =  cast('2009-' || EXTRACT(month FROM datetimeupdated) || '-' ||
    EXTRACT(day FROM datetimeupdated) || ' ' || EXTRACT(hour FROM datetimeupdated) || ':' ||
    EXTRACT(minute FROM datetimeupdated) as timestamp);

The casts are needed to get the update to cooperate, but basically this recreates the date time piece-by-piece based on the original date-time value.

Better way to get the Scheme, Host and Port from Uri Object in .Net

Recently I was working on a project where I needed to strip the scheme, host and port (if it wasn’t 80) from a Uri object. Obviously I could have used string concatenation to get the value I needed, but it just seemed so ghastly and inelegant. In frustration and annoyance that it wasn’t part of the standard Uri object definition, I asked a friend who gave me this little gem:

side effect of clomid

Uri uri = new Uri("http://localhost:6767/h/ello.php");
string url = new Uri(uri.AbsoluteUri).GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);

The string, ‘url’, will (in this example) hold the value “http://localhost:6767”. This works in .Net 2.0 and up, and with .Net 3.0, you could even create a static method extension to make it even easier.

Sometimes, Microsoft Gets it Right (The .NET Framework 4)

Parallel Programming are two words which are not nearly used enough by programmers today. I think this is partially due to the fact that most developers are answerable to management types who simply “want to get the job done”. It’s also highly susceptible to deadlocks, race conditions and other problems, which are somewhat more avoidable in traditional single-threaded-apartment model applications. The problem is, that we’ve reached a precipice in CPU architecture where CPUs are scaling out instead of up. In other words, instead of simply working harder and faster, they’re working smarter – executing many simultaneous operations.

The only problem with this is that applications need to be programmed to capitalize on this architecture – and making Multi-threaded applications easier is obviously on Microsoft’s mind with the announcements of features in the upcoming The .NET Framework 4.0.

One of the main the main features I am looking forward to is the Parallel class to easily thread simple loops. This Parallel class represents a significant advancement in simplistically managing loops.  The .Net 4.0 team assures us that “for many common scenarios, it just works, resulting in terrific speedups”.  A similar technique can be used to write parallel loops over iteration spaces of non-integral objects.

Parallel.For(0, N, i=>
  {
    DoWork(i);
  });

There are also overhauls to the ThreadPool class (which was in dire need of serious attention) and the inclusion of “Tasks” – simple generic types which assist developers in creating native IAsyncResult objects: this means that Task can be used as the core of a Begin/End implementation.  They’ve also really thought about these improvments, with easy and clear ways to cancel parallel operations, as well as a number of great ways to handle Exceptions within parallel blocks.

There are of course other advantages to the 4.0 Framework, but it’s the big emphasis on easing MTA (Multi-Threaded Apartment) model application development that’s got me excited.

Enjoy!

Configuring a Basic Reverse Proxy in Squid on Windows (Website Accelerator)

I do a lot of web development in Visual Studio 2005 (and 2008) on a Vista workstation joined to a domain.  Up until recently I’ve been working on a very large set of RESTful APIs written in a special library for creating RESTful APIs using metaprogramming.  Its a great in-house library, but its not compatible with IIS7 – and debugging the PHP requests through the production compiled staging server (aka trawling through many many large log files) is become tedious and difficult.

I thought, wouldnt it be useful if I could debug the APIs if the guys could use the APIs hosted on my machine by the ASP.NET Development Webserver.  But alas, remote connections are not allowed to this light-weight web server making this impossible.

Or is it?

I have been wanting to learn more about reverse proxies as I know from buzz in the industry that they can be god sends.  I thought, that’s what I need!  A reverse proxy to forward external web requests into “internal requests” to trick the ASP.NET Development Webserver that the request was local, when in fact it isn’t.  After playing with a number of options, it turned out that what I had initially avoided for fear of it being too difficult was actually the best and easiest.  Squid!  For those not familiar with the concept of reverse proxies, I thought I’d paste this snippet from the Squid wiki:

What is the Reverse Proxy (httpd-accelerator) mode?

Occasionally people have trouble understanding accelerators and proxy caches, usually resulting from mixed up interpretations of “incoming” and “outgoing” data. I think in terms of requests (i.e., an outgoing request is from the local site out to the big bad Internet). The data received in reply is incoming, of course. Others think in the opposite sense of “a request for incoming data”.

An accelerator caches incoming requests for outgoing data (i.e., that which you publish to the world). It takes load away from your HTTP server and internal network. You move the server away from port 80 (or whatever your published port is), and substitute the accelerator, which then pulls the HTTP data from the “real” HTTP server (only the accelerator needs to know where the real server is). The outside world sees no difference (apart from an increase in speed, with luck).

Quite apart from taking the load of a site’s normal web server, accelerators can also sit outside firewalls or other network bottlenecks and talk to HTTP servers inside, reducing traffic across the bottleneck and simplifying the configuration. Two or more accelerators communicating via ICP can increase the speed and resilience of a web service to any single failure.

The Squid redirector can make one accelerator act as a single front-end for multiple servers. If you need to move parts of your filesystem from one server to another, or if separately administered HTTP servers should logically appear under a single URL hierarchy, the accelerator makes the right thing happen.

Start by obtaining a binary release of Squid. I’ll be using the latest stable release, standard 2.7.STABLE4.  Squid does not require installation as such, simply unzip it where you wish. To make it simple, I’ll install Squid directly in C:\squid as the standard Squid configuration expects it to be installed here – it’s easy to change though!

We’ll start by installing Squid as a service, before doing the actual configuration. Open a command prompt and go to C:\squid\sbin. Now run “squid -i -n Squid”. This will install Squid as a service under the name “Squid”.

C:\squid\sbin>squid -i 0n Squid
Registry stored HKLM\SOFTWARE\GNU\Squid\2.6\Squid\ConfigFile value c:/squid/etc/
squid.conf
Squid Cache version 2.7.STABLE6 for i686-pc-winnt
installed successfully as Squid Windows System Service.
To run, start it from the Services Applet of Control Panel.
Don't forget to edit squid.conf before starting it.

Before we start Squid, we have to configure it. Go to C:\squid\etc and make a copy of squid.conf.default and call it squid.conf. Do the same for mime.conf.default (we won’t edit this one, but it’s needed). There are hundreds of configuration options, all very well documented. Now, I won’t go over all the options, so simply by-pass the entire contents of the squid.conf file, we’ll add only the configuration options that we need at the bottom.

http_port 8880 accel defaultsite=your.dns.address

cache_peer localhost parent 9977 0 no-query originserver name=myAccel

acl our_sites dstdomain your.dns.address
http_access allow our_sites
cache_peer_access myAccel allow our_sites
cache_peer_access myAccel deny all

This particular reverse proxy is going to co-exist on the same machine that is hosting the website, but for better load balancing, you should make the first line http_port 80, and the cache_peer line, change localhost to the ip of the webserver and parent 9977 to 80 as well.  This way, when the Squid server gets a request on port 80 (the default HTTP port) it will properly reverse-proxy to the default webserver port on the web server machine.  The other options are handy to know, so have a read, but so long as your firewall has the relevant ports open, the config file as it stands is all you need at a minimum to get things going.  Another handy thing to know (as your site grows) is that the reverse-proxy capabilities of Squid are quite advanced.  To load balance requests among a set of backend servers allow requests to be forwarded to more than one cache_peer, and use one of the load balancing options in the cache_peer lines. I.e. the round-robin option:

cache_peer ip.of.server1 parent 80 0 no-query originserver round-robin
cache_peer ip.of.server2 parent 80 0 no-query originserver round-robin

This is very asy to spread load of your websites and services.  Wikimedia is quoted a while ago as saying that their front-end squid servers have a 75% hit rate, effectively quadrupling the load capacity of their Apache servers.  No doubt their configuration is quite different to this example, but it gives you an idea of just how much benefit a Squid based reverse proxy can be.

Before you run off and start the Squid service, first run “squid -z” which will report any configuration errors in your conf file.  If all went good, it should look something like:

C:\squid\sbin>squid -z
2009/03/18 11:35:06| Creating Swap Directories

Since its working great, just execute “net start Squid” and:

C:\squid\sbin>net start Squid
The Squid service is starting.
The Squid service was started successfully.

BAM! Your fung foo is strong.  Simply test the external url and it should forward the request and response back for you.

I know this has worked wonders for me, I hope you have the same positive experience.

.Net Remoting Error – Win32Exception: The logon attempt failed

Quite a while ago, in the absence of any alternatives, we built a remote deployment utility so we could push updates to our staging and production servers without manual intervention.

Recently however, while deploying the latest code for an internal project to a new production server, the .Net 2.0 automatic deployment  I had created threw the following, rather unfriendly error:

Exception Details: System.ComponentModel.Win32Exception: The logon attempt failed
[Win32Exception (0x80004005): The logon attempt failed]
[InvalidCredentialException: The server has rejected the client credentials.]

In order to protect the server from attack we have a system service which we communicate to using .Net remoting, which requires authentication.

Apparently the bug occurred, because I created the user account which we authenticate against on the new server, after I have installed the system service.

I uninstalled the system service, reinstalled it and it magically worked like it should.