Dec 26, 2010

Resize image on Ruby

We are using mini_magick to resize images on Ruby.

The best way to install it on Rails is to copy the source code and put it in the plugin folder. Therefore, the running machine does not really need to install mini_magick.

Nevertheless, you will need ImgeMagick anyway. and that's it.

Nov 24, 2010

Rails's cookies

Here is some strange behaviour:

def index
cookies[:key] = "val"
puts cookies[:key]
redirect_to :second_index
end

def second_index
cookies[:key] = "newval"
puts cookies[:key]
end

## Output :
## Open index page for the first time
# nil
# val

## Open index page the second time
# newval
# val



cookies[] is to retrieve the current cookies
but cookies[]= is to assign outgoing cookies, not to re-assign the current cookies.
Actually, you can never re-assign the current cookies.

-----------------------------------------

Here is another different behaviour of using sign and string as indices:

## cookies and request.cookies are different
cookies.class #=> ActionController::CookieJar
request.cookies #=> Hash

## how to access value from cookies and request.cookies
# First set some value in cookies
cookies[:key] = "value"

cookies["key"] #=> "value"
cookies[:key] #=> "value"
# both the output are of type String

request.cookies["key"] #=> "value"
request.cookies["key"].class #=> CGI::Cookie

request.cookies[:key].empty? #=> true
request.cookies[:key].class #=> Array

Ref: http://www.quarkruby.com/2007/10/21/sessions-and-cookies-in-ruby-on-rails#scinrails

First use of Git to obtain whowish project

Assuming you have installed msysgit, you need to follow these steps in order to obtain whowish project.

1. First of all, you need to generate SSH Key for your computer by:
Run Git GUI > Help > Show SSH Key > then generate SSH key.

No need to set passphrase, just press 'enter'.

After you see the SSH key in the textarea, copy it and send it to me by any mean.

2. After I approve your key, you can test it by:

ssh git@github.com

If you see congratulation message, then you're fine.

3. Now you can check out by:

Right-click at a destination folder, select Git Bash,

Then:

git clone git@github.com:tanin47/whowish.git

* Don't forget to set username and email by:

git config --global user.name "your name"
git config --global user.email email@email.com

And there you go, the project will be downloaded to your computer.

Nov 23, 2010

How to access Github

Install msysgit.

How to use Git, really

1. When one wants to start working, he/she NEEDS to fork a new branch by using

git checkout -b branch_name

2. After making some changes, you can:

git commit -a -m "message here"

3. You can push your updates to the server, but if your friend worked on the same branch before, you might want to pull first:

git pull

Then:

git push

4. After sometimes, you might want to merge your branch with the main branch:

git checkout master (switch to the main branch)
git pull (get new updates)
git pull branch_name (merge with your branch)

Then after merging, you NEED to fork again in order to make another change.

Nov 22, 2010

The specified module could not be found ... mysql_api.so

But mysql_api.so does exist.

You just have to make sure that MySQL's bin path is in PATH environment variable.

The specified module could not be found ... mysql_api.so

But mysql_api.so does exist.

You just have to make sure that MySQL's bin path is in PATH environment variable.

Aptana RadRails Setting up for whoWish

  1. Create 3 databases (schema) in MySQL: whowish_development, whowish_test, whowish_production
  2. Get whoWish project folder and import it to Aptana RadRails
  3. Modify config/database.yml so that the username and password are valid for accessing the database
  4. Right-Click on the project and choose Rake > db > schema > load (All the tables will be created)
  5. Right-Click on the project and choose Run As > Run Configurations ...
  6. Right-Click on Ruby Application and Choose 'New'
  7. In the name textbox, type 'Run'
  8. In the Project textbox, browse and choose 'whoWish'
  9. In the File textbox, browse and choose 'script/server'
  10. Click on Apply and Click on Run
  11. Open browser and go to http://localhost:3000
You also need to install:
  • recaptcha plugin, by running 'gem install ruby-recaptcha'.
  • mysql plugin, by running 'gem install mysql'

If you don't have Rake, please run 'gem install --remote rake' in command line.

If you do not have Gem, then download Gem here (we use 1.3.5). and type 'ruby setup.rb' in command line.

If you do not have Ruby, then please install Ruby 1.8.6.

And we use Rails version 2.3.4.

Nov 10, 2010

DbUnit tutorial

Setting Up Lift Environment

Lift enviroment

Lift is a very new web framework and, inevitably, unstable. Therefore, to make Lift work, the versions of Scala, Apache Maven, and Lift itself “must” be compatible.

For the website whowish.com; Lift 2.1, Scala 2.8.0, and Apache Maven 2.2.1 are chosen.

Installation
The installation steps are:

1. Install Netbeans 6.9
2. Install Scala 2.8.0 final (Please read README)
3. Install Scala Plugin for Netbeans 6.9 (Please read README.png)
4. Install Apache Maven 2.2.1 (Please read README)
5. Create a project that uses Lift 2.1 with Scala 2.8.0 by creating manual archetype with these parameters:

* archetype_group_id = net.liftweb
* archetype_artifact_id = lift-archetype-basic_2.8.0
* archetype_version = 2.1
* archetype_repository = http://scala-tools.org/repo-releases
* remote_repositories = http://scala-tools.org/repo-releases
* group_id = your group id
* artifact_id = your artifact id (which is project identity)
* version = your project version

6. Add DbUnit and MySQL dependencies by add these lines to pom.xml under dependencies tag:

* add dbunit 2.2
* add mysql-connector-java 5.1.13

7. That’s it... Congratulation !

Configure it to run with jetty

1. Right-click on Project and select Propeties
2. Go to Actions
3. Select Run Project and, under Execute Goals, type jetty:run
4. Select Debug Project and, under Execute Goals, type jetty:run

5. Go to pom.xml, find <plugin> of Jetty, and change scanIntervalSeconds to 0.

(Right now continuous recompilation on Jetty does not work ...)

Testing

Right-click on the project and choose either Run or Debug

Unit Testing with database mock-up

We are using DbUnit to set the database (MySQL) to a predefined state (coded in XML) and, after running a test code, DbUnit can compare the present state of the database with an expected state (coded in XML)

Oct 26, 2010

Data is out of sync

I have found out that, in Slidex, the printed data cannot be queried at the time when it is sending data to the printer.

Because the printing task is on a different thread. This means that some other threads might already change the data in the database.

It makes the printed data wrong.


Here is the fix:

We need to make copies of all data needed by a printing task. And that's it.

----------------------------------------------------------------------------------

This also happens with all the commanders. We need to make copies of data just for sending.

Oct 16, 2010

Strange behavior of NetworkStream.WriteByte(byte b)

It turns out if you do WriteByte() too frequently, it crashes the network of the computer. The problem might be XP does not handle buffer very well or it blocks too many packets being sent.

We solve the problem by using BufferedStream and do not flush() unless we need to. And that's it. It solves all the problems.

System.Security.Cryptography.CryptographicException: Object already exists.

It occurs when I try to initialize an RSACryptoServiceProvider instance.

This happens because the program is run with different users; One with normal user and another with startup user.

When the key is created, its permission is only granted to the creator.

Therefore, you need to change the permission of the key in order that it can be used by everyone.

Here is the code:


CspParameters cspParams;
cspParams = new CspParameters(PROVIDER_RSA_FULL);
cspParams.KeyContainerName = CONTAINER_NAME;
cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
cspParams.ProviderName = "Microsoft Strong Cryptographic Provider";

CryptoKeyAccessRule rule = new CryptoKeyAccessRule("everyone", CryptoKeyRights.FullControl, AccessControlType.Allow);

cspParams.CryptoKeySecurity = new CryptoKeySecurity();
cspParams.CryptoKeySecurity.SetAccessRule(rule);



OR another solution is to not use UseMachineKeyStore Option.

Never flush() the stream if you don't need to.

Today I found a problem that flush() the stream too often can cause freezing to the ethernet card. The computer won't have access to any network anymore. It happens to only Windows XP though. It seems like Windows 7 fixes this problem with another layer of flushing.

Here is some flushing practice I have found on the internet:

The only time you need to call flush() is if ALL of the following are true:

- You've written some of the data

AND

- You're not totally done. There's still more data to write.

AND

- You want to make sure the data you've already written reaches its destination ASAP. It is not acceptable if there's still some sitting in the buffer that goes with the next write that will come later.

Otherwise, there's no need to call it. If you're already done writing, you'll call close(), and that will call flush() anyway. If you're writing all of the data in chunks one right after the other, and not stopping to do other processing between chunks, then you'll be writing as fast as possible and calling close() right away anyway, so, again, no benefit to calling flush.

So with this code, there's no reason to call flush() explicitly. Note, however, that you should always close streams in a finally block, so that they get closed even if there's an exception.

-------------------------------------------------------------------------------

There will be no buffer overflow because OS will handle that itself. A little bit of lesson here is not to try to handle what OS has already handled; It might cause some strange problems...

Sep 26, 2010

Strange Socket Streaming problem

Today I've found out that, on an old computer with an old Ethernet card (only 3 years old), the card cannot handle big data.

But there is no problem if we use the native function Write(byte[],int,int); to write data.

There will be a problem if we use Write(byte) to write every single byte manually.

The byte[] is of size 200, and that already causes problem.

The ethernet card will crash.

Sep 19, 2010

Window Mobile sometimes get out off Unattended mode by itself.

Today we have found one of the PDAs decided to switch to the normal mode from the unattended mode.

Right now we are going to solve this problem by constantly putting the PDA in the unattended mode.

In combination, we will turn the WiFi on programmatically before making any connection, and we will put the PDA in the unattended mode if the power button is pressed.

And while the screen is off, we will, every 60 seconds, confirm the unattended mode.

Aug 17, 2010

Motorola Symbol MC50 to work with WPA-PSK (TKIP)

After figuring out why a Symbol MC50 does not work with WPA-PSK (TKIP), it turns out that most of the pocket pcs do not work with it.

My HTC with Window Mobile 6 does not work with it.

I have found a client for Symbol MC50 to make it work with WPA-PSK (TKIP). It is called 'Aegis client'.

You can download it here:
https://docs.symbol.com/KanisaPlatform/Publishing/37/10411_f.html

And here is the license:

License ID: 62549151
License Key: 9D71CCB4BDF5E7C51D358F9EDE42A21296809778

Aug 15, 2010

Relay Data-Syncrhonization Protocol Lessons (name is still tentative)

1. Data are never updated at the very same moment users modify them. This implies a global mutual lock throughout the application.

2. When users change local data. (Users see the data changing immediately.) The new local data are submitted to the server. Until the approval or rejection is received (from the server), All new updates from the server are pended. This is to avoid data flickering.

This implies that we need a multiplexer in order to hold updates, and later decide which update to be fired after the approval and rejection is received.

Data Changes --- (All updates during these moments are held) --- Got approval or rejection ---> Decide which updates are the latest ones and fire them.

3. Every data shall hold a timestamp, which indicates the latest update that happened. And we shall never replace new data with older ones.

Jul 20, 2010

Determine how big an array can be allocated.

long FreeBytes = New System.Diagnostics.PerformanceCounter("Memory", "Available Bytes").NextValue();

This means that you can allocate new byte[FreeBytes];

Jul 6, 2010

Simulate Click on PDA (.Net Compact Framework)

It turns out that to simulate a click in .NET Compact Framework is indeed a difficult problem. The normal way of using mouse_event() and SetCursorPos() does not work because SetCursorPos() does not work. Therefore, a click event always occurs on (0,0).

There is a workaround, though it is not quite comfortable as the normal way. This is because you need a Form object on which you want to click on.

Here is the source code.


[DllImport("coredll.dll")]
public extern static int SendMessage(IntPtr hwnd, uint msg, uint wParam, uint lParam);

public const int WM_LBUTTONDOWN = 0x0201;
public const int WM_LBUTTONUP = 0x0202;

private static int delay = 100;

private static uint MakeDWord(int hiword,int lowword)
{
return ((uint)hiword * 0x10000) | ((uint)lowword & 0xFFFF);
}

private delegate IntPtr d_GetHandle(Form f);
private static IntPtr GetHandle(Form f)
{
return f.Handle;
}

internal static void LeftClick(Form form, int x, int y)
{
IntPtr handle = (IntPtr)(form.Invoke(new d_GetHandle(GetHandle), new object[] { form }));

SendMessage(handle, WM_LBUTTONDOWN, 1, MakeDWord(y, x));
Thread.Sleep(delay);
SendMessage(handle, WM_LBUTTONUP, 1, MakeDWord(y, x));

}

Jun 21, 2010

Firefox redirect on a google search result

The symptom also occurs in Google Chrome; Any webpage won't be loaded on Google Chrome.

If you encounter these two symptoms, you are infected Rootkit.Win32.TDSS.

Just download the tdsskiller, and that's it. Problem solved.

Firefox redirect on a search result (After removing AV Security Suite)

I've just solved a malware problem. Firefox seems to redirect to other website when I click on a Google search result.

I have used Malwarebytes'. It deleted these registry keys:

HKEY_CLASSES_ROOT\dnscache.dnscacheobj (Trojan.BHO) -> Quarantined and deleted successfully.
HKEY_CLASSES_ROOT\dnscache.dnscacheobj.1 (Trojan.BHO) -> Quarantined and deleted successfully.

And that's it. The problem is gone.

Jun 20, 2010

Clicking events on UI built with a graphic library

I have been working with my friends on an Auto-clicker program. It is used for clicking on the game. And the game is built with a graphic library. It draws everything manually.

We have found that:

In order to simulate a click on it, we have to simulate 'mouse down', wait for some time, and simulate 'mouse up'.

This is because the game draws itself every 20 ms (or longer). If we fire 'mouse down' and 'mouse up' in the same drawing round, the game will not recognize a click action.

And that's it.

PS. this does not apply for a program built with .NET standard toolkit.

Feb 26, 2010

Syntax Error on ActionMailer

Here is how the error looks like:

/usr/local/lib/ruby/1.8/net/smtp.rb:930:in `check_response'
/usr/local/lib/ruby/1.8/net/smtp.rb:899:in `getok'
/usr/local/lib/ruby/1.8/net/smtp.rb:828:in `mailfrom'
/usr/local/lib/ruby/1.8/net/smtp.rb:653:in `sendmail'
/usr/local/lib/ruby/gems/1.8/gems/actionmailer-2.3.4/lib/action_mailer/base.rb:684:in `perform_delivery_smtp'
/usr/local/lib/ruby/1.8/net/smtp.rb:526:in `start'
/usr/local/lib/ruby/gems/1.8/gems/actionmailer-2.3.4/lib/action_mailer/base.rb:682:in `perform_delivery_smtp'
/usr/local/lib/ruby/gems/1.8/gems/actionmailer-2.3.4/lib/action_mailer/base.rb:523:in `__send__'
/usr/local/lib/ruby/gems/1.8/gems/actionmailer-2.3.4/lib/action_mailer/base.rb:523:in `deliver!'
/usr/local/lib/ruby/gems/1.8/gems/actionmailer-2.3.4/lib/action_mailer/base.rb:395:in `method_missing'
/usr/local/apache2/Yabe/app/controllers/facebook_controller.rb:381:in `test_smtp'



The way to solve it is very simple.

Please remove <> from the "recipients" and the "from" of your ActionMailer object

Jan 21, 2010

"cannot enable executable stack as shared object requires: Permission denied" on Fedora Core Linux

I've got this problem while trying to run Linux. It is actually the problem of the security program in Fedora Core.

Here is how you solve it.

Open the terminal and switch to root user, by typing "su -".

Now type "setenforce 0".

And that's it. Your problem's solved !

JsHttpRequest problem

One of AJAX Library, JsHttpRequest, supports a lot of stuffs (e.g. file upload through iframe). It worked fine, until I used it for my facebook application.

The problem is that the outer frame is on facebook.com. The inner frame is on my server.

JsHttpRequest makes use of the outer frame, which is on a different domain. Therefore, the "permission denied" exception is thrown.

It is thrown on this commmand: top.JsHttpRequestGlobal = JsHttpRequest;

The source code is also obfuscated.

Therefore, I have decided to implemented my own AJAX upload library !

Jan 20, 2010

Flickering free .NET form

To achieve a flickering free form, Only enabling DoubleBuffered property is not gonna work.

You need to add this in the main form:


protected override CreateParams CreateParams {
get {
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x02000000;
return cp;
}
}


This does not speed up the painting process. It just makes your form invisible while the painting process is being done.

Here is the reference: link

Jan 11, 2010

InvalidAuthenticityToken

A controller always throw InvalidAuthencityToken, if it receives HTTP Post from a form which is not created from the controller itself.

It is the Rails protection mechanism.

Therefore, to solve it, we have to turn it off.

In the controller, just add this line:

protect_from_forgery :only => [:create, :update, :destroy]


It specifies that the protection mechanism only applies to those three actions (create, update, and destroy).

For other actions, they can receives a third-party HTTP Post without throwing InvalidAuthencityToken.

Debugging Rails

I've just had a painful experience: Rails does not accept an HTTP request from facebook canvas, and all it returns is HTTP 422 status, which practically means nothing.

After googling for a while, I have found a way to debug a rails server. Simply, runs

ruby script/server


and that is it. You will see debugging message from Rails on the terminal.

And another good thing about it is that you do not need to restart the server everytime you make a change.