Data Binding

So what is data binding? It’s a technique to fill a Asp Control with values from a source. This source could be an XML, or a database. Why would you want that? To create dynamic websites of course!
With data binding techniques, you can separate the way you make data visible, and the actual data.
More posts about this, you can find by tag.

Possibilities for the different Data Bind Controls

Repeater DataList GridView
Templates X X
Styles X
Columns X
Select Items X

Templates

Yes, to show the items from the collection or datasource, we will use templates. This is how we transform the data, to for example, a link. Every Control in the Data Controls, has his own set of templates it can use. What each template does, and wich control use them, you can see in the table below:

Repeater Control DataList Control
HeaderTemplate X X Text above all the items
ItemTemplate X X Each item
AlternatingItemTemplate X X
SeparatorTemplate X X Between items.
FooterTemplate X X At the end of the collection.
SelectedItemTemplate X

Styles

Styles help you with the layout, the colours. What kind of styles are there? A list:

  • ItemStyle
  • AlternatingItemStyle
  • SeparatorStyle
  • HeaderStyle
  • FooterStyle
  • SelectedItemStyle
  • EditItemStyle

Example Observer Application: Traffic Lights

This is the post where you have all been waiting for (I hope J), after reading the informative post what an Observer Pattern is. If you have no idea what an observer is, you better start reading my previous theoretical post about the Observer Pattern.

First an overview of the application we are going to build in this post:

  • An application to create a traffic light who changes his colour
  • Easy expandable
  • Future equipped (easy to add changes)
  • Object Oriented
  • With the Observer Pattern

Stage 1: our Model Control View

Control Model View
Program.cs
TrafficLightApp.cs
Observable.csIObserver.cs
TrafficLights.cs
Light.cs
StartView.cs
Crossing.cs

Program.cs: The start file from the program. It creates a TrafficLightApp Object.
TrafficLightApp.cs: The main control of our program. This class covers for all the interactions. It also starts the views.

Observable.cs: This is the file where every model that needs to be observable will inherit from.
IObserver.cs: An interface where everything that listens to our Observable needs to implement.
TrafficLight.cs: Contains 4 lights (like on a crossroad).
Lights.cs: 1 light.

StartView.cs: A window forms class that has a button to create a new crossing.
Crossing.cs: Enables you to see a crossing with 4 lights.

Stage 2: Implementing the Observable and IObserver

The observable.cs should look like the following:


namespace ObserverExample
{
class Observable
{
private List allObservers = new List();
public void notifyObservers()
{
foreach (IObserver o in allObservers)
{
o.Update(this);
}
}
public void addObserver(IObserver o)
{
allObservers.Add(o);
}
public void removeObserver(IObserver o)
{
allObservers.Remove(o);
}
}
}

So basically, this class (Observable.cs) holds a list from Interfaces. When the notifyObservers() method is triggered, it accesses the method the method of all the interfaces.

So maybe, the IObserver.cs (interface) might like interesting for you to:


namespace ObserverExample
{
interface IObserver
{
void Update(Observable o);
}
}

Stage 3: Implementing the rest of the model

TrafficLights.cs and Light.cs, I will not show code extracts from them here, instead you are able (see bottom of the page) to download a zip file with the project included. You can check them there. Simple explanation what they are about? Light is just 1 light, and has a status which reflects the colour the lamp has (Red, orange or green). Each Light also has a changeLight method what changes the current colour to the next.

TrafficLights has a collection or list<> from 4 Lights. It has a method to change all the 4 their (colour) states. This class is also Observable, so it extends Observable.

Stage 4: Completing the control

I already (from the beginning) did some changes. I edited the Program.cs, to this:


static class Program
{
[STAThread]
static void Main()
{
TrafficLightApp Tla = new TrafficLightApp();
Tla.ExecuteProgram();
}
}

The TrafficLightApp() starts our StartView and also starts new windows, does the ‘control’, the hard work, makes it all works. If you wan’t to see this code, again, download the zip (at the bottom of this page).

Stage 5: Implementing the view

StartView.cs

I just created a really simple interface, with a button that enables to add a new crossing (That has 4 lights, and the ability to change the state). It looks like what you see at the right of this page.


namespace ObserverExample
{
public partial class StartView : Form
{
private TrafficLightApp tla;
public StartView(TrafficLightApp Tla)
{
InitializeComponent();
tla = Tla;
}
private void btnCreateNew_Click(object sender, EventArgs e)
{
tla.addCrossing();
}
}
}

Crossing.cs

Each Crossing contains 4 lights, and looks really nice. Pressing the next will change the status in the class light.cs. Then an notifyObserver() get’s done, and this view, wich is an Observer, will update.

Below you will find the most important parts of the code:

Update:

void IObserver.Update(Observable o)
{
Synchronize();
}

Synchronize:

public void Synchronize()
{
pnlPlaceholder.Controls.Clear();
foreach (Light light in lights)
{
Panel pnl = new Panel();
pnl.Width = 50;
pnl.Height = 50;
switch (light.Status)
{
case 0: pnl.BackColor = Color.Green;
break;
case 1: pnl.BackColor = Color.Orange;
break;
case 2: pnl.BackColor = Color.Red;
break;
case 3: pnl.BackColor = Color.Red;
break;
}
pnlPlaceholder.Controls.Add(pnl);
}
}

And the construct:

public Crossing(TrafficLights Tl, TrafficLightApp TLA)
{
this.tl = Tl;
this.tla = TLA;
lights = new List<Light>();
lights = Tl.Lights;
tl.addObserver(this);
InitializeComponent();
Synchronize();
}

The magic

The files

You can download the Source Files!

I’ve also created another zip file with the exe, and you can find it on the same link.

Sources

I’ve learned a lot from this in the book Design Patterns from O’Reilly. Also, the idea for this example, I got from my java lessons in Howest Simon Stevin, a high school in Bruges.

Creating a new Date or DateTime with ease in Java

For a school application in Java, we had to make a coffee application. The coffee application is a very small application, but trains a few very hard techniques like observer and composition.

Each time an amount of 1 – 10 coffees are made, a log entry has to be stored. With how much coffees there have been made, and the date time of it.

So I needed the date and time it was NOW, to store. Unfortunately I could’t find easy ways to do this, on line. That’s why I’ve searched a good way, and will share it with everyone, on eurekadesign.be!

[ad#Adsense]

Packages

There are a few packages you will need.

import java.util.Date;
import java.util.Calendar;
import java.text.SimpleDateFormat;

Date, is the variable type where in you can store the date and time. Calendar is a system to provide us with the current date and time, in the international calendar system. There is also a GregorianCalendar. SimpleDateFormat is a package to reformat and change our Date into a string.

This may look like a lot of packages, but believe, it is the easiest (and best) way to do it like this. And when you have already imported java.util.*, You do not have to add Date and Calendar any more.

The date!!

How to get the current date?

Date currentDate = Calendar.getInstance().getTime();

The getInstance() returns the current date and time, and the getTime() makes that you can store this in the Date. Next we need to create a custom format.

SimpleDateFormat fullFormat = new SimpleDateFormat("dd-MMMM-yyyy  HH.mm.ss");

Other formats?

Hell yeah! A litlle list and what it returns:

  • dd -> 07
  • MM-> 05
  • MMMM-> february (automatic in the language of local user)
  • yyyy-> 2010
  • yy->10
  • HH-> 8 (am pm format)
  • HHHH-> (0 – 24 format)

Format it to string

String stringTime = fullFormat.format(currentDate);

Test it

Now we simply send it to System.out.println to show that it works!

System.out.println(stringTime);

Now you will see that it works. You could also get our currentDate printed, but that will print a very long string with every information about the time, timezone, … .

Only date?

Just change the format to something like this:

SimpleDateFormat fullFormat = new SimpleDateFormat("dd-MMMM-yyyy");

With the SimpleDateFormat you can really do everything you would like!

Another date?

Of course it is possible. Here below you can see a code example to do that!

Calendar newTime = Calendar.getInstance();
newTime.set(year, month, date, hourOfDay, minute, second);

You have to use like (2007, 12, 35, 11, 30, 35) to add the date you want.

Example application

import java.util.Date;
import java.util.Calendar;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) {
Date currentDate = Calendar.getInstance().getTime();
SimpleDateFormat fullFormat = new SimpleDateFormat("dd-MMMM-yyyy HH.mm.ss");
String stringTime = fullFormat.format(currentDate);
System.out.println(stringTime);
}
}

Resources

http://www.devdaily.com/java/simpledateformat-convert-date-to-string-formatted-parse
http://www.tutorialhero.com/tutorial-70-java_date.php

Rounded Corners

Rounded corners, are just so beautiful. When you wanted to use them, you could or generate them with JavaScript, or make some pictures in photoshop and then putting them in the background.

This is very labour intensive, especially when you have a lot rounded corners, in multiple divs. Css3 again, can make the life of web designers so much more relaxing! Because rounded corners, will become a standard soon. And of course a few browsers implemented this yet! You just have to use the browser specific prefix. (More about this when you follow the link).

Continue reading “Rounded Corners”

Browser specific prefix

We are about to release a few tutorials how to use new Css3 tags. But before we would like to publish some information you have to know when you would like to use browser specific prefixes.

Css, is developed by w3c. And to make a long (boring) story short:

  1. Contributors (authors), people all around the world think about improvement and new tags.
  2. These ideas enter the w3c groups, and people comment it, making the idea workable.
  3. After a few phases, it becomes a standard, then browsers have to implement them into their css engine.

For the moment css2 is the standard, and they are working on css3.

But some browsers like to implement not yet standard tags, because they are so promising. But because they aren’t yet standard, and the definition of how they have to work might change a little (like the box-model), they put a browser specific prefix before the tag. The effect of this is, that you can use these tags yet, but not all the browsers will perform the tag.

Continue reading “Browser specific prefix”

Add hyperlink to the Bulleted List Control

This will be a very short tutorial, but still I couldn’t find any information relevant to the search: How to add hyper link to the bulleted list control.

Nevertheless this is pretty easy. We assume you want to do this in your Code-behind File, so you can add hyperlink in a list dynamically.

First create the BulletedList control, then you have to set his mode to hyperlink.

BulletedList BL = new BulletedList();
BL.DisplayMode = BulletedListDisplayMode.HyperLink;

Now that we have the control,the next code is how to add the hyperlinks. I will show how to add one. With a simple iteration you can add more, the way you might want it.

item.Text = "The text of the link";
item.Value = "the-url.aspx";
BL.Items.Add(item);

Good luck with your project!

Add items to the Bulleted List Control (in the code file)

My next tutorial will be a really short one. But still I have spent a really long time to find what I was looking. Maybe because it was way to easy?

I wanted to generate a BulletedList Web Control, in my code file. Inside a for-loop I wanted to add texts to my list.

[ad#Adsense]

To start, I dropped a PlaceHolder in my file.asp (The html file). Because I like drag and drop, I did it that way! You can find in your toolbox. If you don’t like that, just copy-paste the following text where you would like your BulletedList to appear:
<asp:PlaceHolder ID="ph1" runat="server"></asp:PlaceHolder>
After that it is time to open the code behind file. In the solution explorer, click at the plus, and then open the default.aspx.cs!

The first thing is to make our Place Holder accessible. Just behind:
public partial class Default: System.Web.UI.Page
But above:
protected void Page_Load(object sender, EventArgs e)
We type this code:
private PlaceHolder PH
{
get
{
return ph1;
}
set
{
ph1 = value;
}
}

We have to create the BulletedList outside the iterator. And inside we can add the items we want to the BulletedList. First my example:
BulletedList BltTest = new BulletedList();
foreach (XmlNode QuestionAnswers in Question)
{
BltTest.Items.Add(new ListItem(QuestionAnswers.InnerText));
}
PH.Controls.Add(BltQTest);

This is the code I did use. But maybe a more generic example helps you with your BulletedList problem!
BulletedList BltTest = new BulletedList();
for (int i = 0; i < 10; i++)
{
BltTest.Items.Add(new ListItem("This is the " + i + "th item"));
}
PH.Controls.Add(BltQTest);

Good luck with your BulletedList!

SEO Friendly URLS with .htaccess

Search engine optimization, or short, seo, means optimization so search engines will rank your site higher in their views. This will affect your visitors, in a positive way. What is very important for web shops, because more visitors, is more sales. Even sites with advertising will benefit from more visitors.

When we talk about seo friendly url’s, we ask ourselves the question which link will receive the most visitors:

  • http://example.com/index.php?content=article&sub=7
  • http://example.com/article/7/Title

Some articles say that easy readable urls only affect your visibility for search engines really small. But when a user has to choose between these urls, after searching for something, which link would he choose, do you think?

Open source web applications

Cms (content management systems) like joomla, drupal or wordpress, embed this possibility by default. Sometimes you just only have to activate it. If you use a cms, please do use these functions!

Self-made applications

.htaccess

Just like joomla, drupal and wordpress does, the easiest way to make the friendly urls possible, is to use a .htaccess file. (Note: This only works on the apache server)

This file makes it possible to set additional settings, you could have done in the apache configuration file to. But because most web hosting companies do not allow to edit that file, .htaccess files are really useful!

To create an .htaccess file, we advise to use the build in notepad editor from Windows. Just create a new file and save it as htaccess.txt (Because you can’t name it .htaccess in Windows). After completion of the file, you can upload it with your ftp client, of web ftp interface, and rename it to .htaccess!

These file has to be in your root from your site. An example of the directory (how it could be):

  • Pictures
  • Css
  • Files
  • .htaccess
  • index.php
  • info.php
  • contact.php

RewriteEngine

This is the built-in function from apache, who allows you to modify urls typed in the browser, and sending the right page back. Best of all, you can use this in your .htaccess!

Imagine you have the following .php pages:

  • pics.php
  • groups.php
  • contact.php

Wouldn’t it be nice to access these files with the following urls?

  • http://example.com/pics
  • http://example.com/groups
  • http://example.com/contact

Example of the .htaccess file to accomplish this.

Options +FollowSymLinks
RewriteEngine on
# Checks if the requested url path exists with .php, and if so, it allows the RewriteRule to do so.
RewriteCond %{REQUEST_FILENAME}.php -f
# Rewrite to append “.php” to extensionless URL-path
RewriteRule ^(([^/]+/)*[^.]+)$ $1.php [L]

This is possibly the easiest way to exlude the .php from your url.

What also is very common is the following: : http://example.com/info/ or http://example.com/blog/5/Title
The following example makes this possible.

RewriteEngine On
RewriteRule ^(.*)/(.*)/(.*) index.php?page=$1&sub=$2&$3

This example makes also the following url possible: http://example.com/forum/common/topic=7&active=3. This link will search for the following file: index.php?page=forum&sub=algemeen&topic=7&active=3.

The last example is a bit more complex, and could be an example for a download site.

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^files/([^/]+)/([^/]+).rar /download.php?cat=$1&file=$2 [NC]

This link (http://exaple.com/files/browsers/firefox) would reffer to donwload.php?cat=browsers&file=firefox.

Do not forget to addapt your links!

All the links you have, in your site, menu, … you have to modify! Remove the old links, and add the new ones, who do not have an extension, or are like files/browsers/firefox.

Otherwise, creating the .htaccess for seo reasons, is really stupid, because yahoo or google will think that it is duplicate content.

Images and css files

It might occur that suddenly your images are gone, or your css style. This is because for those links, (image links or css links) the RewriteEngine also tries to modify the links.

Lucky for us there is a simple way to block the RewriteEngine for folders where you put your images, css files or file folders. Just put the following RewriteCond just under RewriteEngine On

RewriteCond %{REQUEST_URI} !^/images/

Just add all the folders, and the job is done! You now have a much easier and more human readable site!

Sources

Thanks to the following sources:

http://httpd.apache.org/docs/1.3/howto/htaccess.html