Tuesday, December 29, 2009

C# Clipboard in Console Application

In C# accessing the Clipboard suppose to be easy, but you'll find out it doesn't work in the normal way.
Here is a small note from MSDN that I missed at first:

The Clipboard class can only be used in threads set to single thread apartment (STA) mode. To use this class, ensure that your Main method is marked with the STAThreadAttribute attribute.
So, in a Console application, use this function:

Code:
public static object GetClipboardData()
{
    object ret = null;
    ThreadStart method = delegate()
    {
        System.Windows.Forms.IDataObject dataObject = Clipboard.GetDataObject();
        if (dataObject != null && dataObject.GetDataPresent(DataFormats.Text))
        {
            ret = dataObject.GetData(DataFormats.Text);
        }
    };
    if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
    {
        Thread thread = new Thread(method);
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        thread.Join();
    }
    else
    {
        method();
    }
    return ret;
}

Saturday, December 26, 2009

Step-by-Step Math

Have you ever given up working on a math problem because you couldn’t figure out the next step? Wolfram|Alpha can guide you step by step through the process of solving many mathematical problems, from solving a simple quadratic equation to taking the integral of a complex function.

From here:
http://blog.wolframalpha.com/2009/12/01/step-by-step-math/

Example:
http://www.wolframalpha.com/input/?i=integrate+x+Sqrt[1-Sqrt[x]]

Sunday, December 20, 2009

Windows 7 & HomeGroup: Sharing with Windows XP, Windows Vista, and other operating systems

http://www.microsoft.com/downloads/details.aspx?FamilyID=80b1aa5d-1b5a-4447-8036-acc918ba7af2&displaylang=en

Windows 7 - Remove User From Login Screen

The users on the log-in screen are all the users that belong to the "Users" group.

To remove a user invoke the following command:

  net localgroup users /delete <username>

Instead, on Windows 7 Ultimate and Professional, you can use the User Manager to do that:

Monday, December 7, 2009

How to grab Google autocomplete list

We all know this wonderful feature:

Automation of grabbing that list can be helpful for instance if you want to know what people are looking for.

While typing in the search box, somewhere there is a Javascript code that makes the following HTTP GET request:
http://www.google.com/complete/search?hl=en&q=QUERY&cp=LEN(QUERY)

For example, the following query gives the same results as in the picture:
http://www.google.com/complete/search?hl=en&q=how%20to%20be%20better%20at%20&cp=20

window.google.ac.h(["how to be better at ",[
["how to be better at halo 3","43,100,000 results","0"],
["how to be better at basketball","87,500,000 results","1"],
["how to be better at math","52,900,000 results","2"],
["how to be better at soccer","88,300,000 results","3"],
["how to be better at football","207,000,000 results","4"],
["how to be better at beer pong","2,760,000 results","5"],
["how to be better at call of duty 4","72,600,000 results","6"],
["how to be better at madden","25,900,000 results","7"],
["how to be better at volleyball","9,370,000 results","8"],
["how to be better at chess","15,300,000 results","9"]]])

Monday, November 23, 2009

Installing Windows XP Professional on HP Compaq nx6310

Four years ago I bought HP laptop nx6310. It came with Windows XP Pro already installed.
Today I reinstalled Windows, but it wasn't as smooth as I thought it would be.
First, Windows setup didn't recognize any hard disk:
"setup did not find any hard disk installed in your computer…"
After searching Google a bit, I found out that I should disable SATA on the Bios.
I disabled it, and continued setup until:
"Windows could not start because the following file is missing or corrupt C:\Windows\inf\Biosinfo.inf"
This time it was a bit harder, because all the solutions I found on the Internet suggested I should get SP2 and it will be solved by itself, because it has all the missing drivers. The only problem is that I already had SP2. Some sites offered to download an installation with all the needed drivers built-in. But I couldn't use it because I want to install Windows in Hebrew.
In the end, the solution was very simple, I went to the place on the Bios where I recently disabled SATA, and I disabled everything else.
It worked. Windows is now installed.
Drivers were downloaded from here:
http://h20000.www2.hp.com/bizsupport/TechSupport/SoftwareIndex.jsp?lang=en&cc=us&prodNameId=1839164&prodTypeId=321957&prodSeriesId=1839143&swLang=8&taskId=135&swEnvOID=1093
The only problem is I wanted to re-enable all the features I disabled, and I couldn't enable SATA without crashing Windows. So I found this post: http://mytechweblog.blogspot.com/2007/10/enabling-sata-native-mode-after-xp.html. The author forgot to mention something, but he did mention it here: http://forums13.itrc.hp.com/service/forums/bizsupport/questionanswer.do?threadId=1057792&admit=109447627+1258968594947+28353475, so it's better to follow the second link. Note that after following the instructions on the link you must re-enable SATA otherwise Windows won't load.
It works! :)

Sunday, November 15, 2009

Telnet on Windows 7

By default Telnet is not installed on Windows7 and you get this error message:
'telnet' is not recognized as an internal or external command,
operable program or batch file.
Solution:
Turn on this feature in Control Panel as explained here:
http://www.tech-recipes.com/rx/4230/windows-7-install-the-telnet-client/


I found a link that explains the list of features for Windows Vista. Most of it is relevant to Windows 7 too:
http://www.bleepingcomputer.com/tutorials/tutorial134.html

Thursday, November 5, 2009

Linux Tutorial

A very good Linux tutorial that I found:
http://rute.2038bug.com/index.html.gz

Wednesday, November 4, 2009

Hide URL in address bar using iframe (code that works)

I've been searching Google for some time, and I expected to find the answer easily, but that was not the case. So I wrote it here.
The following will show Yahoo home page in an iframe, but the URL in the address bar will be yours, and it stays the same, even if the user clicks on some link and go to another site.
If you ever tried to create an iframe, you noticed that you have two scroll bars - one of the page and one of the iframe. Well, the following code solves that too. The piece of code that most people are looking for is marked in red.

<html>
<head>
<style type="text/css">
html {
overflow: hidden;
}
</style>
</head>
<body>
<iframe name='FRAME1' src='http://www.yahoo.com' width='100%' height='100%' marginheight='0' marginwidth='0' scrolling='auto' frameborder='0'>
<p>Your browser does not support iframes.</p>
</iframe>
</body></html>

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.