Feeds:
Posts
Comments

Archive for the ‘Coding’ Category

Django is an excellent web-framework written in Python.

Here is a quick setup guide for installing Django and MySQL-python on Mac OS X Lion.

Setup Django

– Download latest Django here

– At this point I am assuming that you are familiar with the Terminal, so simply execute the following commands on your Downloads folder:

tar -xzvf Django-1.3.1.tar.gz
cd Django-1.3.1
sudo python setup.py install

Test Django installation

Type on the Terminal:

python
import django
print django.get_version()

Setup MySQL-python package

Download the latest MySQL (64-bit, tar archive) here

– Extract tar contents
– Rename folder to “mysql”
– Copy folder to /usr/local/
– You should now have mysql installed on /usr/local/mysql

Download the latest MySQL-python package here

Type on the Terminal:

tar -xvzf MySQL-python-1.2.3.tar.gz
cd MySQL-python-1.2.3

Edit site.cfg on your favorite text editor and change the mysql path as below: mysql_config = /usr/local/mysql/bin/mysql_config

You are now ready to build and install MySQL-python:

sudo python setup.py build
sudo python setup.py install

Edit your ~/.bash_profile, add the following line:

export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/

If you are already using MAMP you still have to follow the above MySQL installation process, as MAMP by default doesn’t include the required header files to build MySQL-python.
Moreover if you prefer MAMP, you don’t have to run mysql from /usr/local/mysql.
On your settings.py remember to set “127.0.0.1” as your preferred db host in case that “localhost” doesn’t work.

Test MySQL-python installation

Restart Terminal and type:

python
import MySQLdb

If you are not getting any errors at this point, then you are all good to go!
I’d suggest starting from the Django’s excellent introductory tutorial.

Read Full Post »

PHP: How to json_encode numbers properly

Here is a handy tip about PHP’s json_encode function.

In some cases numeric data may  appear as numeric strings, for example 1 as “1”. While consuming the json data on a client app that would mean an extra parsing to get for example an int from the string.

The solution is to simply use an extra option (JSON_NUMERIC_CHECK) on the json_encode function call:

<?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>

I have to point out that this option requires a PHP version of 5.3.3 or higher.

Read Full Post »

Using SQLite with .NET

Introduction

SQLite is a serverless SQL database engine.
It can be easily embedded into any software application, without the need to run any other database services on the host machine. The entire database engine and data are included in a single file, which is platform-independent.

Therefore depending on the project type, and data requirements, it could be a brilliant idea to use SQLite instead of another RDBMS system. Mozilla, Apple, Adobe and others are efficiently using SQLite.

This tutorial is showing how to connect and retrieve SQLite data from a .NET application.

Creating the tutorial’s database

We are going to create a new database, using one of the available SQLite management tools.
I am using wxSQLite+, which is pretty simple and doesn’t require any special setup.
However feel free to browse and maybe select an alternative one.

So, if running wxSQLite+ for the first time, from the Transaction menu, uncheck “Auto start transaction”.

We are going to create a new SQLite database,  called contacts.db.
Simply click on File -> Open/Create and save contacts.db on your preferred location.

sqlite_dot_net_1
Creating a table and adding sample data

Right click on Tables and select Create Table.

sqlite_dot_net_2
We are going to create a table named “friends” and add three columns (ID, name, phone). The ID will be the primary key of the table, having the autoincrement option ON.

sqlite_dot_net_3
If you are familiar with the SQLite SQL syntax, you can always use a “create table” command, instead of using the gui to create the table.

Now let’s add a couple of sample rows via SQL.

INSERT INTO friends
VALUES (null, 'Mary', '0900200200');

INSERT INTO friends
VALUES (null, 'John', '0800100100');

Do a “SELECT” query at the end to verify that the sample data have been successfully stored.

sqlite_dot_net_4

Getting the SQLite ADO.NET provider

SQLite can be used with any modern programming language, however an appropriate SQLite driver/wrapper is required to handle the database connection.

For .NET, I would recommend the SQLite ADO.NET 2.0/3.5 provider, which you can download here for free.

Creating a new C# Console Application

For the purpose of this tutorial, let’s create a new C# Console Application.
From the SQLite ADO.NET archive which you have downloaded, we only need the System.Data.SQLite.DLL file (\bin). So let’s just extract the dll and add a reference to it on our project.

The SQLite ADO.NET provider’s syntax is very similar to the corresponding Microsoft SQL Server ADO.NET provider’s syntax.

The connection string must contain the full path of the SQLite database file (contacts.db).

Here is the complete source code which is required to select data from the “friends” table and output the result on the Console:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;

namespace SQLiteTestCS
{
    class Program
    {
        static void Main(string[] args)
        {
            String connString = "Data Source=E:\\contacts.db";
            using (SQLiteConnection conn = new SQLiteConnection(connString))
            {
                StringBuilder query = new StringBuilder();
                query.Append("SELECT * ");
                query.Append("FROM friends ");
                query.Append("ORDER BY name");
                using (SQLiteCommand cmd = new SQLiteCommand(query.ToString(), conn))
                {
                    conn.Open();
                    using (SQLiteDataReader dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            Console.WriteLine(dr.GetValue(0) + " " + dr.GetValue(1) + " " + dr.GetValue(2));
                        }
                    }
                }
            }
            Console.ReadLine();
        }
    }
}

And the result should look like this:

sqlite_dot_net_5
Conclusion

As it was demonstrated on the tutorial, it is quite easy to setup an SQLite database, and use it as a data source on any .NET project.

Read Full Post »

Introduction

GridView is one of the most popular ASP.NET data controls.
It is most commonly used to display data coming from a database.
However, a GridView can also read and display data from plain XML files.

This tutorial is showing how to setup an XMLDataSource and associate it with a GridView.

XML data

Let’s start by creating a simple XML file for this demo.
The XML file stores contact data, a “name” and a “phone” number.

contacts.xml

<?xml version="1.0" encoding="utf-8" ?>
<contacts>
	<contact>
		<name>John</name>
<phone>0800100100</phone>
	</contact>
	<contact>
		<name>Mary</name>
<phone>0900200200</phone>
	</contact>
</contacts>

Transforming XML data

If you try to use the above XML file as it is with a GridView, you will get an error.
The required XML format is a bit different.
GridView is expecting to find for each row something like that:

<contact name="John" phone="0800100100" />

Editing our XML file is not an option, imagine having a few hundred contact entries.

The proper solution is to transform our XML data using XSLT.
XSLT (Extensible Stylesheet Language Transformations) is an XML-based language used for the transformation of XML documents into other XML or “human-readable” documents.

Here is an XSL file which will do the trick:

contacts.xsl

<xsl:stylesheet version="1.0" xmlns: xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:msxsl="urn:schemas-microsoft-com: xslt" exclude-result-prefixes="msxsl">
<xsl: output method="xml" indent="yes"/>
<xsl:template match ="/">
	<contacts>
      <xsl:apply-templates select ="//contact"/>
    </contacts>
</xsl:template>
<xsl:template match ="//contact">
	<contact>
		<xsl:attribute name="name">
			<xsl:value-of select="name"/>
		</xsl:attribute>
		<xsl:attribute name="phone">
			<xsl:value-of select="phone"/>
		</xsl:attribute>
    </contact>
</xsl:template>
</xsl:stylesheet>

Visualizing the transformed XML data

This step is entirely optional.
Follow it if would like to view the transformed XML data.

Create a new C# Console Application, and paste the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Xsl;

namespace XslTransformCS
{
    class Program
    {
        static void Main(string[] args)
        {
            XslCompiledTransform xslt = new XslCompiledTransform();
            xslt.Load("E:\\xml\\contacts.xsl");
            XmlTextReader reader = new XmlTextReader("E:\\xml\\contacts.xml");
            XmlTextWriter writer = new XmlTextWriter(Console.Out);
            xslt.Transform(reader,null,writer,null);
            Console.ReadLine();
        }
    }
}

Running it, will output in the console:

asp-net_gridview_xmldatasource_1

Creating and populating a GridView

Create a new Web Application, and add the contacts.xml/xsl files.
Drag/drop a GridView on the designer.

Click on “New data source …”:

asp-net_gridview_xmldatasource_2

Select “XML File”:

asp-net_gridview_xmldatasource_3

Browse for the contacts.xml, contacts.xsl files.

asp-net_gridview_xmldatasource_4

Customizing the GridView

This step is also optional.

You can click on GridView’s “Edit Columns” to change the column names, as by default they are set to the XML tag names.

asp-net_gridview_xmldatasource_5

Moreover you can select a GridView theme (click on “AutoFormat”) to get a better data display.

asp-net_gridview_xmldatasource_6

Here is a preview of the final result:

asp-net_gridview_xmldatasource_7

Read Full Post »

Introduction

Unit Testing verifies that the smallest bits of testable source code behave exactly as expected. Test-driven development is based on Unit Testing, and the use of automated testing frameworks.
The most popular Java testing framework is JUnit. Unfortunately JUnit cannot work in J2ME projects, since J2ME does not support Reflection. However J2MEUnit comes to the rescue, as it is based on the original JUnit source code, and it is designed to work with J2ME.
This article explains how to integrate J2MEUnit with Eclipse, and write a simple Unit test.

Setting up the environment

I am assuming that Java, WTK, Eclipse and MTJ are already installed and properly configured.
For J2MEUnit, simply download the j2meunit.jar file.

Creating a new MIDlet project

Create a new MIDlet project on Eclipse.

unit_testing_j2me_eclipse_1

Since this is a “hello world” type application, give it a simple name like “MobileUnitTest”.

Use the default properties on the Target Device:

unit_testing_j2me_eclipse_2

Creating a “Hello World” Midlet

Right click on the “src” folder and click on New -> Java ME MIDlet
Name it “HelloUnitWorld”, and use the “mobile.unit” as package name.

You should now see the empty auto-generated methods on the newly created MIDlet.

Let’s add some minimal code, in order to run our “Hello World” application.

1. Add a new private variable on the class with the following code:

private Display display;

2. Add the following code on the “startApp()” method:

display = Display.getDisplay(this);
String message = "Hello Unit World!";
TextBox textBox = new TextBox("HelloUnitWorld", message , 50, 0);
display.setCurrent(textBox);

Run the application and you should get something like that:

unit_testing_j2me_eclipse_3

Adding some testable code

We need to add some testable code for this tutorial.
So let’s create something simple, a new Java class, named “Calculator”, having the following code:

package mobile.unit;

public class Calculator {

	public int Add(int firstValue, int secondValue){
		return firstValue + secondValue;
	}

}

The method “Add” accepts two integer parameters, adds them, and returns the sum as integer.

Now we are going to modify the “startApp()” MIDlet method, to output a sum result.

//String message = "Hello Unit World!";
String message = String.valueOf(new Calculator().Add(3, 4));

If we run the application again, it should display the sum of 3+4:

unit_testing_j2me_eclipse_4

Adding the test code

Here comes the interesting part, adding the test code.

1. We need to reference the j2meunit.jar, which we have downloaded before.
Project -> Properties -> Java Build Path -> Add External JARs… -> Select j2meunit.jar

2. Create a new source folder named “tests”.

3. Create a new Java class on the “tests” folder with the name “CalculatorTests”, on a new package “mobile.unit.tests”.

Every test class has to import the j2meunit.framework, and extend the “TestCase”.
Moreover it should have two default new constructors.
Since there is no Reflection support, we need to manually add every test method on a “TestSuite”, and have a method that returns the “TestSuite” instance.
The test methods do not have to start with the “test” prefix, however it’s a good practice to have it.
If that sounds a bit confusing, please have a look on the complete CalculatorTests.java code:

package mobile.unit.tests;

import j2meunit.framework.*;
import mobile.unit.Calculator;

public class CalculatorTests extends TestCase {

	public CalculatorTests(){
		super();
	}

	public CalculatorTests(String name, TestMethod method){
		super(name, method);
	}

	public Test suite(){
		TestSuite suite = new TestSuite();
		suite.addTest(new CalculatorTests("testAdd", new TestMethod()
				{public void run(TestCase tc) {((CalculatorTests) tc).testAdd();}}));
		return suite;
	}

	public void testAdd(){
		assertEquals(10, new Calculator().Add(5, 6));
	}

}

The actual test code is contained on the “testAdd()” method.
We are trying to add 5+6, and expect a sum of 10, which is clearly going to fail.

Running the tests

Here comes the tricky part, we are going to use the j2meunit console TestRunner.
Go to Run -> Run Configurations -> Java Application -> New Configuration
Project: MobileUnitTest
Main class: j2meunit.textui.TestRunner
Arguments: mobile.unit.tests.CalculatorTests

If you fail to include the correct package on the Arguments, you are going to get an ugly error on the console:

TestRunner.main()
Could not create and run test suite

If everything goes fine, the console will output:

FAILURES!!!
Test Results:
Run: 1 Failures: 1 Errors: 0
There was 1 failure:
1) testAdd(mobile.unit.tests.CalculatorTests) “expected:<10> but was:<11>”

This is our expected test failure!

Let’s modify the “testAdd()” method to properly pass the test:

assertEquals(11, new Calculator().Add(5, 6));

Run it again, and get on the console:

OK (1 tests)

Conclusion

As I have demonstrated on this tutorial, J2MEUnit requires some effort to set up the tests, and add all required code.
However the result is really pleasant, as it gives you a fully working J2ME testing environment.
And that’s what matters most at the end day, because “Debugging sucks, Testing rocks!”.

Read Full Post »

Introduction

This is a tutorial on how to call a server-side ASP.NET method from a client-side JavaScript method.

If you are wondering when that could become useful, imagine the following scenario:

A Web Application having an implemented authentication system.
Users log in with their username and password.
At any point the user is able to log out by clicking on the respective “Log Out” button.
On the server-side, the log out action would trigger a cleaning up process of user’s temp data.

However, the user instead of clicking on the “Log Out” button, may simply close the browser window. Now since HTTP is a stateless protocol, the server-side cannot directly detect the user’s action. Therefore the client-side (browser) would have to notify the server that the user is closing the window.

A solution to this problem would be to call a JavaScript function when the client-side “onUnload” event is triggered. The JavaScript function would then be able to call the appropriate server-side method to clean up the data.

The exact required AJAX mechanism to accomplish that kind of communication is described on the “Hello World” project below.

Please note that for the purpose of this tutorial all methods are kept as simple as possible, so that you can easily modify them for your application.

1. Creating a new ASP.NET project

AJAX is required, thus a new “AJAX enabled ASP.NET Web Application” has to be created on Visual Studio 2005 or “ASP.NET Web Application” on  2008.

aspnet_server_side_from_client_side_1

2. Modifying the server-side code

Every server-side method that is called from the client-side, must be declared as “static”, and also has to be decorated with the [System.Web.Services.WebMethod] tag.

Now let’s create a simple function that returns a string value.

[System.Web.Services.WebMethod]
public static string Message()
{
    return "Hello from the server-side World!";
}

3. Modifying the ScriptManager

The “EnablePageMethods” attribute has to be added on the ScriptManager tag.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />

4. Adding a simple HTML button

We are going to add a simple HTML button rather than a server-side ASP.NET button control. The “onClick” event is going to be associated with the JavaScript function “GetMessage”.

<input onclick="GetMessage()" type="submit" value="Get Message" />

5. Adding the JavaScript code

Let’s add the “GetMessage” JavaScript function, which is going to call our server-side “Message” method.

function GetMessage() {
    PageMethods.Message(OnGetMessageSuccess, OnGetMessageFailure);
}

The “OnGetMessageSuccess” is the name of the JavaScript function that will be called if the request is successful. Whereas the “OnGetMessageFailure” will be called if an exception is thrown.

So let’s add these two functions:

function OnGetMessageSuccess(result, userContext, methodName) {
    alert(result);
}

function OnGetMessageFailure(error, userContext, methodName) {
    alert(error.get_message());
}

Please note that you can give to the functions any name you wish, as long as they match the PageMethods call parameters.

If there are no errors, the “OnGetMessageSuccess” will show a pop-up window with our server-side “Message” text. Else, the pop-up will have an exception message.

6. Running the Web Application

This is it, we are ready to run our Web Application. Everything seems to be working just fine on Internet Explorer (IE6 and IE7):

aspnet_server_side_from_client_side_2

However if we run it on Firefox (currently the latest version is 3.0.4) the pop-up will display the following message:

The server method ‘Message’ failed.

aspnet_server_side_from_client_side_3

7. Fixing the Firefox issue

We just need to modify the button’s onclick event a bit:

<input type="submit" value="Get Message" onclick="GetMessage();return false;" />

And this would do the trick:

aspnet_server_side_from_client_side_4

8. Here is the complete source code for your reference

Default.aspx

(Had to replace double quotes (“) with single quote (‘) in order to post it correctly.)

<%@ Page Language='C#' AutoEventWireup='true' CodeBehind='Default.aspx.cs' Inherits='AJAXEnabledWebApplication2._Default' %>

<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>

<html xmlns='http://www.w3.org/1999/xhtml' >
<head runat='server'>
    <title>Page</title>
    <script type='text/javascript'>
        function GetMessage() {
            PageMethods.Message(OnGetMessageSuccess, OnGetMessageFailure);
        }
        function OnGetMessageSuccess(result, userContext, methodName) {
            alert(result);
        }
        function OnGetMessageFailure(error, userContext, methodName) {
            alert(error.get_message());
        }
    </script>
</head>
<body>
    <form id='form1' runat='server'>
    <asp:ScriptManager ID='ScriptManager1' runat='server' EnablePageMethods='true' />
<div>
            <input type='submit' value='Get Message' onclick='GetMessage();return false;' /></div>
</form>
</body>
</html>

Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace AJAXEnabledWebApplication2
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        [System.Web.Services.WebMethod]
        public static string Message()
        {
            return "Hello from the server-side World!";
        }
    }
}

Comments are always welcome!

Read Full Post »

Introduction

This is a short tutorial on how to insert data with a subquery on SQL Server databases.
The reason I am writing about it is that the required syntax is not that obvious!

Sample tables and data

Let’s create two simple tables for this tutorial with the names ‘Customers’ and ‘Orders’.

CREATE TABLE [dbo].[Customers](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[name] [varchar](100) NOT NULL,
	[username] [varchar](20) NOT NULL
)
CREATE TABLE [dbo].[Orders](
	[order_id] [int] IDENTITY(1,1) NOT NULL,
	[customer_id] [int] NOT NULL,
	[order_date] [datetime] NOT NULL
)

We are also going to insert a new row on table ‘Customers’:

INSERT INTO Customers
VALUES ('John Smith','john.smith')

Inserting data with a subquery

The obvious syntax to insert data into the orders table with a subquery would be:

INSERT INTO Orders
VALUES ((SELECT id FROM Customers WHERE username = 'john.smith'), GETDATE())

However if you try the above query, you would end up with the following message:

Subqueries are not allowed in this context. Only scalar expressions are allowed.

The correct syntax to accomplish our task is:

INSERT INTO Orders
SELECT id, GETDATE() FROM Customers
WHERE username = 'john.smith'

or if you would like to specify the columns:

INSERT INTO Orders (customer_id, order_date)
SELECT id, GETDATE() FROM Customers
WHERE username = 'john.smith'

Conclusion

Hope you find it useful, especially if you are getting the “Subqueries are not allowed …” error.

Read Full Post »

Introduction

This tutorial describes the required steps needed to be followed for logging with log4net on Oracle 10g.

Prerequisites

– Oracle 10g (could also be working with Oracle 11g, however I haven’t tried it – please leave a comment if you try it)
Oracle Data Access Components for Windows (ODAC) / (ODP.NET)
log4net (1.2.10)

Step 1

Creating the SQL table, where all logging messages will be inserted.

CREATE TABLE "LOG4NET"
	("LOG_ID" NUMBER NOT NULL ENABLE,
	 "LOG_DATE" DATE,
	 "LOG_LEVEL" VARCHAR2(10),
	 "LOG_IDENTITY" VARCHAR2(100),
	 "LOG_MESSAGE" VARCHAR2(4000),
	 "LOG_EXCEPTION" VARCHAR2(4000),
	 CONSTRAINT "LOG4NET_PK" PRIMARY KEY ( "LOG_ID" ) ENABLE
	 )
/
CREATE SEQUENCE "LOG4NET_SEQ" MINVALUE 1 MAXVALUE 999999999999999999999999999
	INCREMENT BY 1 START WITH 1 NOCACHE NOORDER NOCYCLE
/

LOG_ID: This is the PK of the table, it is getting an autonumber value from the sequence “LOG4NET_SEQ”.
LOG_DATE: Logging date for each message.
LOG_LEVEL: log4net’s level (DEBUG, ERROR etc.)
LOG_IDENTITY: Username (Web or Win32 application user)
LOG_MESSAGE: The logging message, or exception message.
LOG_EXCEPTION: Exception’s full stacktrace.

You can always modify this table to include more information according to your logging needs, however you will also have to modify accordingly the configuration file (Step 2).

Step 2

Setting the web.config (Web application) or app.config (Win32 application).
Here is a sample app.config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
<log4net>
  <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
      <bufferSize value="1" />
      <connectionType value="Oracle.DataAccess.Client.OracleConnection, Oracle.DataAccess, Version=2.102.2.20, Culture=neutral, PublicKeyToken=89b483f429c47342" />
      <commandText value="INSERT INTO LOG4NET (LOG_ID, LOG_DATE, LOG_LEVEL, LOG_IDENTITY, LOG_MESSAGE, LOG_EXCEPTION) VALUES (LOG4NET_SEQ.nextval, :log_date, :log_level, :log_identity, :log_message, :log_exception)" />
<parameter>
<parameterName value=":log_date" />
        <dbType value="DateTime" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%d{dd/MM/yyyy HH:mm:ss}" />
        </layout>
      </parameter>
<parameter>
<parameterName value=":log_level" />
        <dbType value="String" />
        <size value="10" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%level" />
        </layout>
      </parameter>
<parameter>
<parameterName value=":log_identity" />
        <dbType value="String" />
        <size value="100" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%identity" />
        </layout>
      </parameter>
<parameter>
<parameterName value=":log_message" />
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%m" />
        </layout>
      </parameter>
<parameter>
<parameterName value=":log_exception" />
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%exception" />
        </layout>
      </parameter>
    </appender>
    <root>
      <level value="All"/>
      <appender-ref ref="AdoNetAppender"/>
    </root>
  </log4net>
</configuration>

The “ConnectionType” is using the Oracle’s ODP.NET dll (Oracle.DataAccess.Client.OracleConnection).
Therefore make sure that you have it referenced on your project.

Step 3

Configuring log4net on source code, as well as setting the connection string. Here is the sample code (in VB.NET) required for a Win32 app:

Private log As log4net.ILog = log4net.LogManager.GetLogger(Me.GetType())
	Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        log4net.Config.XmlConfigurator.Configure()
        Dim h As log4net.Repository.Hierarchy.Hierarchy = log4net.LogManager.GetRepository()
        Dim adoAppender As log4net.Appender.AdoNetAppender = CType(h.Root.GetAppender("AdoNetAppender"), log4net.Appender.AdoNetAppender)
        adoAppender.ConnectionString = "[your connection string]"
        adoAppender.ActivateOptions()
        log.Info( "hello world!" )
    End Sub

You can also set the connection string directly on the .config file (connectionString tag), however that would render the database username/password visible to anyone who has access to the .config file.

Well, there aren’t any more steps, if you have done everything right, check the database table for the “hello world!” message!

Conclusion

Logging is crucial for every application, and log4net is one of the most recommended logging frameworks. As demonstrated above, it is quite easy to set it up, and start logging from your .NET application. You can find more configuration examples here.

Read Full Post »

This is my second article about the Google App Engine.
On the previous article, I have gone through the installation/setup process, and a “Hello World” project.

Introduction

While developing web applications it is always a good practice to separate the presentation layer from the application logic. This approach is recommended for all modern web frameworks, whether that is PHP, ASP.NET, Google App Engine etc.

During the design time, different people/teams may work on each layer, i.e. web designers on the presentation layer, and programmers on the code-behind. Maintenance will also be easier, as it could only involve the update of a single layer.

In our case, the presentation layer is going to be a simple HTML file, and the application logic a Python script file.

Coding – Part 1

Create a new folder on your hard disk called “template”.

Create the “template.py” file with the following code:

import wsgiref.handlers, os

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

class MainPage(webapp.RequestHandler):
    def get(self):
        html_title = 'Google App Engine - Template'
        html_body_text = 'This is a simple demo of the templating system.'

        template_values = {
            'html_title': html_title,
            'html_body_text': html_body_text,
            }

        path = os.path.join(os.path.dirname(__file__), 'index.html' )
        self.response.out.write(template.render(path, template_values))

def main():
    application = webapp.WSGIApplication(
                                    [('/', MainPage)],
                                    debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
    main()

On the above code we are declaring two variables, named html_title and html_body_text.
The html_title will form the HTML title content, while the html_body_text is going to be printed on the HTML body.

Now, let’s include the variables on the HTML file, named “index.html”:

<html>
<head>
    <title>{{ html_title }}</title>
</head>
<body>
    
{{ html_body_text }}
</body>
</html>

We also need to create the configuration app.yaml file with the following code:

application: template
version: 1
runtime: python
api_version: 1

handlers:
- url: /
  script: template.py

Now let’s start the development web server by typing in the command prompt:
“dev_appserver.py D:\GoogleAppEngine\template”
Please replace the “D:\GoogleAppEngine\template” with the path of your “template” folder.

Point your web browser to http://localhost:8080/ , and you should see something like the following output:

Coding – Part 2

Now we are going to further improve our presentation layer by adding a CSS file.

Create a subfolder named “stylesheets” inside the “template” folder.

Create the “template.css” stylesheet file with the following code:

p {
    color: #FF0000;
}

Edit the “index.html” in order to include the CSS file:


<html>
<head>
	<title>{{ html_title }}</title>
	<link type="text/css" rel="stylesheet" href="/stylesheets/template.css" />
</head>
<body>
	
{{ html_body_text }}
</body>
</html>

Add the following handler on the app.yaml file:

- url: /stylesheets
  static_dir: stylesheets

Save all files, refresh your browser, and you should see the following output:

Conclusion

Google App Engine template system is based on Django’s template engine, and as demonstrated above, it is quite easy to be implemented.
You can find a more complicated example on Google App Engine’s template help page, using class properties and if/else logic on the presentation layer.

Read Full Post »

Introduction

Lately I have been reading quite a lot of articles about Google App Engine, and I just couldn’t resist trying it out myself.

Google App Engine enables you to build web applications on the same scalable systems that power Google applications.

If this is the first time you are hearing about the Google App Engine, it would be a good idea to read this introductory document.

The following post is based on the official “Getting Started” guide.

Setup

Setup is quite easy, all you need is the Google App Engine SDK, and the Python Runtime software.
I am using Windows XP, so I have downloaded the “GoogleAppEngine_1.0.1.msi” and “python-2.5.2.msi” installers from the above links.
Both of them are available for Windows/Mac/Linux, so you can download the required files according to your Operating System.
Installation is also straight-forward, I have installed both of them with the default options. There was no need to edit config files or do something else.
Google App Engine even sets a “Path” Environment Variable in Windows to make the development web server more accessible.

Coding – Part 1

Here comes the fun part, let’s find out how to build the “Hello World” application.

Create a new folder on your hard disk called “helloworld”.

Fire up your favorite text editor, mine is Notepad++, and paste the following code:

print 'Content-Type: text/plain'
print ''
print 'Hello World!'

Save the file as “helloworld.py” inside the folder “helloworld”.

Create a new text file called “app.yaml” in the same folder with the following contents:

application: helloworld
version: 1
runtime: python
api_version: 1

handlers:
- url: /.*
  script: helloworld.py

The “app.yaml” is the configuration file, you can find more information about it here.

Now let’s start the development web server by typing in the command prompt:
“dev_appserver.py D:\GoogleAppEngine\helloworld”
Please replace the “D:\GoogleAppEngine\helloworld” with the path of your “helloworld” folder.

Point your web browser to http://localhost:8080/ , and you should see something like the following output:

Now change the “helloworld.py” a bit:

print 'Content-Type: text/plain'
print ''
print 'Hello World! - Google App Engine rocks!'

Save it, refresh your browser, and you should see:

The development web server is monitoring the project files, thus you can automatically view the changes!

Coding – Part 2

On this second part we are going to use the included, with the SDK, “webapp” framework.

Let’s create a new Python script file called “helloworld2.py” with the following contents:

import wsgiref.handlers

from google.appengine.ext import webapp

class MainPage(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.out.write('Hello World from the webapp framework!' )

def main():
  application = webapp.WSGIApplication(
                                       [('/helloworld2', MainPage)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()

We also need to modify the configuration file (app.yaml), in order to specify the url that is going to handle the second script:

application: helloworld
version: 1
runtime: python
api_version: 1

handlers:
- url: /
  script: helloworld.py

- url: /helloworld2
  script: helloworld2.py

As you can see, we changed the first handler (/.* -> /) to respond only to the root directory.
Also we added a second handler to respond on the /helloworld2 path.

Navigate your browser to http://localhost:8080/helloworld2 and you should see:

You can find here more information about the “webapp” framework and how to use it.

Conclusion

Well that was just the beginning to an exciting new way of developing web applications.
The API is under heavy development, and definitely you have to spend some time in order to get familiar with it, and build a real-world application.

Read Full Post »