Calculate age from birthday with MySQL

By Nisse Pettersson at May 20, 2010 11:15
Filed Under: Code
Share on Facebook

The e-date service i'm running has no statistics on the average age of it's members. logo-mysql-110x57This is something I feel is needed and so I made my own.  This query will handle the leap year. Replace [COLUMN] with the field with birthdate and [TABLE] with the table name.

SELECT EXTRACT( YEAR
FROM (
FROM_DAYS( DATEDIFF( NOW( ) , [COLUMN]) ) ) )
 +0 AS age
FROM [TABLE]

This will give you the age of all users and if you just need the average age use the following query.

SELECT AVG( EXTRACT( YEAR
FROM (
FROM_DAYS( DATEDIFF( NOW( ) , [COLUMN]) ) ) )
) +0 AS age
FROM [TABLE]

 

Technorati-taggar:


Progressbar in C# with backgroundworker

By Nisse Pettersson at February 11, 2010 12:20
Filed Under: Code
Share on Facebook

I'm developing a application where there are some time consuming database activity and I need to show the user that the application is running and not crashed. You would also want the GUI thread to be free so the user can move the window and navigate the menus.

I found a blog with a simple example of how you can use a backgroundworker for this. *



Implement ObjectListView in your Winforms application

By Nisse Pettersson at January 02, 2010 06:02
Filed Under: Code
Share on Facebook

I'm developing an inventory software and I was using a listview component. But I do need to be able to change the sorting. Microsft have whitepaper on how to do this. Started reading and then gave up. Did a google search and found ObjectListView. Love at first sight!

This DLL-package is what I was looking for and it's a really nice application. NOTE: This is an open source and is licensed under GPL

Since the getting started guide on their homepage is awsome i'll just link to that page. Get it on!

Technorati-taggar: ,,


Solution for error: BlogEngine is not defined

By Nisse Pettersson at December 31, 2009 11:41
Filed Under: Technical, Code
Share on Facebook

I've upgraded my blog to BlogEngine 1.5.0.7 and then I got a Java Error saing BlogEngine is not defined. The solution is the following.

Download the latest version from codeplex.
Extract blog.js and open it in your favorite editor and look at the code.

// global object
BlogEngine = {
    $: function(id) {
        return document.getElementById(id);
    }

 

The first row is to be deleted, so the start of the file will look like this.

BlogEngine = {
    $: function(id) {
        return document.getElementById(id);
    }

 

Upload the file and restart your .NET application. Edit your Web.Config to get the server to recompile the site.

Technorati-taggar: ,


Howto implement google maps and a marker

By Nisse Pettersson at December 09, 2009 05:59
Filed Under: Code
Share on Facebook

I'm developing a site for a customer who wish to have  a map of his stores and a marker as well. Googles new v3 API of google map is what i'm using since it's newer and hade a nice look and feel than v2.

In my application i'm reading the coordinates from a database but for this example we will use static. Paste the following code in your <HEAD> secion.

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
 <script type="text/javascript">
  function initialize() {
    var myLatlng = new google.maps.LatLng(<? echo $clsShop->LatLong;?>);
    var myOptions = {
      zoom: 13,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    
    var marker = new google.maps.Marker({
        position: myLatlng, 
        map: map,
        title:"Hello World!"
    });   
  }


</script>

In your <BODY> tag we will load the map with the onLoad command and unload it when we leave. Use the following tag.

<body onload="initialize()" onunload="GUnload()">

 

Then all you need to do is to create a <div> with id = map_canvas where you wish to place the map. You can use the following example.

<div id="map_canvas" style="width: 220px; height: 220px"></div>

 

Then you're all set and google maps will load. If not you might need sign up for the google API. For more examples you can check out googles own example gallery



PHP Classes guide - Part 1

By Nisse Pettersson at November 19, 2009 08:07
Filed Under: Code
Share on Facebook

I'm working as a technician and as a programmer and 90% of my programming is done in PHP which is a great language but some see it as an amateur language. This language is for me a great language to learn and it's also a very capable language. Facebook is a great example of an application running PHP. This guide however is not for beginners since there is already a lot of beginner guides out there. This is for programmers who is ready to take the next step and how shuffle more than 5 values to and from a database.

The first big site i developed the SQL statements where a headache and after a while I found out that classes would be something that might come in handy. So read on and please comment if, makes the guide better and helps people to make PHP a better language.

The issue with big SQL-strings is that you sometimes get lost in them, especially the INSERT strings. An example below.

INSERT INTO tbl (var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, var11, var12, var13,var14) VALUES ($var1,$var2,$var3,$var4,$var5,$var6,$var7,$var8,$var9,$var10,$var11,$var12,$var13,$var14)

This is a messy code and we need a way of loading our variables and then just hit save.

The solution

Classes is a great way of manage you data and to have a decent structure in your code.
In a nutshell we are going to create a class, give it some properties, function and then load and save our data to a database.

Let's go!

I like using the car as an example so we are going to use that. A car have some characteristics like make, model, colour, engine and so on.

If we would build us a car inventory we need a class called car. So create a new file called classes.php and in that file we need to create a function that initialize a connection to our database. In this example I will use a ODBC connection. but you can use what ever connection you like, as it returns a connection handle.

function db_conenct()
{
	$conn_id = odbc_connect("ODBC-DSN", "", "") or die ("Could not connect");	
	return $conn_id;
}

Then we will create the class car and the properties we wish to use is, make, model, colour. We also need a way of keeping track of our items in the database so we need to add Id and then I always have a Deleted column since it's easier to set to false again then to restore database from backup. Insert the following code in our classes.php

class Car
{
	var $Id;
	var $Make;
	var $Model;
	var $Colour;
	var $Deleted;
	
	var $connection_id;
	
	function Car($conn)
	{
		$this->connection_id = $conn;
	}
		
}

Notice the function with the same name as the class, this is called a constructor and is run every time you load a create a class in your code. But we need to insert and read some data from our class. So we need 4 functions and then we can do whatever we want with our car data. First of we need to get data for a specific car and we use the Id column to identify our cars. Insert the following function.

	function GetCarById($id)
	{
		$sql = "SELECT * FROM tblCars WHERE Id = $id";
		$result = odbc_exec($this->connection_id, $sql);
		$data = odbc_fetch_array($result);
		
		$this->Id = $data['Id'];
		$this->Model = $data['Model'];
		$this->Colour = $data['Colour'];
		$this->Deleted = $data['Deleted'];
		$this->Make = $data['Make'];
	}

This function send a query to the database and get a result back, loads the current class's variables from the database, notice that we write $this->Id instead of $Id or $car->Id. The command $this-> tells php that THIS is for THIS instance of the class car. It is very important that we use the $this-> command. Next we need a function to get all the cars since we probably would like to make a list of cars.

Here comes a nice way of doing business, we only get the Id from the database and return all the data in an Array. We then use the Id number to get the actual database row. Go ahead and insert the following function in our class.

	function GetAllCars()
	{
		$sql = "SELECT Id FROM tblCars Where Deleted = false Order by Make DESC";
		$result = odbc_exec($this->connection_id , $sql);
		$i = 0;
		while($data = odbc_fetch_array($result))
		{
			$DataArray[$i] = $data['Id'];
			$i++;
		}
		return $DataArray;
	}

Notice the SQL statement we select just Id and we filter out the deleted rows and get an array in return. Now we can move on to our main page where we list our cars.
Create a file and a table with the columns (make,model,colour).
On top of our file we need to include our classes.php and this is done with require_once():. Go ahead and add our classes.php on row 1.

Below you have an example showing how this works.

<html>
<head>
<title>Nisses class example</title>
</head>
<body>
<table border="0">
<tr>
	<td>Make</td>
	<td>Model</td>
	<td>Colour</td>
</tr>
<?
$clsCar = new Car(db_connect());
$DataArray = $clsCar->GetAllCars();

for($i = 0; $i < count($DataArray);$i++)
{
	if($i % 2 == 0)
	{
		$bgcolor = "#FFFFFF";
	}
	else
		{
			$bgcolor = "#D8D8D8";
		}
	$clsCar->GetById($DataArray[$i]);
	echo "<tr bgcolor=" . $bgcolor . ">";
	echo "<td>" . $clsCar-Make . "</td>";
	echo "<td>" . $clsCar-Model . "</td>";
	echo "<td>" . $clsCar-Colour . "</td>";
	echo "</tr>";
}
?>
</table>
</body>
</html>

The row $clsCar = new Car(db_connect()); creates a connection to our database. Remember the function db_connect that returns a connection handle. It's then taken care of by our constructor and stored in the class variable $this->connection_id . We have now a class called $clsCar and what we need to do is to get a list of all non deleted cars. We need to call our function GetAllCars and store the returned value in an array. $DataArray = $clsCar->GetAllCars(); does that for us. We now have ourselves an array of Id's on which we can query the database for actual items. So we loop the array until it ends and print out the data. Notice that we don't use the $this-> anymore. We are only interested in the instance we created $clsCar and only for this user.

I've been using this method for getting data from tables for a few years now and it proves to be very scalable since all we need to do if you like to add a property there is not that much work in doing that. Next step is to insert and update our data. The next step is in the works, stay tuned!

Technorati-taggar: ,,,,


Insert large amount of data in MSSQL field with PHP

By Nisse Pettersson at May 24, 2009 04:21
Filed Under: Code
Share on Facebook

There is some what of a problem when inserting huge amounts of text in a textfield. I've working on a site right now where the user will edit the whole contet of the page itself with the help of FCKEditor.
I started with an Access Database and outgrew that one in 20minutes, exported the database to a SQL 2005 database. The PM value in Access will be ntext in SQL, this is wrong and it should be just text. My next issue is that the maxtextsize in php is to small, so we need to change that in the php.ini

mssql.textlimit = 65536,
mssql.textsize = 65536;

Then you also need to change the textsize of the queries insert this code before the queries or if you work with classes you could add this code to the constructor.

mssql_query ( 'SET TEXTSIZE 65536' , $myConn ); // myConn is the connection identifier for the connection.
ini_set ( 'mssql.textlimit' , '65536' ); // Not needed but I set them anyway
ini_set ( 'mssql.textsize' , '65536' ); // Not needed but i set them anyway

 

This solved this for me, i'm not sure how this works with MySQL, if you do, please leave a comment.



Return affected rows from a stored procedure

By Nisse Pettersson at May 19, 2009 01:49
Filed Under: Code
Share on Facebook

I'm working on a site where I use alot of stored procedures and I wish to log the results of the datamining. So I would like to get affected rows sent back from the stored procedure. I googled and found this thread which had a comprihensive exampel.http://www.ozgrid.com/forum/showthread.php?t=79766

Just a small tip Smile



Microsoft Provisioning System(MPS) control panel

By Nisse Pettersson at May 14, 2009 07:06
Filed Under: Technical, Code
Share on Facebook

I've recently deployed an MPS installation for hosting at our company. There is a small ASP.NET site that's included in this software but it's not sufficient to use in a production enviroment. There is alot of control panels out on the market but they are expensive. For us using smaller setup we have the choice of using provtest.exe and manualy edit the XML-files so we can edit the information in the provisioning system.

I've started development for a controlpanel that's supposed to be easy and without support for sharepoint. The main idea for this application is to add a new organization to the Exchangeserver, edit users, edit plans and handle the accounts in the Active Directory. The application is not ready and i would not even say that it's in Alpha stage but there is some screens and at the moment you can edit som settings for each Exchange account. The goal is to have something ready for release as a free application. But there are som major goals overcome first. Make it fully functional as a Exchange Account editor and edit the source code so it's not embaressing to release

Start up view. Select customer and press get all to query the MPS server.

 

Edit user view

 

Edit aliases for a user.

There is work being done but it's slow. I'm learning winforms and on the same time working with MPS and Provisioning databases. Exciting but slow progress.

I started using the provtest.exe and genereated XML-files. I knew that i could use the SDK supplied from Microsoft but did not know how to make it work. I've got alot of help in the asp.net forums and now i use DLLs from Microsoft.