= fn(n){n xor 0xFFFF004B eq 0×0 ? n : fn(n – 0×1)}

Archive for the ‘Tech.’ Category

REMIX10 – Share the Web Love, Late Update

Saturday, June 19th, 2010

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

Wednesday, March 10th, 2010

.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!

Sunday, March 29th, 2009

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)

Monday, March 23rd, 2009

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.



Web Klip Enhancement – Special Effect Applied

Sunday, March 22nd, 2009

Currect release: 1.1

Download: http://www.koumei.net/download/wp-webKlip.zip

Not too much special effects. In order to make the contents which read from the underneath javascript show themselves up naturally. Not in a harsh.



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

Saturday, March 21st, 2009

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.

:-)



A Simple Rss2Json Service Released!

Friday, March 20th, 2009

Now I simply add a Rss2Json service on my blog, it just return the very first post from the target website as JSON and, of course, the target should be RSS format. The reason why I create this interface is because I would like to utilize cool AJAX to obtain the content from my friend’s blog, yet the browser secure prevent me crossing the boundary to other domain. Could it be working using iFrame? Negative. The only approach to cross the border is using JSON.

The definition of my interface is:

Name: Rss2JSon
Interface: http://www.koumei.net/rss2json/
Method: GET
Parameter 1:  rss  – The URL of the rss content
Parameter 2: cb — The javascript callback function
Return: application/x-javascript
Example: http://www.koumei.net/rss2json/?rss=http://www.blogjava.net/max/rss&cb=<callback>  (A blog of my friend)

The callback function is very significant. Don’t forget to define a callback JS function on your script. The definition of the callback function should be similar as below ( parameter rss is an object, containing “title”, “link” and “description” and so forth<please go through RSS schema on item tag>.)

<script type=”text/javascript”> 

function myCallback(rss){
    var title = rss["title"];   // or rss.title
    var link = rss["link"];  // or rss.link
    var desc = rss["description"];  // or rss.description.
}

</script>

Now, you can embed the script to wherever you need.
<script type=”text/javascript” src=”http://www.koumei.net/rss2json/?rss=http://www.blogjava.net/max/rss&cb=myCallback”></script> 

Enjoy scripting.



An idea for “Add to Favorite” function for virtuemart

Wednesday, March 18th, 2009

The original Virtuemart provides RSS feed to every product, so that users can “eat” the feed if they like the product. The idea is cool, but actually, I prefer an on-line favorite subscribe function for the user than RSS subscribe. The RSS subscription is good to track back to a single category or a whole website, not so good to track each product. How many chance you would like to change the product’s description or product’s price to let the users know the newest status of product? So your product categories and website will be renew every now and then, even everyday, but not a single product, right? So the single product is good to be traced on the website’s favorite function. Unfortunately, Virtuemart doesn’t come with such a function for people to trace their own favorite product. The favorite products mean the products are probationary, users don’t buy them, but could buy them later. So what I think the “Add to Favorite” function could be specified as:

  1. It’s managable. User could easily add product to favorite list just a single click, better not refresh the page after they click a button.
  2. User can review the favorite list. 
  3. The product in the favorite list will be shown when the product is published.

I think this little gadget could help user shopping with happiness.



Howto: Create “Cash on Delivery” payment Varied from Different Postcodes for Virtuemart

Tuesday, March 17th, 2009

Actually Virtuemart has done a great job on cash on delivery support, but what if cash on delivery cost a fee not only the total amount of purchase but also the different postcode? Here comes a tutorial on how to calculate the different rates based on users’ postcode.

Of course, before doing that, you need to have a workable Virtuemart distribution on joomla. You can find more tutorials on joomla official website or virtuemart website.

There are only two steps of this simple tutorial:

  1. Create a new payment method on Cash on Delivery. Actually the orignal virtuemart comes with an option of “COD”, but at this time I don’t want to ruin its file structure. I prefer to create a new one. Actually creating new payment method helps you to know more about joomla.
  2. Revise “ps_checkout.php” to make it works.

Let’s dive to details.

Create a new payment method on Cash on Delivery.

Sooner or later will you find that creating payment method couldn’t be easier. What you need to do is to create a class, and of course, you write some methods which is recoginzed by joomla framework. You can find bunch of original payment classes on /administrator/components/com_virtuemart/classes/payment/ folder. If you see carefully, you can see each payment class comes with a config file. For instance, you can see a payment class called ps_paypal.php, should come with a config named ps_paypal.cfg.php. I won’t use config file, so I don’t need the cfg.php file. Now here’s my turn on creating such a class:  create a file name “ps_codonpc.php” (which means “Cash On Delivery On PostCodes”), never mind its name, but I think you better follow the naming convention of Virtuemart. Open this file with any kind of text-editor, I recommend to use notepad++. Create a skeleton below.

if( !defined( '_VALID_MOS' ) &amp;&amp; !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );
 
class ps_codonpc{
 
var $classname = "ps_codonpc";
var $payment_code = "PU";
 
function show_configuration() {
return false;
}  
 
function has_configuration() {
return false;
}
 
function get_payment_rate($sum, $ship_to_info_id=null) {
}  
 
function configfile_writeable() {
return true;
}
 
function configfile_readable() {
return true;
}
 
function write_configuration( &amp;$d ) {
return true;
}
 
function process_payment($order_number, $order_total, &amp;$d) {
return true;
}
 
}

I know what you must be thinking.  You must be wondering if there is any necessity to create those functions within the class. Yes, you have to. That’s the weakness as well as fexibility of the characteristic  object-oriented of PHP. Well, it makes senses, because PHP is runtime dynamic language, not compile-time language. The payment classes on /payment folder are dynamically recognized by the framework, they use the same functions naming convention to make the polymorphism works.  I mean the ps_paypal.php and ps_paymate.php are of the same functions’ name, and created by the framework, however the framework doesn’t need to know the existance of payment classes and doesn’t know what they are doing. The framework only knows their functions’ name. Confused? Never mind.  Forget this paragraph. You can do the same thing on java using “reflection”.

You can see a function called “get_payment_rate” in this class. Well, not all the classes in /payment folder have this function. Why? That’s because virtuemart framework will only calculate the payment rate if the “get_payment_rate” function is defined. Actually, there is only one parameter is need: $sum, but since we need to calculate the fee by post code, I add an additional paramter(ship_to_info_id)  and give it a default value(null).

Now you need to fill the “get_payment_rate” logic to make it works. I add a simple logic to calculate the payment rate.

function get_payment_rate($sum, $ship_to_info_id=null) {
		//Get the ship_to_info_id if the parameter is null
		//Normally the item is passed from checkout module
		//We need to change ps_payment_method.php to pass the parameter to this object.
		if( empty( $ship_to_info_id )) {
 
		    $sdb = new ps_DB();
 
		    $sdb->setQuery( "SELECT user_info_id FROM #__{vm}_user_info WHERE user_id=".$auth['user_id']." AND address_type='BT'" );
 
		    $ship_to_info_id = $sdb->loadResult();
 
		}
 
		//Get the zip(post code) from user info table
 
if(!empty( $ship_to_info_id )){
 
			$sdb = new ps_DB();
 
			$qry = "SELECT `zip` FROM `#__{vm}_user_info` WHERE user_info_id='".$ship_to_info_id."'";
 
			$sdb->query($qry);
 
			$sdb->next_record();
 
			$postcode = $sdb->f('zip');
		}  
 
		if(!empty($postcode)){
			if($postcode >= '3000' && $postcode < '3050'){
				return 0;  //these areas are free
			}else if($postcode >= '3050' && $postcode < '3150'){
				return floatval( $GLOBALS['CURRENCY']->convert(-5));  //these areas cost $5
			}else{
				return floatval( $GLOBALS['CURRENCY']->convert(-10)); //the othes cost $10
			}
		}else{ //unknow post code, use default
			return floatval( $GLOBALS['CURRENCY']->convert(-10)); //the othes cost $10
		}
}

Can you see the return value? it’s negative, that’s because the get_payment_rate function return the payment discount (according to the definition of this function), the name should be changed to get_payment_discount. Otherwise would be a little bit confused. If you return a positive, the users will get a discount from this payment; a negative, the users will pay an extra fee.

OK. That’s fine.

Revise “ps_checkout.php” to make it works.

And now go to ps_checkout.php, and find a line 1673, change “return $_PAYMENT->get_payment_rate($subtotal);” to

$ship_to_info_id = $_REQUEST['ship_to_info_id'];
return $_PAYMENT->get_payment_rate($subtotal, $ship_to_info_id);
“.

Okey dokey, Now add the Cash On Delivery paymethod on your administration page, and then go through the check out process and find out more excitement. Of course, the logic provided here is very simple, you can judge the rate from a post code data table and apply new features.



Howto: Show your images using fla-img-sw

Sunday, March 15th, 2009

“fla-img-sw” is a flash movie clip that enables several images loading by passing the images’ URL to the flash parameter. “fla-img-sw” is annouced by myself, you can get the source code or get the package on http://code.google.com/p/fla-img-switch/ .

Using AJAX to improve the loading phrase of the website is considered to be a good pratice on presentation tier. Actually, Flash movie cilp can do the same thing as AJAX. Imagine there are several images are to be loaded in one page, it takes user’s time on loading the page. If you show a thumbnail in that page, then if users would like to see the detail of the image, they have to click on that image link, your website then pop-up a window to show the original size of the picture. It waste users’ time, according to Even Faster Web Sites (Steve Souders), Life is too short, we should write code faster then even (means saving your users’ life and time :-)  

But I am not here to talk about how to utilize AJAX to improve the website, but gonna show a tutorial on how to use my open source gadget to show images on your website. Before that, just take a look at the example of how the gadget work: (click to enlarge, please note that the demo below is a snapshot of the commercial usage, the open source version is somehow a little bit different from the commercial one, like I depict on the previous post.)
fla-img-switch 
You can see a thumbnail on the right side, and the main picture which is selected will display on the big left side.

It’s easy to use. Once you get the package, you will see a file call “ImgSwitch.html”, that is the demo file, double click this file and you can see a demo locally. If you feel enough for the demo and being inclined to use it, just open the “ImgSwitch.html” and you will see how it works.

Easy to proceed:

  1. Copy “ImgSwitch.swf” to a appropriate position which you can refer from your HTML
  2. Copy the code below to where you would like to show the images:
    <object classid=”clsid:d27cdb6e-ae6d-11cf-96b8-444553540000″ codebase=”http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0″ width=”690″ height=”492″ id=”ImgSwitch” align=”middle”>
    <param name=”movie” value=”ImgSwitch.swf” />
    <param name=”quality” value=”high” />
    <param name=”bgcolor” value=”#c2b29a” />
    <param name=”FlashVars” value=”picurl=1.jpg;2.jpg;3.jpg;4.jpg;5.jpg&maxpic=5&modelNo=TestTing” />
    <embed src=”ImgSwitch.swf” quality=”high” bgcolor=”#352B68″ width=”690″ height=”492″ name=”ImgSwitch” align=”middle” allowScriptAccess=”sameDomain” type=”application/x-shockwave-flash” pluginspage=”http://www.macromedia.com/go/getflashplayer” FlashVars=”picurl=1.jpg;2.jpg;3.jpg;4.jpg;5.jpg&maxpic=5&modelNo=TestTing”/>
    </object>
  3. Change the parameters:
    A. Replace “picurl” paramter with your image url, note that if your images are from www, don’t forget to quote the images’ URL starting with “http://”. And the URL is separated by semi-colon(;).
    B. Replace “maxpic” parameter with the actual images quantity you would like to show. 
    C. Replace “modelNo” paramter with the title(name) of this group of images.

Done.



Profile

  • Koumei Deng's Facebook profile


Submit Your Site To The Web's Top 50 Search Engines for Free!