.comment-link {margin-left:.6em;}
My Photo
Name:
Location: Unspecified, Mauritius

I too, am a bug within Māyā.

My Other Blog(s) and Site(s)
Friend sites and blogs
My Recent Posts
Tutorials
Best Articles
My C-Sharp Ideas
Archives
Blog Directories

Sunday, September 18, 2005

 

Popularity Checking Tool - And Random Thoughts

Find out if you're popular or not.
[Yay, my popularity is 0.0000000000000000000000000000000000001]

I was a little bit busy. I had homework to do, I had an assignment to complete and on top of that, I'm working on a freelance job, and I have 2 personal projects running. Which leaves me with plenty of free time to think about nonesense. I was wondering whether there's a way of measuring one's popularity. Of course, if you want to measure something, you need to have something else against which to compare the value.

I devised an ingenious (and perfectly flawed) means of finding out a person's popularity, which I decided to baptize (2 minutes ago) as the "Rowan-Dynamic-Popularity-Counter". Rowan, because it's my name. Dynamic, because it sounds cool, and popularity counter, because after performing the various hyper-complex mathematical calculations involving addition and division of whole numbers, you're left with a floating point value which represents an invividual's popularity, compared to another one.

Comparing your popularity won't work, if you're a "normal" individual. This technique of finding popularity is solely based on the number of web pages that contains your name. You need to be some kind of actor/actress, or singer or somebody who yields more than 1000 page results on search engines with your name being the exact keyword. Although it doesn't really represent real-world statistics, it does mirror popularity to a certain extent.

Well, yes. My RDPC (Rowan Dynamic Popularity Counter
(TM)) algorithm involves the use of search engines to count the number of results returned with exact matching keywords. Of course, because nothing is absolute in this universe, you have to compare the total number of results with a known celebrity's return results.

The use of multiple search engines will theoretically yield better results, if we consider that different search engines cover different parts of the internet (although this is not totally true).

I needed a lab rat. I found the name "Jaime Ray Newman" on IMDB. Turns out she stars in 2 episodes of SG-Atlantis. Maybe I should download those sometime soon... I tested her popularity against Nicole Kidman's:

[J] represents Jaime, [K] represents Nicole Kidman

google
[J] 44,400
[K] 5,790,000
-> 0.77%

msn
[J] 1,163
[K] 802,235
-> 0.14%

yahoo
[J] 2,560
[K] 10,300,000
-> 0.02%

all the web
[J] 1,150
[K] 4,690,000
-> 0.02%

Average: 0.24%

Jamie Ray Newman is therefore currently at 0.24% (18 Sep 05) of Nicole Kidman's popularity. Yep... Now time for automation. How about putting all of this into a little C# program that'll do the job for us, eh? Hehe... It'll be a totally useless program, but there's worse. Look what I found (quoted from http://www.tifareth.com/tpsy.html):

Tele Hypnosis Pro is a esoteric program that uses the occult power of your computer to influence people remotely; the program takes its root in the ancient qabalistic magick and the modern psychotronics, giving you an unvaluable tool to influence people remotely. The effect of the program is natural and progressive; that means that the effects are not sudden, so the person will never know that has been submitted to remote mind control; the effects are progressive, so for example, if you use TELE HYPNOSIS PRO to seduce remotely a woman that previously ignored you, the effects will be progressive, she will start to feel some attraction for you, that with the continue usage of the program, will become love, and finally, deep love; the effect is so natural that she will never suspect she was submitted to remote mind control; she will always think that she fell in love for you in a natural way.

I always thought I was a bit crazy. I really feel normal now. And I'm proud I can write fairly good English.

Coming up next week: A full tutorial on how to use the System.Occult namespace, and make use of the System.Occult.MindControl class. If you don't have the Occult namespace on your GAC, download the ODK (Occult Development Kit) from Microsoft. It's free.


Wednesday, September 07, 2005

 

MySQL with C#

A quick intro
Is MySQL really mine?

Hello guys. I'm back from uni, and in full health. I've got so many new things to tell you, so many new things to teach you... hehe! :)

MySql is one of the most popular (and free) database management software around. You can have a look and freely download MySQL at www.mysql.com - make sure to download the .Net connector and also the MySQL administrator if you can. It's pretty useful if you don't know much of MySQL.

Now, let's get started. After downloading MySQL, MySQL's Administrator and MySQL Connector, make sure you're not a silly dick with a condom stuck up in your ass. Already checked? Okay, we're set to go.

We'll open up MySQL Administrator. The MySQL Administrator provides a nice user interface for people like me and you (if you're reading this, then I guess you don't know much about SQL) who aren't quite fluent in SQL. Well, I wasn't a few months ago, but now I'm some kind of advanced noob. Anyways, open up MySQL Administrator. You'll see something like this:




I remember being stuck on this fucking screen for quite some time the first time I opened up MySQL. Well duh, of course, the server host is localhost, and the username is "root" (and not "sa"). The password's the password that you typed in during installation. Don't change the port unless you specified something else during install. Click on OK. You should now be into MySQL Administrator.

At the top left, you'll see a menu with pretty icons on it. There's mainly "Server Information" which gives you information about your SQL server, Service Control - which allows you to start / stop / restart the MySQL service on your machine, Startup Variables - some useful variables and paths for MySQL, User Administration - where you can create / manage / delete / update users, etc... I'm not going to explain in detail what each of the menu items do, they're pretty much straightforward I think :)

Let's get straight to the point. What interests us for the moment is the Catalogs menu item, found at the bottom of the top-left menu. Click on the catalog, and create a new catalog by right-clicking on some empty space on the list box right beneath the top-right menu. Choose "Create New Schema". By default, mysql already has a few schema's created, but never mind about them. Create a new one, called CS. CS, of course, doesn't stand for Counter-Strike (as many dick-heads might have thought), but rather for C-Sharp. This is going to be our test catalog.

Right, after creating that schema, we'll need to create a new table for it. Right click on the big space on the right of the menu's (where obviously the tables should be, but aren't) and click on Create Table. Well, heh, you can also click on the little "Create Table" button, but that's all up to you.

Create a table named users. Make sure the table is of type "MyISAM" and not "InnoDB". We don't need to use transactions here :) Here are screenshots of my users table:.




Here are the types I used. Make sure usr_Name (the username) and usr_Pass are maked as "Binary". Else, the username and passwords wouldn't be case-sensitive at all.






We don't need no transactions! Use MyISAM storage engine.


Right. Now that our tables are set up, we can open up our C# editor. Create a new console application. Add a reference to the MySQL .net Connector (which I'm sure you already downloaded and installed from this location). The MySQL connector for the .Net framework 1.0, after installation, can normally be found at [MySQLInstallPath]\MySQL Connector Net 1.0.4\bin\.NET 1.0

Here's the wrapper that I wrote for this example. It's pretty straightforward. There's a class called "DbWrapper" which does all the database work for us. The DbWrapper has methods to add a user, verify whether a username exists or not, and validate a username and password.




using System;
using MySql.Data.MySqlClient;

namespace CSConnector
{
/// <summary>
/// Wraps calls to the users database
/// </summary>
public class DbWrapper
{
private MySqlConnection sqlConn;
private string connStr;
private bool isConnected;

/// <summary>
/// Creates a new database wrapper object that wraps around
/// the users table.
/// </summary>
/// <param name="svr">The name of the server</param>
/// <param name="db">The database catalog to use</param>
/// <param name="user">The user name</param>
/// <param name="pass">The user password</param>
public DbWrapper(string svr, string db, string user, string pass)
{
this.connStr = "Server="+svr+";Database="+db+";Uid="+user+";Pwd="+pass+";";

try
{
sqlConn = new MySqlConnection(this.connStr);
}
catch(Exception excp)
{
Exception myExcp = new Exception("Error connecting you to " +
"the my sql server. Internal error message: " + excp.Message, excp);
throw myExcp;
}

this.isConnected = false;
}

/// <summary>
/// Creates a new database wrapper object that wraps around
/// the users table.
/// </summary>
/// <param name="connStr">A connection string to provide to connect
/// to the database</param>
public DbWrapper(string connStr)
{
this.connStr = connStr;

try
{
sqlConn = new MySqlConnection(this.connStr);
}
catch(Exception excp)
{
Exception myExcp = new Exception("Error connecting you to " +
"the my sql server. Error: " + excp.Message, excp);

throw myExcp;
}

this.isConnected = false;
}

/// <summary>
/// Opens the connection to the SQL database.
/// </summary>
public void Connect()
{
bool success = true;

if (this.isConnected == false)
{
try
{
this.sqlConn.Open();
}
catch(Exception excp)
{
this.isConnected = false;
success = false;
Exception myException = new Exception("Error opening connection" +
" to the sql server. Error: " + excp.Message, excp);

throw myException;
}

if (success)
{
this.isConnected = true;
}
}
}

/// <summary>
/// Closes the connection to the sql connection.
/// </summary>
public void Disconnect()
{
if (this.isConnected)
{
this.sqlConn.Close();
}
}

/// <summary>
/// Gets the current state (boolean) of the connection.
/// True for open, false for closed.
/// </summary>
public bool IsConnected
{
get
{
return this.isConnected;
}
}

/// <summary>
/// Adds a user into the database
/// </summary>
/// <param name="username">The user login</param>
/// <param name="password">The user password</param>
public void AddUser(string username, string password)
{
string Query = "INSERT INTO users(usr_name, usr_pass) values" +
"('"+username+"','"+password+"')";

MySqlCommand addUser = new MySqlCommand(Query, this.sqlConn);

try
{
addUser.ExecuteNonQuery();
}
catch(Exception excp)
{
Exception myExcp = new Exception("Could not add user. Error: " +
excp.Message, excp);
throw(myExcp);
}
}

/// <summary>
/// Verifies whether a user with the supplied user
/// credentials exists in the database or not. User
/// credentials are case-sensitive.
/// </summary>
/// <param name="username">The user login</param>
/// <param name="password">The user password</param>
/// <returns>A boolean value. True if the user exists
/// in the database, false if the user does not exist
/// in the database.</returns>
public bool VerifyUser(string username, string password)
{
int returnValue = 0;

string Query = "SELECT COUNT(*) FROM users where (usr_Name=" +
"'"+username+"' and usr_Pass='"+password+"') LIMIT 1";

MySqlCommand verifyUser = new MySqlCommand(Query, this.sqlConn);

try
{
verifyUser.ExecuteNonQuery();

MySqlDataReader myReader = verifyUser.ExecuteReader();

while(myReader.Read() != false)
{
returnValue = myReader.GetInt32(0);
}

myReader.Close();
}
catch(Exception excp)
{
Exception myExcp = new Exception("Could not verify user. Error: " +
excp.Message, excp);
throw(myExcp);
}

if (returnValue == 0)
{
return false;
}
else
{
return true;
}
}

/// <summary>
/// Checks whether a supplied user name exists or not
/// </summary>
/// <param name="username">The user name</param>
/// <returns>True if the username is already in the table,
/// false if the username is not in the table</returns>
public bool UserExists(string username)
{
int returnValue = 0;

string Query = "SELECT COUNT(*) FROM users where (usr_Name=" +
"'"+username+"') LIMIT 1";

MySqlCommand verifyUser = new MySqlCommand(Query, this.sqlConn);

try
{
verifyUser.ExecuteNonQuery();

MySqlDataReader myReader = verifyUser.ExecuteReader();

while(myReader.Read() != false)
{
returnValue = myReader.GetInt32(0);
}

myReader.Close();
}
catch(Exception excp)
{
Exception myExcp = new Exception("Could not verify user. Error: " +
excp.Message, excp);
throw(myExcp);
}

if (returnValue == 0)
{
return false;
}
else
{
return true;
}
}


}
}


This is not really a tutorial on SQL statements. But still, I'll give you a quick overview on what exactly I did in the statements, and how you can use this code.

First of all, it's up to you to make sure that the users don't include single inverted commas into the username or password fields. You must absolutely make sure the user can only enter strings containing only characters a..z, A..Z and numbers. If you don't, you might run the risk of having SQL injection attacks on your code, especially if you're making an ASP.net Web Application.


To insert a new user:
INSERT INTO users(usr_Name, usr_Pass) VALUES('Rowan', 'ISeeSharp');

To verify whether a user exists:
SELECT COUNT(*) FROM users WHERE (usr_Name='Rowan') LIMIT 1;

To verify user credentials:

SELECT COUNT(*) FROM users WHERE (usr_Name='Rowan' AND usr_Pass='ISeeSharp') LIMIT 1;


There's no black magic in there. I'm just inserting users and counting records. Here's how you can use the wrapper - I used only the Add user and UserExists method. You can try the rest out yourself :)




DbWrapper myWrapper = new DbWrapper("localhost", "CS",
"iseesharp", "seesharper");
myWrapper.Connect();

myWrapper.AddUser("Rowan", "ISeeSharp");
if (myWrapper.UserExists("rowan"))
{
Console.WriteLine("Something's weird here");
}
else
if (myWrapper.UserExists("Rowan"))
{
Console.WriteLine("I exist, therefore I think!");
}

myWrapper.Disconnect();


This short piece of code instantiates a new DbWrapper, and passes it the required parameters to connect to my database. It adds a new user "Rowan" with the password "ISeeSharp" into the SQL Database. In between the Connect() and Disconnect() methods, you'll be able to use any of the provided methods in the wrapper. Make sure you disconnect after using the wrapper!

Cheers,
Rowy