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.

Advertisements

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 »

Older Posts »