Thursday, October 22, 2009

URI might change in HttpWebResponse

In the following example the red bold line is very important, hence it's red and bold.
Without it, any cookies stored in the CookieContainer object from the GET request might not pass to the POST request. Consider the following scenario:
1. GET request to: "http://site.com/form.php"
2. Request is redirected to: "http://www.site.com/form.php"
3. Cookies are stored for this address
4. POST request to: "http://site.com/form.php"
Clearly, the POST request will not have the cookies. Solution:

CookieContainer cookieContainer = new CookieContainer();
Uri uri = new Uri("http://site.com/form.php");
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Method = "GET";
httpWebRequest.CookieContainer = cookieContainer;
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
uri = httpWebResponse.ResponseUri;
httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.CookieContainer = cookieContainer;
httpWebRequest.Method = "POST";
...


Copy code with syntax highlights - Visual Studio and Notepad++

To copy from Visual Studio, first paste in Word, then copy from Word and paste in target

To copy from Notepad++, use the NppExport plugin
(I found the solution here)
Select your code, then: Plugins -> NppExport -> Copy all formats to clipboard
To create a shortcut for this command, you can use Settings -> Shortcut mapper...
I use Ctrl+Shift+C for this command

Update: See a better solution for C# here

MySql and numbers

I really like MySql!

Both queries work:
SELECT * FROM table1 WHERE numbers_column=4
SELECT * FROM table1 WHERE numbers_column='4'

But that's nothing comparing to:
INSERT INTO table1 (numbers_column) VALUES (4)
INSERT INTO table1 (numbers_column) VALUES ('4')

Which means it's generic enough to write a statement without knowing the data type of the columns.
Was quite helpful in my previous project.

C# DataGridView and MySql

This code demonstrates how to bind a DataGridView control to a MySql table.
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=7604&lngWId=10

Usage:

// bind DataGridView control
Bind();
// now user can modify table using the DataGridView control.
// a faster way to modify table, is to use the Rows property
// DataGridView control will be updated automatically
Rows.Add("a", "new", "row");
// to save changes:
Save();


A few notes about command builder:

  • The command builder object MySqlCommandBuilder doesn't work with complex queries, in that case you should write your own commands for Update,Delete,Insert
  • When writing a custom Update command, notice there is a difference between the new and old values
  • In order to save time and effort, one could write a simple query and use the command builder object results to create the more complex query
  • I already have a class for it, I'll publish it later


Here is the code:


MySqlConnection mySqlConnection;
MySqlDataAdapter mySqlDataAdapter;
MySqlCommandBuilder mySqlCommandBuilder;
DataTable dataTable;
BindingSource bindingSource;

public void Bind()
{
    mySqlConnection = new MySqlConnection(
        "SERVER=localhost;" +
        "DATABASE=;" +
        "UID=;" +
        "PASSWORD=;");
    mySqlConnection.Open();

    string query = "SELECT * FROM
";

    mySqlDataAdapter = new MySqlDataAdapter(query, mySqlConnection);
    mySqlCommandBuilder = new MySqlCommandBuilder(mySqlDataAdapter);

    mySqlDataAdapter.UpdateCommand = mySqlCommandBuilder.GetUpdateCommand();
    mySqlDataAdapter.DeleteCommand = mySqlCommandBuilder.GetDeleteCommand();
    mySqlDataAdapter.InsertCommand = mySqlCommandBuilder.GetInsertCommand();

    dataTable = new DataTable();
    mySqlDataAdapter.Fill(dataTable);

    bindingSource = new BindingSource();
    bindingSource.DataSource = dataTable;

    dataGridView1.DataSource = bindingSource;
}

public DataRowCollection Rows
{
    get { return dataTable.Rows; }
}

public void Save()
{
    mySqlDataAdapter.Update(dataTable);
}


Sunday, October 11, 2009

What information is submitted in HTML form

Some of the information I discovered during working on a project, other stuff from Google and from: http://www.w3schools.com/html/html_forms.asp
It might seems obvious, but it caused me a lot of trouble.
There are 3 simple rules:
1. For POST method - If there are no files the Content Type is "application/x-www-form-urlencoded" otherwise it is "multipart/form-data"
2. It takes the "value" attribute of: "input", "select", "textarea"
3. It an element has "disabled" attribute it must be "false", and if it has "checked" attribute it must be "true"
More details:
1. For "input" it does not submit the value of elements with "type" equals to "submit" or "reset"
2. "button" elements are also submitted, but see the notes here: http://www.w3schools.com/tags/tag_button.asp

C# Image Processing library

This is a nice tool:
http://www.aforgenet.com/

From the documentation:


Hough circle transformation.
Namespace:  AForge.Imaging
Assembly:  AForge.Imaging (in AForge.Imaging.dll) Version: 2.0.1.0 (2.0.1.0)

Syntax


C#
public class HoughCircleTransformation

Remarks

The class implements Hough circle transformation, which allows to detect circles of specified radius in an image.
The class accepts binary images for processing, which are represented by 8 bpp grayscale images. All black pixels (0 pixel's value) are treated as background, but pixels with different value are treated as circles' pixels.
Sample usage:

CopyC#
HoughCircleTransformation circleTransform = new HoughCircleTransformation( 35 );
// apply Hough circle transform
circleTransform.ProcessImage( sourceImage );
Bitmap houghCirlceImage = circleTransform.ToBitmap( );
// get circles using relative intensity
HoughCircle[] circles = circleTransform.GetCirclesByRelativeIntensity( 0.5 );

foreach ( HoughCircle circle in circles )
{
    // ...
}

Initial image:

Hough circle transformation image:

Saturday, October 10, 2009

Project is done

My first project on RentACoder is done!
I got good a ranking (10) and a good comment from the buyer.
Now I'm developing a new project for the same buyer.
Here is a screenshot:

Sunday, October 4, 2009

C# abstract index operator

That's how it's done:

    public abstract int this[int index]
    {
        get;
        set;
    }

Saturday, October 3, 2009

C# string literals

http://msdn.microsoft.com/en-us/library/aa691090(VS.71).aspx

I have a feeling that this paragraph is going to save my day in the future:
Since a hexadecimal escape sequence can have a variable number of hex digits, the string literal "\x123"contains a single character with hex value 123. To create a string containing the character with hex value 12 followed by the character 3, you could write "\x00123" or "\x12" + "3" instead.

mysql_real_escape_string

I got this weird message in a PHP code where I wanted to escape input before putting it in a query:
Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'XXX'@'localhost' (using password: NO) in XXX on line 7


Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in XXX on line 7
It seems that this function needs a database connection to be opened in order to work. The reason is, that it must know the character set of the database in order to protect from SQL Injection.

10MB Internet!

My deal with my ISP is over, so I made an new deal for 10Mbps download and 800Kbps upload. I pay 95.4 NIS to Bezeq and 66.5 NIS to Bezeqint, and I got for free a brand new D-Link wireless router. The deal for 10Mbps was actually better than for 5Mbps. Bezeq is using their NGN technology, and they are working hard to get it into the market. It looked promising at the beginning with more that 10Mbps. However, today I get maximum download speed of 1.5Mbps, and surfing to web sites became really slow. I can't even watch South Park episodes anymore!

Friday, October 2, 2009

MD5 in PHP and in C#

I use MD5 for adding security for non secured connection between a client and a server. Though the information is not classified, it is important that it won't be changed by MITM.
The client needs to send data to the server. Both the client and the server have a common secret password. The server has a public integer counter. Each time a message sent I do: counter++;
When the client wants to send the data, he must add a signature which is the following:
md5(counter + secret_password + data)
or in C# terms:


        public static Encoding encoding = Encoding.Default;

        public static string ComputeMD5(string str)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            return Convert.ToBase64String(md5.ComputeHash(encoding.GetBytes(str)));
        }


        ComputeMD5(counter + secret_password + data);




On the server side, we compute the same thing in PHP:

base64_encode(md5($counter . $secret . $data, true)));


Unfortunately, sometimes it works and sometimes not. The result of MD5 is different in the two sites, though I verified the data is the same. It took me a day to realize the problem was special characters (I had the character 0xa0 instead of 0x0a by mistake), only to find out it's not the only problem, and there are still some problematic cases.
I'm sure it's a simple problem, and I don't see the solution due to the fact I'm awake for over 24 hours now. I'm pretty sure it has something to do with that encoding thing I had to use. I'm going to look into it tomorrow.