Saturday, January 27, 2007

From php to c#and asp.net

I learned asp.net for a few months three years ago and now i have to do a website for my work so i had to get acquainted again with the programming logic and c# syntax. I use c# because i can't say goodbye to the curly brackets blocks, Maybe python can make me abandon them but not VB.net.

The basics


The first thing i needed to know is how to include files because in php the master-content pages is set up by including files. Because the server only has the .net 1.1 framework i couldn't work with the master-content pages. This is where i first noticed a big difference between php and asp.net/c#. Where php is an embedded programming language, asp.net is the templating language for c#. You can go the php way and embed the c# code into your html code but if you use the asp.net controls and ids for other html elements you can keep your html clean enough so that a designer can understand what you are doing. All the html ids maybe a torn in the eye of css architects and javascript coders but it's workable.

But now back to the include files syntax. It's a weird html comment but it's easier than in php

<!--# file="c:\httpdocs\site\\test.aspx" -->

<!--# virtual="/site/testpage" -->

The first example is the counterpart of the include function from php even with the same double quote behaviour. The second example is nicer because it's relative to the root directory. In php i had to provide that myself by using a constant.

The next thing was how to get the php $_POST and $_GET globals. That was easy enough Request.Form["test"] gets you the posted form values, Request.QueryString["test"] gets you the url parameters. The Request object is like the $_SERVER global in php but the $_GET and $_POST are a part of it too which is cleaner than in php.

Now i got the basics i can make things work, i thought. c# is a strong typed language so you have to know which sort of content your variable will hold. You can guess Request.QueryString["test"] is a string but to compare it with a numeric variable you need to convert it.

int test = Convert.ToInt32(Request.QueryString["test"]);


The database


Now for the database connection. In php code there is morethan one way to do this but most of the database manipulation code now is object oriented and so is the c# code. The difference in c# is you have to use parametrized queries.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.Odbc" %>
<script language="c#" runat="server">
// variables
int number = 1;
string query = "SELECT name FROM testtable WHERE id = ?";
// prepare connection
OdbcConnection conn = new OdbcConnection("Driver={Mysql Odbc 3.15 Driver}; Server=localhost; Database=test; User=user; Password=password; Option=3;");
// prepare database connection
OdbcCommand com = new OdbcCommand(query, conn);
// add value to query string
com.Parameters.Add("",OdbcType.BigInt, 20).Value = number;
// start error handling
try
{
// open connection
conn.Open();
// get database result
OdbcDataReader reader = com.ExecuteReader();
// process database result
while(reader.Read())
{
textboxName.Text = reader.GetString(0);
}
// because it's a single result it can be shorter
textboxName2.Text = com.ExecuteScalar();
reader.Close();
}
// database error
catch (OdbcException ex)
{
labelMessage.Text = ex.Message;
}
// general errors
catch (Exception ex)
{
labelMessage.Text = ex.Message;
}
finally
{
conn.Close();
}
</script>
<html>
<head>
<title>test</title>
</head>
<body>
<p><asp:Label id="labelMessage" runat="server" /></p>
<p><input type="text" id="textboxName" runat="server" /></p>
<p><input type="text" id="textboxName2" runat="server" /></p>
</body>
</html>

To summarize the previous code.

  • Define classes needed for database manipulation

  • C# code

    • Prepare database manipulation

    • Display database result



  • Html/asp.net code



I will give you some rest now and i hope i helped other php programmers to take their first steps in asp.net/c#.

Sunday, January 14, 2007

New installation, different taskbar

I bought a new laptop and as a windows power user i adjust many things to make my experience easier. I found a few new things, for me, this time.

I never cared too much about all the toolbars in the taskbar except for the quicklaunch one. As an experiment i added the address toolbar. I found out it was good for launching websites, even with firefox as default browser, and for opening directories/folders without the trail of double clicks to get to the folder. As a bonus the address field remembers previous inputs.

I also tried if cmd would run and it did so i searched for a way to start other programs from the address bar. The solution i come up with is simple and expandable.

I created a batch file, a text file with the extension .bat, with only one line.

START c:\start\%1

The start command lets you run the program. The folder is one i made to put all my program shortcuts in. %1 is the first parameter of the batch file. I saved the file as start.bat in the c:\windows\system32 folder.
In the start folder i made a shortcut to 7-zip with that name so i can type in the address field 'start 7-zip' and the program starts. The only thing you have to do is to add shortcuts with the name you prefer to start other programs.

I like visual aids to search the window i'm looking for. In firefox i use the ctrl tab preview add-on and for programs i use the Microsoft Alt-Tab Replacement powertoy. I had downloaded the Visual Task Tips program but i hadn't installed it before. This shows a thumbnail screenshot of the program if you hover over the program in the taskbar. Because i'm using the address toolbar i put the taskbar on top which made the visual task tips more visible too. Now together with the Taskbar Shuffle program the taskbar has become more than a collection of clickable things.

Update : i changed from alt-tab replacement powertoy to TaskSwitchXP because the screenshots are bigger and it selects windows that aren't in the taskbar too.

Monday, January 01, 2007

Beginning python : function

Functions are another basic part of any programming language, without it you have to rewrite/copy all your code. And knowing how bad programmers are at copying it's not a good idea. And again python beats php for this part. functions are called definitions in python.

Building functions



function name($arg1,$arg2='optional',$arg3='optional'){
echo $arg1.' '.$arg2.' '.$arg3;
}

A simple function with 2 optional arguments that shows the values of the arguments. Now the same function in python.

def name(arg1,arg2='optional',arg3='optional'):
    print arg1, arg2, arg3


The differences in syntax are:

  • def instead of function

  • open function with a : character

  • indentation of codeblocks is necessary

  • the , character instead of the . character

  • close function with a white line


You also notice that you don't have to use a string with a space to separate the values of the arguments because the print function processes the white space in the code.

Using functions



name(1);
name(1,2,3);
name(1,'optional',3);

Above you can see a few function calls for the php function. The last call shows a pain in php. You have to know the default value of an argument to access an argument later in the list. To break this behaviour you can put your optional arguments in an associative array and sort them out in the function.

function name($arg1,$array){
echo $arg1;
$arg2 = ' optional';
$arg3 = ' optional';
if(count($array) == 0){
echo $arg2.$arg3;
}else{
foreach($array as $key => $value){
if($value != ''){
switch($key){
case 'arg2': echo $arg2; break;
case 'arg3': echo $arg3; break;
}
}
}
}
}

As you can see this extends the function code quite a lot and in this example you can only use it if the optional arguments don't depend on each other. Now lets look at some python magic.

name(1)
name(1,2,3)
name(1,arg3=3)

It are the same function calls and as you can see the last one sets the argument using a keyword/value pair. You can call all arguments like that but once you start setting arguments by keyword/value pairs you can't use the value only setting any more.

name(1,arg2=2,3)

This example will cause an error. Wrong keywords also raise an error.

The setting function arguments by using key/value pairs is a real programming relief.

First of all you don't have the remember the default values of optional arguments when you want to set an argument later in the list, you don't even have to add it to your function call.

Second reason : you don't have to remember the place of arguments in the list. Remembering the argument names is easy if you use consistent argument names, remembering where you put the arguments in the list is harder if you made the function six months ago and haven't used it a lot.

Third reason : you can use an associate array (dictionary in python speech) or even an array (list in pythonese) to set the arguments.
A dictionary is build by a key/value pair(s) surrounded by curly brackets.

listtest = [1,2]
name(*listtest)
dicttest = {'arg1': 1, 'arg2': 2}
name(**dicttest)

You notice the use of the single and double asterisk to identify the datatype to unpack it in the function.
This is great because you don't have put different function calls in if statements if the arguments for the function call are different. You can build different argument dictionaries or lists and call the function in the end. This makes the code more readable.