# Smoky Cogs

Thoughts on programming, life and anything else that floats through my brain

Tag: Programming

## Drawing spirals in C#

Mar 2

Spirals are a relatively easy shape to draw, but in order to draw a good spiral we need a bit of simple trigonometry.

The basics of the spiral are the radius of a particular point from the origin, at a particular angle, and for the code below, the radius increases as the angle increases. The exact relation between angle and radius determines the type of spiral.

In the simplest case, the radius will increase linearly with the angle, thus

We can also use quadratic or cubic equations to define the realtionship

The most interesting spiral, however, is the exponential spiral, which is found in nature most famously in the nautilus shell.

Now that you can determine the relationship between radius and angle, it is a simple matter to draw the spiral.

Starting at the origin, with angle 0, we need to increment the angle by a certain amount – in the code below by 0.5 degrees per iteration – and then calculate the radius, and then using the radius and the angle, we are able to calculate the x and y coordinates of the point by using simple trigonometry, since sin(angle) = y/r and cos(angle) = x/r.

Now after finding the coordinates of the point, we simply need to draw a line segment from our previous point to the new point. The smaller the angle increment, the smoother the curve which is drawn will be, but it also means that more points need to be calculated to draw the same curve, which consumes more processing time.

One good way of speeding up the calcution of the curve, is to use a lookup table for the cos and sin values instead of calculating them with each iteration, but that is a topic for another post.

```      public void drawSpiral(double scale, double delta, double revolutions, int centreX, int centreY, SpiralType spiralType, int width, int height, Color color, Graphics g)
{
Pen p = new Pen(Color.Blue, 1);

double prevX = centreX;
double prevY = centreY;
double X = centreX;
double Y = centreY;
double theta = 0;

while (theta <= (revolutions * 360))
{
theta += delta;
if (spiralType == SpiralType.Linear)
{
}
{
radius = theta * theta * scale;
}
else if (spiralType == SpiralType.Cubic)
{
radius = theta * theta * theta * scale;
}
else if (spiralType == SpiralType.Exponential)
{
radius = (Math.Pow(theta / 180 * Math.PI, Math.E)) * scale;
}

prevX = X;
prevY = Y;
X = (radius * Math.Cos(theta / 180 * Math.PI)) + centreX;
Y = (radius * Math.Sin(theta / 180 * Math.PI)) + centreY;
g.DrawLine(p, (float)prevX, (float)prevY, (float)X, (float)Y);
}

}

public enum SpiralType
{
Linear,
Cubic,
Exponential
}
```

## My Experimentation with Android

Feb 5

Recently I decided to experiment a bit more with developing Android applications. I had played around with Android a rather long while ago, creating two rather simple apps – Dutch Public Holidays and Plasmatic, but decided to look at it again.

I have improved upon my two previous apps, making them much more useful, and created a third app, using webservices to look up animal and plant scientific names.

Thanks to the thousands of Android tutorials littering the web, it is not hard at all to get started in Android development, and the integrated Eclipse/Android SDK makes for a very pleasurable development environment.

Since there is nothing that can’t be found in other tutorials in the applications, I won’t list the code for the apps themselves, but you can download the source code for the apps from the links below.

Dutch Public Holidays
This was the first app I wrote, and is rather very simple in construction. It merely shows a list of public holidays for the Netherlands for a particular year.
InstallerSource

Plasmatic
I ported some code from my C# fractal library I had written a while back to Java to draw plasma fractals. The application generates a plasma fractal based on a set of preferences, and is able to save the generated images to a file on the mobile device.
InstallerSource

Scientific Name Search
This app makes use of a webservice provided by www.itis.gov to search for information such as the scientific name and taxonimic classification of plants and animals.
InstallerSource

## A simple city autocomplete field

Sep 10

I was playing around with some code recently, and came across a very easy way to create a city lookup field using jQuery’s UI components and a very useful webservice provided by Geonames.

How the autocomplete functionality in jQuery works, is by wrapping the functionality around a standard html text input field, populating a dropdown list of values from an ajax call to a webservice, in this case, the Geonames webservice.

When supplied with a partial city name, the GeoNames webservice returns back a list of information for cities matching the partial city name supplied, allowing you to display, and keep track of, the country, province, full city name, and a host of other info. Full documentation is provided on the GeoNames site.

```\$( "#city" ).autocomplete({
source: function( request, response ) {
\$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
//Display city name, state name, country name
response( \$.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
\$('#city').val(ui.item.value);
return false;
}
});
```

## Better protection for users passwords

Jun 13

Last week, as by know, no doubt, you have probably read, LinkedIn had a security breach, with 6.5 million passwords being stolen. It has caused a lot of people to argue back and forth that they didn’t implement good enough security measures and should have done things differently, such as using a salted SHA-1 hashing algorithm instead of an unsalted hash as they had used.

However, I found a really interesting interview with Thomas H Ptacek on the Krebson Security news site.

Ptacek maintains that no matter whether they had used salted or unsalted SHA-1 encryption, or even SHA-512 encryption, it would not have mattered. The problem lies not with how secure the hashing is, but rather how quickly the hash is calculated, making brute force attacks possible.

Ptacek goes on to explain how these cryptographic hashing techniques are designed to be as fast as possible, allowing many millions of attempts to crack the passwords in a reasonable amount of time, which is exactly what happened when the hashes of the LinkedIn passwords were stolen.

The solution that should have been using is password hashing. The key difference with password hashing is that it takes a lot longer – from milliseconds to a second or more – to hash the password (or any other value passed to it), which makes a brute force attack such as those that would work on a normal cryptographic hash virtually impossible. One common way of accomplishing this is to simply apply a cryptographic hash repeatedly, say a thousand times, on the value. With no increase in development cost, and with only a slight increase in server load for logging in users, it is possible to eliminate the threat of brute force attacks on password hashes.

So, why wasn’t it implemented this way in the first place then? Well, simply, most programmers do not know about it, myself included. The vast majority of programmers spend very little time analysing hashing techniques, relying instead on accepted practices to provide guidelines as to how to implement security.

As an example of this, 2 days ago, I wrote (and passed) the Microsoft Certified Technical Specialist module Accessing Data with .NET 4, which covers just about everything you need to know about manipulating data with .NET. There is a section in the module specifically covering how to protect passwords in a database, with the recommendations of the book being that you should use salted SHA-1 hashing, or if you want better security SHA-512. Nowhere in the book is any mention made of password hashing techniques such as discussed by Ptacek in the interview mentioned above.

Therefore, is it any wonder that most programmers are oblivious to the dangers when even official sources fail to mention the best way to protect your data, instead of methods that have time and again proven to be relatively easy to compromise.

## Turning the page in HTML5

Feb 10

In days gone by, if you wanted to imitate a book on a website, being able to browse content by flipping pages, you needed some Flash or some other extension to handle it.

Now, turn.js comes to the rescue.

With just a few lines of code and this open-source jQuery plugin, you can add a fully animated book feel to your site.

The only requirement to get it to work is an HTML5 compliant browser and let turn.js do the rest.

## Focus in jQuery

Jan 25

To focus on an element using jQuery is really easy, since all it takes is one function – .focus(). There are cases though were it is just a little bit trickier.

Let’s take the scenario where after entering a field, you need to validate it, and if the validation fails, you need to return focus to the field. You would expect the following code to do the job:

```\$(elem).blur(function(){
if (do some validation fails) {
\$(this).focus();
}
});
```

This code, logically, should work, and indeed it does in Internet Explorer, but Firefox stubbornly refuses to set the focus.

The problem is that the event is firing at the wrong time for Firefox, and therefore the focus event is being lost.

The solution for this is to delay the focusing by a small bit, which then yields a solution that works in all browsers

```\$(elem).blur(function(){
if (do some validation fails) {
var \$this = \$(this);
setTimeout(function () { \$this.focus(); }, 10);
}
});
```

## A new project in the works

Nov 1

It has been a really long time since I have last put up a blog post.

With a combination of the summer holiday, and then on to various pet projects that have been keeping me busy since then, I have had little time to blog.

One of the more interesting projects I am working on at the moment, is creating a web-based version of my Urania astronomical library, which is a complete rewrite of the C# codebase into Javascript.

It is still a while away from completion, but it is looking very promising indeed.

I will keep you posted as to my progress….