Web Development Good Practices

>> Thursday, May 3, 2012

In this post I'll try to add some good practices which are nice to have in mind while developing for the web.
Developing for the web includes varios different technologies, this is what I like about web developing, it includes HTML, CSS and Javascript for the client, then a programming language like PHP or C# for the server, let's not even get into the server technology, like Linux + Apache, or Windows + IIS, and data storage like MySQL, Postgree, MSSQL, or even NoSQL databases like MonoDB and Cassandra.

I'll talk about the most common technologies and the ones I know, of course.

HTML

It's very important to follow standards, in every technology, but in web is really important, as your app is released to the masses and HTML is one of the things everyone can see. If you output bad HTML the browser might render it just fine, but it might break in some browsers, also, it's not good for a professional site to have malformed HTML, or deprecated HTML.

If you are starting a project from scratch you should consider using HTML 5, it's already supported, modernizr helps quite a bit for unsupported browsers, it's the new standard and it will look good on your portfolio.

HTML 5 isn't really hard to learn, it's simpler and nicely evolved from the old HTML, so you should really give it a try.

CSS

CSS hasn't changed much, and support for CSS 3 isn't quite implemented correctly yet, so using CSS 2/2.1 is what you should do by now, but that doesn't mean you can't extend it!
LESS is there just for that, it takes CSS and adds a bit of logic inside, like variables, nested rules and more.

You can compile it to standard CSS or just write LESS CSS and use Javascript to interpret it, up to you, Javascript is really supported right now, so it's safe enough to use it.

Do not use flash!

There are very few things you can do with flash that you can't with HTML 5 + Javascript, and to be honest, I can't think of one right now, with HTML 5 + Javascript you can do a Video Player (like youtube does), Image Manipulation, you even have sockets now! There's really no need to use a privative plug in with security issues, you can just use the browser, and the user won't need to install anything nor compromise his security.

Javascript

When using Javascript you might want to use JSHint (or the more strict and mean, JSLint) to check your code, writing code that follows JSHint ensures it follows basic good practices.
Also you should use a library like jQuery, it ensures cross-browser compatibility, making the biggest pains of Javascript go away!
Also! It's important that you understand how Javascript really works, Object Orientation with Javascript can be a bit tricky.
Once you understand this little language it's easy to love it.

Client Side Frameworks

There are several frameworks for this, basically what these frameworks do is give you a nice solid base so you can write cross-browser and even cross-platform (PC, Tablet, Mobile) applications with less effort.
These frameworks give you a base style and/or script for you to be as productive as possible.
My favourite right now is Bootstrap, a lightweight open source framework by Twitter. It gives you a nice CSS reset, fonts adjustments, and a grid system.
It also defines a nice set of components you can use on your site, some with CSS, and others with Javascript (which depend on jQuery).
Using a framework like Bootstrap is highly recommended.

Server Side Technologies

This is sometimes personal taste, and sometimes more technical. The most common technology for web applications today is probably LAMP (Linux, Apache, MySQL and PHP), but there are other technologies which are getting quite popular too, like RoR, Django and ASP.NET MVC.
All of them are free to use, ASP.NET of course requires IIS 7 and a windows environment, but hiring a windows hosting isn't much more expensive than a linux one, nevertheless, if you plan on hosting your own app or are afraid it will scale a lot, licences might be a problem, Azure might be a workaround for this, as you don't pay licences at all, just the resources your site uses, but learning a whole new technology just you host your application there it's not really a big advantage.
Most of the time though, you can just choose whatever you feel like using, and its more fun to use for you, PHP, Django, RoR and ASP.NET MVC all handle themselves pretty nicely, performance won't be a real issue, you should worry about the speed of development and your own fun while developing.

Comparing PHP to RoR is quite unfair though, as RoR is a framework and PHP is a language, if anything, we could compare PHP to Ruby, but you won't ever want to use plain ruby for a web application, what you want is a framework, you can either make one yourself or use a well-tested one.
So for PHP I recommend using a MVC Framework, like CodeIgniter, CakePHP, Symfony or Yii.
What PHP really lacks is some kind of advanced functionality, of course, PHP does have that, but for example, if you want advanced caching, you might need to install APC, or XCache, or memcache, on ASP.NET MVC you just use the standard cache you are given with the framework, this makes PHP a bit harder to use, but more versatile.
Note: StackOverflow uses redis for it's cache.


It's important to note though, most of the time you won't really need to worry much about the server-side technology, that beeing what database engine you use, how you cache, what language or framework you use, what you do have to have in mind is the client side, that's why using something like Bootstrap is awesome.

If you do care about the server, then you can start worrying about using MySQL, Oracle, Postgree or MSSQL, or mixing standard SQL with a NoSQL database like MongoDB, Cassandra or Redis, or mixing different languages, like making your own modules for PHP in C, or use Facebook's HipHop PHP to compile your PHP code to C++, but that's far beyond the scope of this entry.

What I want to emphasize is, use whatever you find fun, and pay special attention to the user interface, follow the standards and you will be fine, they are there for a reason.

Read more...

Javascript Clean HTML

>> Tuesday, April 24, 2012

Normally when using WYSIWYG editors liks CKEditor, you allow the user to enter poorly formatted HTML, this isn't really a big issue most of the time, but you have to be very careful with this, for example, if you allow them to enter any html, they could easily send a tag with a custom request, and XSS injection.

This isn't about security but a little help with managing the generated HTML, I needed a function to clean empty tags, thanks to the awesomeness of Regular Expressions, I ended up with this little guy


String.prototype.htmlTrim = function () {
        return this.replace(/<(p|div|span|b|u|i|strong|em|h\d+)>\s*\n*\t*[ ]*\s*\n*\t*<\/\1>/, '');
};

That will clean all empty tags, but it won't fix much more. Anyways! I think this might be helpful for some people so I'm sharing it here.

Usage is


myString.htmlTrim();

Read more...

Object Oriented Javascript 1: Inheritance

>> Monday, April 9, 2012

Pretty Javascript!

Javascript is such a different language, I wouldn't call it hard to use or understand, but we are used to different and more structured languages, Javascript gives you so much freedom, you end up doing whatever you want, and not quite understanding what's really going on, personally I find this frustrating, as I really want to understand everything I do, afters years of barely using Javascript for web development, for several reasons I decided to go a bit deeper on this, and find out what's really going on with my code.

When we think about object orientation we normally think of languages like Java, or Ruby, in which a Class defines how an object will behave, and you can then implement inheritance by just adding a "extends" to that class definition.
This implementation of Object Orientation is based on classes, Javascript on the other hand uses Prototypes.

Before Prototypes... Let's talk about the new keyword


Hey hey, stop right there my fellow reader, let's take a moment to relax and go back to the basics, let's talk about the new keyword.
In Java, for example, the new keyword takes a class, and creates/instantiates an object based on that class, the object has all the definitions the class specified.
But in Javascript, we have no classes! What on earth does the new keyword do then?
Well the new keyword can only be used on function definitions, and that function will act as a constructor for our new object.

But there are other ways of creating objects, why bother using new? Well let's see! Let's make some objects

var a = {x:12};
var b = {x:12};

As you can see, we have two objects, a and b, they both hold the same definition, but its repeated, what if we wanted to create 10, or 100 objects? Well we use the new keyword! That way all our instances references only one object

var a = function() { this.x = 12; }
var obj = new Array();
for(var i = 0; i < 100; i++) { obj[i] = new a(); }
We just made 100 objects! Inside an array but...well you get the idea, using the new keyword is closely related to classes, as it's how we say "Take this class, make an object modeled after this class", but as we have no class, we just give the new keyword a constructor, and say "Here, make an object and call this constructor".
Inside the constructor, we can use the "this" keyword as if we are already inside our object, just like a regular constructor.

Ok, so we have the equivalent of a class constructor, but how do we set the attributes, and methods to share across all objects? Prototypes!


What are prototypes?


Awesome question! Prototypes are objects, the special thing about prototypes is that every object in Javascript has a prototype (except some system objects), and a prototype specifies the methods and properties the object will have when instantiated.

Let's take a look at this simple code.
var A = function() { this.x = 12; } // function expression
var objA = new A();                    // creates an instance of A, using the A as constructor
objA.x
> 12
var objB = new A();
objB.x
> 12
That's nice, we have two instances of A, an anonymous function acts as constructor, and we didn't use prototypes! Using the new keyword, we even create instances properly so the function is referenced and not copied twice. This is a pretty efficient way of defining objects in Javascript.

But why, oh why prototypes then?


I didn't need them before, why learn about them? Well, what if we need to extend our A pseudo-class? As we don't have classes, we have to put all the things we want our instances to share in the prototype, instead of the class! So to inherit something, we use... that's right, the prototype.

Let's first understand how this is possible: When a method of an object is requested, the Javascript interpreter asks the object for that method, if it can't find it, it asks the object for it's prototype, and it seeks the method in the prototype, that way, we can create a chaining of prototypes, and implement inheritance cleanly.

Don't worry! Here is the example
var Animal = function() { this.type = "Mammal"; } var Cat = function() { this.name = "Cat"; } Cat.prototype = new Animal(); // Cat gets all the properties of this object
var myCat = new Cat();
myCat.type
> "Mammal"
myCat.name
> "Cat"
Note that we use new Animal() to set as the prototype, as we need an object, not a function, otherwise it would not work!

As myCat doesn't have a type property, it looks up on the prototype definition of Cat, and calls the method we want, there it is! Inheritance!

Okay so maybe we need prototypes...


Good! Now that I convinced you that prototypes are what cool kids use, let's now take a closer look on protoypes
var A = function(){} // object definition with empty constructor
A.prototype.x = 12; // using the prototype, we define x as 12
var objA = new A(); // create an instance of the object
objA.x
12
A.prototype.x = 6; // modify the prototype after instantiating an object
objA.x 6 // ta-da!
Crazy huh? Well maybe it's not that impressive, as you could say "Hey but why don't just change the x property of objA to 6?" Well yes, it would do the same, but imagine x is a function, and there are 10 instances of A, some by inheritance, some regular instances, and we change x, do to something completely different, changing a method at runtime! It's a lot of power! This is why Javascript is so dynamic, and scary sometimes, you have so much freedom! You can have some crazy design patterns for your programs!
As the instances of A don't have an x property, Javascript looks for the prototype's implementation of x, making this possible.

Note: As Javascript is so dynamic you should be careful with your code! Make sure you follow good standards to not end up with a crazy monster of a program, you can't even understand or debug!

Other cool things you can do...


Have you heard of Partial Classes? Not a big deal really, it lets you define a class in separate files, so you have a part of the definition in one, and a part in other, it's not quite the same as inheritance, it's the same class, the compiler just joins all the files and then compiles the class as one.
This is cool, and you can do it in Javascript! This lets you extend classes without inheriting, and making your own extensions, for example, say you want to add a method to Javascript's native String class, it's easy!
String.prototype.isNullorEmpty = function() { return (this == null || this == "" || this == undefined); }
"".isNullorEmpty()
> true
"hI".isNullorEmpty()
> false
Prototypes are pretty hard to get used to, but they certainly do not lack power!

Read more...

MSSQL Alternative to MySQL's LIMIT Pagination

>> Wednesday, April 4, 2012

In MySQL is quite easy to paginate, with SQL you just do

SELECT * FROM MyTable LIMIT 10, 5

That will select the first 10 rows starting from 5, oddly enough MSSQL does not have an easy way to do this, there are a lot of different ways to do it, but the easiests is using two TOPs

SELECT TOP 10 * FROM MyTable WHERE id NOT IN (SELECT TOP 5 id FROM MyTable ORDER BY Id DESC) ORDER BY Id DESC

This will work as long as you don't want to start from 0, of course, in that case a regular TOP statement will do fine.

Read more...

ASP.NET: Disabling a button control when clicked, and do postback

>> Friday, March 16, 2012

I'm not a fan of ASP.NET, but work is work, and I have to use it for now.
Beeing a fan of Open Source and PHP it's quite hard to get used to, but I find the structure of C# fun enough, what I don't really enjoy is the ASP.NET framework, seems too hard to do basic things, and too easy to do complex things (If you let it handle things for you).
Nevertheless, this is a common problem I think many people might have, when you have a button control which has a postback event associated, and you also want to associate some javascript to it, well, I saw many solutions but by far this was the cleanest and easiest.

Enjoy!

Read more...

jQuery Ajax File Upload

>> Saturday, December 10, 2011

I needed a simple and easy to configure and use script, for uploading a single file using Ajax and jQuery, yet the solutions were overcomplicated... So I decided to make my own plugin, it works on FF, Chrome and IE, as far as I tested, it's pretty small (2kb minified) and easy to use, it can only upload one file though, maybe in the future versions I'll just make a plugin to send a multipart form as Ajax.
Anyways! You can get the plugin here, to use it just include the js file and configure it!

<script src="ajax_upload.min.js"></script>
<script>
$(document).ready(function(){
     $('#my-container').uploader({
        'script': 'myScript.php',
        'button': $('#chooseFile'),
        'status-id': 'a-status',
        'iframe-id': 'a-iframe',
        'container': $('#uploaderContainer'), // optional
        'onComplete': function(data){ /* my function */ }
    });
    $('#my-button').click(function(){
        $('#my-container').uploader('upload');
    });
});
</script>

And that's it! I hope you find it useful as I did :) That will just send a file named 'file_upload' to the script, just handle as usual.

Read more...

Getting all possible paths of two vertices in a Graph using DFS

>> Thursday, June 9, 2011

As you might have seen, I recently explained something similar, but now I'll find all possible paths. This is pretty much more of the same but it's way more tricky.
Well modify our basic DFS search and do a view more stuff

Input: vertex start, vertex end, list of lists of vertices "paths", list of vertices "path"
Output: boolean, wheter or not I found a path
add start to path
if(start == end)
    return true
else
    mark start as visited
    for each adyacent vertex w of start
        if w is not visited
            boolean found = dfs(w, end, paths, path)
            if found
                add a clone of path to paths
        path.removeLast()
    mark start as non visited
    return false

That's it! It might seem simple but in Java it's a bit longer. Hope it helped!

Read more...

Getting a Graph's path between two vertices using DFS

As you might have seen, I have made a similar post before, but this time, we use another way of going though our graph, it's called Depth First Search, and it's my favourite way as it's nature is recursive, and recursion is fancy :)
Basically, we will now go though our graph with an bucket of paint and a string, every time we see a non visited vertex, we will paint it, tie the string to it and go on, when we cannot advance any futher, we go back pulling from our string, until we see an unvisited vertex, to then repeat. You can kind of think of it like a way to get though a maze.
The algorithm is something like this

Input: a start vertex
mark start as visited
visit start
for each incident edge E of start
w = opposite(start, E) 
if(w is not visited)
mark w as visited
DFS(start)

The output of DFS can be viewed as a tree, with root on Start, every time we visit a node adyacent to start we add it as a child, and we do the same with each of start's children, making a generic tree. There are different kind of edges which we can see in this image.

Output of a DFS showing different kind of edges
Anyways, that is not important for us, what is important is to get the path between two vertex, this is quite easy, same as with BFS, we have to modify mostly the 'visit' part of the algorithm.

Input: a start vertex, an end vertex, and a list L
// This time we won't output anything, just add the path to our list!
mark start as visited
L.addLast(start)
if(start == end)
return true
else
for each incident edge E of start
w = opposite(start, E) 
if(w is not visited)  
found = DFS(start)
if(found) return true
endfor
L.removeLast()
return false

And that's it. With that algorithm we can search for a path between two vertex, we have to add an extra argument, but we can make a method to make everything nicer. Like in this java example.
Hope you find it useful!

Read more...

Getting a Graph's shortest path between two vertices using BFS

Long title indeed, but this is a rather specific entry. I've been working with graphs lately, for university, and I'm afraid there are lots and lots of different properties and algorithms (you can imagine studying that for an exam is a pain in the ass) but well, I tried searching for this on Google with no luck, there are many algorithms for getting the shortest path between two vertex, and many sites say "It can be done using BFS" but they do not explain how.
So, I found a rather nice and easy solution. First of all, let's say G is a simple graph, with no directed edges, and we don't consider edges' weight. I'll use pseudo-code in this entry since it's more CS oriented.
First of all, if you don't know what BFS is, it's Breadth First Search, it's a way of iterate through a graph, in which you go by levels.

BFS Animation

You can see wikipedia for more info, I'll assume you know the algorithm, at least just on paper, the algorithm is like this:

Input: a vertex called start
Let Q be a queue
Q.enqueue(start)
visit start
while(Q is not empty)
    w = Q.dequeue()
    for each adyacent vertex v of w do
        if v is not visited
            mark v as visited
            add v to queue
            visit v

That's it. Basically, when you solve a problem using an algorithm like this, what you want to work on is on the "visit v" part, what we are gonna do is use a map, in which we will save each vertex we visit, and once we reached our end vertex, we simply "go back". A map is a data structure which has a Key and a Value, so we will use the Key as our vertex, and the value will be the vertex' parent, that way we can just go back and return a list of visited vertex' which make the shortest path from START to END.


Input: a vertex called start, and a vertex called end
Output: a list containing the shortest path from start to end, or null if it cannot find a path
Let Q be a queue
Let M be a map
Q.enqueue(start)
map.put(start, null) // Start has no parent!
while(Q is not empty)
    w = Q.dequeue()
    for each adyacent vertex v of w do
        if v is not visited
            mark v as visited
            add v to queue
            if(v == end)
                Let L be a list
                while(v != null)
                    L.addFirst(ww)
                    ww = M.get(ww)
                return L
return null

There it is, hopefully someone will find it useful! Note that basically the only part that changes is the 'visit' part.
I'll leave the Java code just for the sake of it ;) Sorry it's in spanish, as it's from university, but this should not be much problem.

Read more...

Fedora + Xfce on my netbook

>> Saturday, April 2, 2011

I have to admit, I'm suprised with the compatibility and the performance and stability of Fedora on my Netbook, it works even nicer than Ubuntu (or Xubuntu), I'm pretty happy with it :)
I had no major problems getting up and running even though this is the first time I try another distro than Ubuntu or any Ubuntu variation.

Here's an screenshot of my little netbook screen right now

I still have to add some more customization and programs but it's looking lovely so far :)
Definetely reccommended for netbooks, works awesome with Intel Atom processor.

Read more...

About akaikiwi and stuff

>> Monday, March 28, 2011

As I've now started University I have less time for hobby coding, I'm working on some Java stuff now, as that's what I use at university, I'm working with slick and making some game development, not a full game though, just things like GUI and stuff, once I put together some stuff I'll finish a RPG I was working on :)
About akaikiwi, it's development has drastically stopped, but I plan on finishing it, not now, but soon, I have to do some PHP for work but all Joomla! related (which to be honest I pretty much hate Joomla! awful implementation of MVC but oh well...).
I'd really love to have more time and see more RoR and Django but right now I can't, I want to finish akaikiwi first, although I do take some ideas from those frameworks, I'm really interested in Django on Appengine, I think I'll deploy my next web app there, which is probably gonna be a designer's resource site.
Once I have more free time I'll work on some nice stuff I have on hiatus :)

Read more...

NoSQL Request Injection Attacks with PHP Magic Variables

>> Monday, March 7, 2011

A "new" and interesting injection in PHP has been pointed out, and although very easy to defend against, it's pretty interesting. You can read more about it on the php website.

Read more...

Blender Journey i

>> Thursday, March 3, 2011

Blender is one of the best examples of open source software, and also one of the best 3D tools out there, with it's fame of beeing hard to use, I decided to use that excelent piece of software to learn to create 3D models.
The reason is mostly because is free, it's lightweight, it has lots of free documentation and good support and its used by professionals.

As an indie game developer I've done some nice games, I finished a few and started a lot, I have experience with 2D but I really want to try with 3D, and knowing how to use a 3D program and knowing 3D jargon will make my life way easier, plus I like to make my own resources for my games :)
The idea is using blender to make models, then I'll use Unity to create games.

I'll be reporting on my Blender journey here, I'll be using this free book, right now I read the first few chapters, until the simple man with a hat, which I made and looked funny, but similar to the one in the book :)

Read more...

How To Install PostgreSQL And phpPgAdmin Support In XAMPP

>> Friday, February 25, 2011

I'm working on akaikiwi and I want to test some stuff on Postgre, as the databases I'm aiming to support are SQLite, MySQL and Postgre, the latter is the only one XAMPP doesn't support natively.

I found a great post on How To Install PostgreSQL And phpPgAdmin Support In XAMPP that worked nicely, except in the last part, I had to add

Alias /phppgadmin "D:/xampplite/phpPgAdmin/"

 AllowOverride AuthConfig
 Order allow,deny
 Allow from all

Inside alias_module instead of mime_module, but other than that, it works like a charm :)

Read more...

Sending mails from localhost with XAMPP Lite

>> Monday, February 21, 2011

One of the most common tasks of web development is sending emails, whether from a registration process, password recovery or if they suscribed to an update, you will need to send emails. The problem is that XAMPP doesn't have a default configuration for sending mails, and developing without this ability is pretty dull, you need to test your mails!
But don't worry, you won't have to install anything, and you wont need a hosting, you just need a Gmail or Hotmail account.

  1. Edit your php.ini file located inside the php folder of your XAMPP installation path.
  2. Search for the line ';sendmail_path = "\"YOUR_XAMPP_PATH\sendmail\sendmail.exe\" -t"'
  3. If it has a ';' in the beggining, remove it
  4. Edit sendmail.ini file inside the sendmail folder
  5. Add the following lines
  6. account Gmail
    tls on
    tls_certcheck off
    host smtp.gmail.com
    from [your-email]@gmail.com
    auth on
    user [your-email]@gmail.com
    password [your-password]
  7. Finally edit the account default line, it should look like this
    account default : Gmail
  8. That's it! Now restart apache and you can now send mails.
If you want to use Hotmail instead of Gmail just change the host to 'smtp.live.com', the email adresses, and if you want, the account name (Hotmail instead of Gmail).

Read more...

Rounded Corners with Yahoo Javascript Library, YUI 3

>> Saturday, February 19, 2011

YUI 3 is an awesome Javascript library by Yahoo!, I'm really loving it, it has a very nice organization and it's nice to use.
Something that seemed a bit weird to me though, it's that it doesn't have a Rounded Corners plugin, so I decided to create one, and here it is!
Using it it's pretty simple, here it's and example:



Enjoy!

Read more...

Creating Anonymous PHP Objects

So I'm working on akaikiwi and found out a very nice thing, which doesn't really help me right now, but I really feel like sharing it, as I'm sure it'll be useful for somebody.

$obj = (object) array('foo' => 'bar', 'property' => 'value');
echo $obj->foo; // prints 'bar'
echo $obj->property; // prints 'value'

That's it! That will cast the associative array to stdObject. Useful to save some code.
In PHP 5.3 you could actually also use closures to make some nasty stuff, it's a pity PHP 5.3 is still not widely used.

Source: http://www.php.net/manual/en/language.oop5.php#84292

Read more...

More on YUI and akaikiwi

>> Tuesday, February 15, 2011

So far, I've been working on a personal site, forum-like, and I've been playing with YUI more, I'm very satisfied, it feels way nicer and more like Javascript than other frameworks. I like the organization of widgets, plugins and extensions. It's really nice so far.
About akaikiwi, I'm adding little fixes here and there, thanks to my project, I always try to follow YAGNI (You Ain't Gonna Need It) so basically add functionality when I need it, instead of when I think I will, this makes the libraries simple and tight.
The site should be finished by febrary but I think it might take until the end of march to get it up and running online.
About akaikiwi, I don't know when the first release is comming, but I think it will be released after this site is finished and tested.

Read more...

Gedit

>> Friday, February 11, 2011

So I've been using linux way more lately, because of my new netbook, so I've been playing with Gedit too, it's surprisingly nice, very nice alternative to Textmate and free, it can do pretty much anything Textmate can, and it works on Windows and Linux.
I really recommend it, the completation function is very nice, also de snippets.
I've been using it a lot since I've been working on akaikiwi and aoi pantsu, it's doing great so far.

Editing some Yui 3 Javascript

Read more...

Drop Down Chooser

>> Wednesday, February 9, 2011

This is a little widget I made for Yui3 as I'm still learning, it seems very nice so far, it's kind of huge, but not hard, it just takes time.
It's just a basic dropdown chooser, but it can help a lot to make your life way easier, which is basically what widgets are for :)
The basic idea is that you create a new instance of the DDChooser widget, then set the launcherNode, which is the node which will launch the chooser, the chooser will position automatically and hide/show automatically too.
Here's an example:



You can download it from the NekoCM Bitbucket repository, you can also just see full code, or just the the min version (compressed with yui compressor).

Read more...

  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP