Category Archives: Tech.

Some Must-have PHP+MySQL development tools and utilities

After being a web developer for so many years, I find that myself is still a big PHP fan. The reasons are quite obvious: first of all, it is lightweight, very easy to deploy to any server in the world, and it is free! There are also a lot of open source PHP frameworks such as CakePHP, Yii that we can use. As a PHP web developer, I want to share some tools here with my comments. Hope that they are useful.

1. WAMPServer (Apache/MySQL/PHP included)

Setup PHP+MySQL development environment in no time. It is not very hard to setup the development environment by yourself, however this tool is extremely helpful if you don’t want to spend your time to do the job that someone else has already done for you.

2. Framework: Bootstrap 3 (or 2.5)

Originally from Twitter team, it is now becoming famous for its responsive framework. I really like to use it because it really saves me time to write a lot of CSS.

3. Useful gadget: Firebug (plugin for firefox)

It is actually nothing to do with PHP, however, if you are developing a website, you don’t want to miss it.

4. Tortoise SVN for window / Tortoise Git for window

Version control. I like to use it because it is seamless embedded in window explorer.

5. Navicat lite

A lightweight MySQL client software. (No more free, please find it through google for the old version, trust me, old version is good as well)

6. NetBeans IDE

Open source PHP IDE. Other option: If you are developing open source project, you can also get a PHP Storm for free.

What else?

There are bunch of software/tools help to improve the productivity that can be found on Design Junction‘s Ultimate Free Toolkit for Internet Web Ninjas as well. Hundreds of tools are listed.

Gallery CMS MOD: View As HTML or Partial HTML

Gallery CMS  provides an easy-manage CMS (Content Management System) framework for gallery. I like the way they manage data, all the data are exposed as XML or JSON. It is not a complete solution of photo gallery online, but if you need to integrate photo gallery on your website that would be a very good start: you can easily develop or integrate. And guess what is the exciting part? It’s free! For more information, please feel free to download @ http://www.gallerycms.com/

It’s easily integrate but sometime you might need more convenience when integrate it to your website. Of course using XML or JSON which is the basic data structure is not that difficult, but I think most of time, for the integration itself, the most easiest and convenient is managing HTML. On the view if you are rendering the content partially, later you can use AJAX to replace the partial HTML content dynamically other than managing JSON on client side: we need rich client application, but if it lose weight a little bit, why don’t we make it lighter?

So, let us apply the MOD to it. It’s MIT license, so, no harm to mod it. Just pay a little attention to it’s license file: Gallery CMS comes with 2 licenses, one license is MIT license which represent itself, and the other license is derived from CodeIgniter which the basic framework.

1.\application\controllers\view.php //Add the following codes to it:

function html() {
$data['row'] = $this->gallery_xml->viewXML();
$this->load->model(‘settings_tbl’);
$data['settings'] = $this->settings_tbl->viewSettings();
$this->load->view(‘view_html’, $data);
}

2. On\application\views\ folder, create a file view_html.php

Please note that, you can make the view html a full html or you can partially render it like this:

<?php if(isset($row)) {?>
<div>
<?php foreach($row as $r){?>
<?php if(isset($r->images)) {
foreach($r->images as $img) { ?>
<div>
<div><a href=”<?php echo base_url();?>uploads/<?php echo $img->filename;?>” target=”_blank” title=”<?php echo $img->caption;?>”><img src=”<?php echo base_url();?>uploads/<?php echo $img->thumbnail;?>” border=”0″ align=”absmiddle” width=”<?php echo $settings[0]->thumb_width; ?>” height=”<?php echo $settings[0]->thumb_height; ?>”/></a></div>
<div><?php echo $r->title;?></div>
<div><?php echo $r->description;?></div>
</div>
<?php } ?>
<?php } //if  ?>
<?php } ?>
<div style=”clear:both”></div>
</div>
<?php }?>

After that, you can use: http://<GALLERY_CMS_WEBSITE>/index.php/html  to retrieve the HTML content. In our mod above, it is just partial HTML, so you can jQuery it:

$.get(‘http://<GALLERY_CMS_WEBSITE>/index.php/html ‘, null, new function(resp){$(‘#html-container’).html(resp);});

Nice and easy.

ASP.NET MVC Whole Site 301 Permanent Redirect

For some reasons, we need to permanently redirect the whole website to another website. It would be much easier that you are the owner of the server. But most of time you just host your website on the server out there. It wouldn’t be a big problem that your hosting company will support you to do some simple 301 redirect or may you have enough privilege to do it yourself. Is it possible to redirect permanently the website to other website by programming a little bit?

Sure you can. With MVC routing facilities, you can define your customized redirect logic: CREATE AN EMPTY MVC PROJECT, MODIFY GLOBAL.ASPX.CS FILE ONLY ON THIS EXAMPLE:

First of all, define two objects which implemented IRouteHandler and IHttpHandler, you can feel free to define those two objects on Global.aspx.cs file:

//@Implements IRouteHandler
class RedirectRouteHandler : IRouteHandler
{
private string newUrl;
public RedirectRouteHandler(string newUrl) { this.newUrl = newUrl; }
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new RedirectHandler(newUrl);
}
}

//@object implements IHttpHandler
class RedirectHandler : IHttpHandler
{
private string newUrl;

public RedirectHandler(string newUrl) { this.newUrl = newUrl; }

public bool IsReusable { get { return true; } }

public void ProcessRequest(HttpContext httpContext)
{
httpContext.Response.Status = “301 Moved Permanently”;
httpContext.Response.StatusCode = 301;
httpContext.Response.AppendHeader(“Location”, newUrl);
return;
}
}

Then add one line on RegisterRoutes(RouteCollection routes) method (in Global.aspx.cs):

routes.Add(new Route(“{*pathInfo}”, new RedirectRouteHandler(@”http://koumei.net”));

Now all request to the website will redirect to “koumei.net” permanently. :)

REMIX10 – Share the Web Love, Late Update

I almost forget the interesting 2-day event or you can say “meeting” in Melbourne. The idea of this conference is to show Microsoft developer the latest development kits and to let technical or IT people catch up each other. $300 for joining the meeting but I got it for free. Thanks to my boss to give me such great opportunity to join the great event.

I got 2 souvenirs, such as t-shirt, caps, but all are related to Microsoft stuff. You want to get the t-shirt? well, need to make some efforts. Everyone who attends the meeting will get a magic cube from the host, and need to fix the cube to a designated image. After all, once cubes are fixed, the host sorts them out and put them in a frame, to shape a IE icon:

The Frame of Magic cubes

The Frame of Magic cubes,Everyone is involved

I think the most useful sessions are about how jQuery works peacefully with ASP.NET and VS.NET 2010 new features, and one interesting session talking about the future data representation, and introduce Pivot. Microsoft considers the cooperation with jQuery is a giant step forward, and shows its ambitions to open source community. Microsoft starts to contribute to open source community and make a lot of effort towards it, look forward to seeing its powerful tool released in months to come.

Frankly Speaking - Talk Show in REMIX10

Frankly Speaking - Talk Show in REMIX10

One thing somehow a little bit disappointed me is on this event, Microsoft doesn’t show any thing about HTML5 and CSS3, I think because Microsoft more focuses on sliverlight technology?

Use of Lambda Expression to Create Complicated Query

.NET FX introduces a powerful weapon for creating the compact, breezy and elegant code in your project. The weapon’s name is as complicated as the mathematical stuff, called Lambda expression.

As the name implies, the great convenience comes great complication inside. Lambda expression is too important to understand, it is useful and I think it is good to know how it works. Well, it’s not as complicated as we think, just a little bit confusing when using it.

First of all, Lambda is used for 2 purposes. 1 is to simplify delegation, 2 is to create expression tree. In my case, I need to create lambda expression to create dynamic query.

Imagine the following usecase:

In your product table, there is a field called “Tags” and it’s used for storing the CSV (comma separated value) like “car, mazda, suv, luxury”, you have many records:

Product Table: (Table name: ProductTable)

ID    ProductName    Tags
1    Tow bar        car,mazda,suv,luxury
2    Cup holder    car,luxury
3    Phone holder    car,mazda
4    FM Transmitter    car,suv
5    Queens bed    luxury
6    DVD Burner    car,BMW,x5,luxury

When your searching criteria is
“mazda” and “luxury”, the following records would be selected out:

ID    ProductName    Tags
1    Tow bar        car,mazda,suv,luxury
2    Cup holder    car,luxury
3    Phone holder    car,mazda
5    Queens bed    luxury
6    DVD Burner    car,BMW,x5,luxury

In ancient SQL age, you would probably write a SQL like this:

string SQL = “SELECT * FORM ProductTable WHERE Tags LIKE’%mazda%’ OR Tags LIKE ‘%luxury%’”;

It is IMpossible to create SQL like above except the project scope tells you the fixed keywords that would be used, the keywords should flexible. Then the code would be as much as:

string[] tags = new string[]{“mazda”, “luxury”};
string SQL = “SELECT * FROM ProductTable WHERE 1=1″;
foreach(string tag in tags)
{
SQL += string.format(@” AND Tags like ‘%{0}%’”, tag);
}

You must be very exciting that your code supports as many keywrods as it can. (I did before, I mean I would be very exciting when the code filled with logical stuff, LOL, of course, not now, that’s what geek did before~ )

Back to the reality, to the modern age, with the lambda expression, what you need to do is:

(pre-condition: you have created corresponding domain model which mapped to the database.)
The domain object or entity would look like:

[Table("ProductTable")] Class ProductTable{
[Column]public int Id{get; set;}
[Column]public string ProductName{get; set;}
[Column]public string Tags{get; set;}
}

to fullfill the same kind of logic as the stone-aged people do, you just need to

DataContext db = new DataContext(“<connection-string>”);
Table<ProductTable> table = db.GetTable<ProductTable>();
string tag1 = “mazda”;
string tag2 = “luxury”;
var data = table.where(x=>x.Tags.Contains(tag1)).where(x=>x.Tags.Contains(tag2)) select new ProductTable;
return data.AsQueryable();

Since so far, you still feel comfortable with this, but after minute, you would probably wanna go back stone age, how do we dynamically create the query in this case? Unfortunately, there is no short-cut for this, but many people provide lots of solutions on the Internet. We can either download some source codes about dynamically query on Internet or just grab the codes from the blogger’s website.( Most of time, you can’t use all of their codes posted on the blog, the codes are broken and bad structure, remember what Koumei always suggests, absorb the mind from the other coders, do not copy the code they provided. )

But in here, I would rather to use Expression Tree to implement the dynamic query.

First of all, we need to create an expression, because it would be applied to IQueryable.Where(Expression<Func<ProductTable, bool>> expression), so the expression should be defined as:

public static System.Linq.Expressions.Expression<Func<ProductTable, bool>> ApplyTags(IEnumerable<string> tags) //parameter is the collection of tags
{
ParameterExpression c = Expression.Parameter(typeof(ProductTable), “c”); //Get the parameter from Func<ProductTable, bool>, remember? this is the advanced and lazy version of delegation, we need to craete ParameterExpression to hold this
var tagsProperty = Expression.Property(c, typeof(ProductTable).GetProperty(“Tags”)); //Here is the expression for get the Tags value from ProductTable object
Type[] ContainsTypes = new Type[1];
ContainsTypes[0] = typeof(string);
System.Reflection.MethodInfo myContainsInfo = typeof(string).GetMethod(“Contains”, ContainsTypes);
//Create the expression collection (based on the tags collection from parameter)
List<Expression> myTagExpressions = new List<Expression>();
foreach (var t in tags)
{
myTagExpressions.Add(Expression.Call(Expression.Call(tagsProperty, “ToString”, null, null), myContainsInfo, Expression.Constant(t)));
}
Expression OrExpression = null;
foreach (Expression myTagExpression in myTagExpressions)
{
if (OrExpression == null)
{
OrExpression = myTagExpression;
}
else
{
//Need to implement OR relationship among all the expressions
OrExpression = Expression.Or(myTagExpression, OrExpression);
}
}
//This is how Expression would be extracted to expression tree later on.
Expression<Func<ProductTable, bool>> predicate = Expression.Lambda<Func<ProductTable, bool>>(OrExpression, c);
return predicate;
}

Again, you can’t copy the code, since you would NOT have the same object like ProductTable and the same “Tags” property as I do. Luckily, you still can copy the code that I provide later, which is using the magic of template or generic programming. Before that, let us see how to use it:

IQueryable all = table.Where(ApplyTags(new List{“mazda”,”luxury”})).AsQueryable();

Since so far, I am 100% sure you can do it like refactoring, re-structuring to optimize your code. However, I would like to provide the code which can be general used:

public static System.Linq.Expressions.Expression<Func<T, bool>> ApplyFilter<T>(IEnumerable<string> filters, string property)
{
//Get parameter
ParameterExpression c = Expression.Parameter(typeof(T), “c”);
//Get property from <T>
var tagsProperty = Expression.Property(c, typeof(T).GetProperty(property));
Type[] ContainsTypes = new Type[1];
ContainsTypes[0] = typeof(string);
System.Reflection.MethodInfo myContainsInfo = typeof(string).GetMethod(“Contains”, ContainsTypes);
List<Expression> myTagExpressions = new List<Expression>();
foreach (var t in filters)
{
myTagExpressions.Add(Expression.Call(Expression.Call(tagsProperty, “ToString”, null, null), myContainsInfo, Expression.Constant(t)));
}
Expression OrExpression = null;
foreach (Expression myTagExpression in myTagExpressions)
{
if (OrExpression == null)
{
OrExpression = myTagExpression;
}
else
{
OrExpression = Expression.Or(myTagExpression, OrExpression);
}
}
Expression<Func<T, bool>> predicate = Expression.Lambda<Func<T, bool>>(OrExpression, c);
return predicate;
}

The usage is similiar:

IQueryable all = table.Where(ApplyFilter<ProductTable>(new List{“mazda”,”luxury”}, “Tags”)).AsQueryable();

Not that hard, right?

Enjoy the powerful weapon, but don’t hurt yourself, bacause the deadline is ahead!

6    DVD Burner    car,BMW,x5,luxury

My Webklip Plugin For WordPress: Goes Multiple-RSS!

Today I refactory the source code and add new features to Webklip, it becomes 1.2 and, most encouraging, multiple rss supports!

The improvement includes:

  • Uses template engine to show widget. No more embedded HTML.
  • Moves all functions to a util class
  • Supports up to 5 RSS
  • Still reads RSS feed dynamically on client-side

The feature version will be released next day or two, will enhance javascript flexibility. E.g., not compulsorily needs jQuery framework.

You can download the widget on http://www.koumei.net/download/wp-webKlip.zip

Relative article:

WordPress Widget: Client-side RSS util, The Web Klip Released!

Virtuemart: Ajax Effect on IE 8 Fix List based on Virtuemart 1.1.3(stable release since 22, Jan)

Virtuemart utilizes Ajax mostly by mooTools. It works fine in many browsers except microsoft newly released browser IE 8. Especially when user try to add a product to shopping cart using Ajax, the mooPrompt (a pop-up window) fails, and nothing happen on that page… Maybe the first thing you are about to do is to upgrade mooTools. Yes, that’s seems a great idea, however mooTools’s updates from 1.11 to 1.21 is totally a nightmare for developer. Many things change, you have to revise the code manually for Virtuemart. 

The following files should be updated (if you want to satisfy IE 8 users):

  • \components\com_virtuemart\js\mootools\mootools-release-1.11.js  (update to 1.21)
  • \components\com_virtuemart\js\mootools\mooPrompt.js (you have to revise it manually. Should change a lot of JS class definitions in accordance with mootools 1.21 syntax)
  • \components\com_virtuemart\js\slimbox (update to slimbox for mootools 1.21)
  • \components\com_virtuemart\themes\default\theme.js (you have to revise it manually. Should fix a bug on line 59, change to var timeoutID = setTimeout( ‘document.boxB.close()’, 3000 );)

Besides updating corresponding files, you can also disable Ajax function on the administration page. Or.. Wait until next stable release of VM). If you need the files above, just leave me a message, and I will pack them up for you.

WordPress Widget: Client-side RSS util, The Web Klip Released!

The original WordPress (2.7+) provides RSS clip widget from the other website. It looks good but it is server-side script that may occupy the server resource to interpret the RSS. I don’t like that approach. So I decide to create a client-side script that loads rss from other website or blog.

If you want to try, just download the widget on http://www.koumei.net/download/wp-webKlip.zip , then unzip to wp-content/plug-ins/ folder, and activate the plugin and add widget to you wordpress blog.

Before using this widget, there are some notes you should know:

  1. Defects:
    Currently only support ONE RSS excerpt.
    Only shows the first RSS item.
    jQuery should be included on your blog.
  2. Usability:
    Site that provide at least 1 item RSS feed could be refered by this widget.
  3. Extension:
    Multiple-RSS and rollover will be available  on next release.

The Demo:

webklip_1
Picture 1. The plugin will be shown after you copy the unzipped file to your plugin folder
webklip_2
Picture 2. Add the widget to the “Widgets” menu on your administration panel. You can add a RSS feed to this widget

You can  find the demo on the right side of my blog.

:-)