martes, 26 de febrero de 2013

FontAwesome and Less

FontAwesome is a very nice font resource. The amount of icons is huge and since they are not images, they scale properly to any size and look nice on any resolution. This is something I really like

One issue I found is that presentational classes force you to modify your HTML to add an icon. While this could be fine for new projects there are situations when you probably would be better using semantic names instead.

That's why I made this, just by searching and replacing on the font-awesome.css file

I added the extension .css to gist files to enable the syntax highlighter. They should be less files.
Doing it this way I can use more semantic names, and when I don't need those I can still use the normal presentational classes that font-awesome offers. So I guess I have the best of both worlds

viernes, 7 de septiembre de 2012

Internet Explorer 7, 8 and 9 must die or kittens will die

Update: Google is dropping IE8, they don't want to kill kittens 
http://googleappsupdates.blogspot.co.uk/2012/09/supporting-modern-browsers-internet.html

Today is the last day I will spent time fixing issues for Internet Explorer 7, 8 or 9. I stopped doing for Internet Explorer 6 some time ago, and that was a good thing. But it is about time to do the same with the other not HTML5 good enough browsers. Don't get me wrong, Internet Explorer has made a very good job, the browser is really good, but webkit based browsers and Firefox have done an even better job those days. And even Microsoft has done EXTRAORDINARY GOOD JOB making Internet Explorer 10 the best microsoft browser ever.

So why should we (the developers) still suffer because there are huge group of people that won't want to upgrade the browser they use? Before there were not that many options, and Internet explorer users were majority, but nowadays the Chrome user base has increased a lot, so at least for me it make no sense to still support Internet Explorer, 7, 8 or 9 anymore.

How much time have we heard from other developers all the pain that they have to pass to make their websites to work properly in Internet Explorer 7 - 9? Do you remember how much time took to actually kill IE6? I guess that we haven't learned the lesson. As Douglas Crockford said on one of his talks, we are guilty of make that happen. We did a very good job supporting IE6 that we shoot ourselves in the foot while doing it. We made our life a living hell. And we're doing the same again for the other Internet Explorer versions.

So what do we do with the Internet Explorer Users? well, to start we can show to them the path to redemption, and evangelize them. Yeah, we should be like the Jehova Testifiers, we should be HTML5 Evangelizers, and tell our friends and family that they can have a better life, that they will find the peace of mind and the way to heaven if they use a Grade A Browser (either Chrome, Firefox, Safari, Internet Explorer 10, etc). It is the word, it is written in the Bible... of the web, that they need to change or be condemned to a life of misery and pain.

How many times we as developer had cool ideas and want to play with it, we make something really cool with nice transitions, effects and animations, only to hear from our product managers or marketing divisions that, we cannot deliver it, unless it runs on Internet Explorer 7-9, and this gets even worse, because they probably don't know that this new cool stuff that your are playing with won't work well on that oldie browser. Or maybe they know and they just want to make the life of the developer a bit more complex. he he.

So, are the Internet explorer user lost? should they lost any hope? Well I guess that there are some actions that they could make. And that is telling them to stop being lazy and install a better browser, that it is free and cost no money. And if they're not that proactive, we should show to them the path to the light. We all have friends that ask ourselves all the time about

Each time we make a web application we should add a tiny message for Internet explorer users warning them about the fact that their browsers are very old and they will not be able to render the cool content that we the developers are trying to show to them. Do that showing a funny message maybe with some humor something like this:


This browser is really Old! 

The browser you're using does not support the features required by this app. It is very old and you should consider change it to one of the better browsers out there, likeChrome or Firefox But, if you are stubborn enough to keep this very old browser then you can use the chrome frame.
Remember each time you open a web page in Internet Explorer 8 or 9 a WebDeveloper and 2 kittens are killed. So you should stop this insane killing!.





So at least users will realize that they are using and old browser and maybe, if we're lucky enough they will be able to do something, either switch to a better browser or at the very least install the chrome frame.

There are reasons to still support Internet Explorer users, I know, they're still a huge portion of the total user base in a website. But this could be worse if we keep supporting it!.

So what else can we do appart from showing to them the path to redemption?

Here are couple of actions that we all can make:

1. Talk to our managers to stop making us to work on supporting Internet Explorer 8 - 9 browsers. Tell them how much time is that costing and how much time we should probably get to invest on new "cool" stuff made with newer technology that runs very well on Grade A Browsers. Show them some examples. show them Sprite 3d, three.js, the Atari page for Internet Explorer 10 and other more, let them know that the web could be a more vibrant place, not only to display information in the traditional way but to do very very cool stuff!.

Mention to them that now the Chrome frame does not require administrative permissions so you don't need to be an administrator to install it.

Mention to them that Microsoft is very close to release (finally) a very good Internet Browser, Internet Explorer 10 and that we should only support that version from that time on.

2. Mention to our friends and family that they do not require to use Internet Explorer 8 - 9 that they can use better browsers, one more time.

3. Do not spent time fixing cosmetic issues in Internet Explorer. Don't do it. If we all stop doing it, a good portion of our users will be forced to upgrade to other browsers, like Chrome or Firefox. Even better those browsers expose a silent update feature, so they will be "up to date" most of the time with no effort (yeah we now our users are lazy). If they (PM, UE, Marketing teams) force you, make your web app work at some level, and stop there. At least stubborn users will see something, probably not that cool, but they will be able to use your app.

4. If you are a developer, make a tiny javascript library that other developers can include in their websites to detect and older browser and show to them a message that the one above, make this to not depend on anything so every website in the world can use the script and will spread the word about stop using Internet Explorer 7 - 9

IF WE STOP SUPPORTING THEM ALL TOGETHER, THEY WILL CHANGE, OTHERWISE WE ARE GOING TO HAVE A VERY BAD LIFE UNTIL THEY DIE. And they could stay forever if we let them, like it happen with Internet Explorer 6.

So this is the last day I support Internet Explorer 7 - 9, I will politely reject make any cosmetic fix for IE, and will reserve the cool stuff only for Grade A Browsers.

Web developers of the world, get united against Internet Explorer 7 -9.

PD: Well if you force me to do it, I will still do, but against my will, hahahahaha.



lunes, 13 de agosto de 2012

touch draggable for iPad/iPhone

Some time ago I had to implement a good draggable plugin for mobile devices (iPad and iPhone), the current app was using the jquery ui draggable and it was good (very good) in the browser. But sadly it was not that good on mobile, it was choppy and not really nice.

We had layer to simulate the mouse events on the devices that does not support it, and that made the jquery ui plugin to work properly. Well at least as good as it could be on mobile devices.
But somehow (maybe because in my interior I had a designer/UX soul) I feel it was not good enough, the performance was not that great and that was very sad. jquery ui draggable uses top/left properties to move the elements around, and since those properties are not hardware accelerated, it does not look good on the iOS devices.

But css transforms are hardware accelerated so I took the decision (about one year ago) to make this very tiny widget implementing the same interface of the jquery ui one (well only the one I needed at least) and the result is this widget, which seems to perform better than the current version of the draggable one from jquery ui. I'm pretty sure the next version is going to fix this for mobile/tablet devices, but just in case you feel adventurous, like to take risks or just like to play with new code, you can use this one and implement the rest of the interface that is missing here.

Source code:
https://github.com/royriojas/touch-draggable

Demo: (make sure you visit it on an iPad/Android)
In the case of android it seems the experiment at the bottom is not working not sure why yet
http://dl.dropbox.com/u/16252882/royws/td/demo/touchdraggable.html



Bye!

jueves, 21 de octubre de 2010

Yet Another Validation Plugin… Again!

Well this is the first widget wrote by me from scratch that will include in my End of studies project Astrea. This is a simply widget but a really useful one. 
Validate forms is a very common task, and is usually performed either writing custom functions for each field like is suggested in this page http://www.w3schools.com/js/js_form_validation.asp., which could be considered "the old school way". Another approach is to use a plugin that involves the writing of few lines of javascript to perform the validation, wiring each field with the type of validation that will perform and with the error message that is going to be used. Like in the case of this jQuery Validation Plugin http://jquery.bassistance.de/validate/demo/marketo/. and Another plugins try to improve the way validation is done, like this one http://www.devx.com/webdev/Article/31695
While they do a great job validating the fields, which is what you expect from a validation library in the first place :), it is not always customizable enough. There are situations when you may want the validators look differently or be in a completely different position in the form layout. Other times, you don't want to use the form to send the data directly maybe you just want to extract the value fields as a JSON Object and send that object to the server using Ajax, etc.
Well This is Yet Another Validation Plugin. It is not perfect but include a bunch of features that I found useful in all the time I'm doing web development.

 

Features

  1. It is completely customizable with CSS, and since is manually located in the form layout, it could appears in any position. And the error messages can contain whatever you need from plain text to html.
  2. It is unobstructive, and somehow aspect oriented. The behavior of the validators is set using data-* properties
  3. It is possible to add new validators and they will work fine (In the case of dynamic forms)
  4. It is simply to use, and I tend to believe that can be easily extended to add support to new type of validators.
  5. It is not restricted to validate one single field. Several fields can be validated at once.
  6. It is possible to validate just a subset of the validators, or even just validate one. I plan to support validate outside the main container
  7. It is not only restricted to validate actual forms, any container (a div i.e.) can be used as the container for the validation.
  8. It support asynchronous validation, so actually it is easy to perform Ajax validation with this approach
  9. Each field is also validated on blur, change, while the user is interacting with the field.
  10. can validate any type of fields, radios, checkboxes, etc.
  11. Out of the box this plugin supports the following validation types: required, compare, range, regex and custom. Using the regex and custom validators it is possible to perform almost any kind of validation.

Example of Validator Widget

Go ahead to the result tab to see in action and use the html tab to see the required html, javascript and css
You can find the code here in the Astrea repo. under the examples folder.
To know how to use it take a look to the source code in the example above, I will include a brief documentation later.
The widget is implemented using the widget factory from jQuery UI. So I guess this is actually good news if you're already including this library.
The widget is still work in progress, so there are probably bugs and other stuff. But for a first release I guess it is good enough.
If you have developed in ASP.NET you can find this validator plugin somehow similar to the ASP.NET validator component. That is intentional. I had to work on a PHP project after 4 years of been developing with ASP.NET and missed the validators, and like a lot of us, well I just like to reinvent the wheel and still this can be used for my End of Studies Project. (Yes I know that I ended the University 4 years ago, But I guess it is better late than never)

 

know Issues.

  • To support async validation, the custom validators receive a callback function as part of the arguments. It's up to the programmer to call it with the right validation value. An example of async validation will be included later.
  • If more than one validator is assigned to the same field, if the first fail and the second succeed the failed class gets removed so the visual hint to denote that a field has failed the validation is lost. This will be fixed soon.

 

Short FAQ

Licensing?

While this validator widget has been made for my own consumption, I guess that everybody can use it freely and improve it if is required. The source code is on Github under the Astrea project (Astrea is the name of the Library that I'm looking to finish as my End Of Studies Project). The Project will be released under the LGPL and MIT licenses. So Feel free to use it.

Can't find the documentation?

That's my fault, I haven't enough time to write a proper documentation for this widget yet. I promise I will include one soon. For now you can see how it works live in the code example above.

Can't find the unit tests?

My fault again, this project is just starting and I will love to include unit tests for all the widgets that I will include as part of this Library. So Unit testing using QUnit will be added in the future.

Why not use the HTML5 validators?

Well actually I believe is a good idea to use HTML5 Validators, but the problem with this, is that is not supported by all browsers at this point. I will keep a close eye to how the HTML5 validators evolve and will update this library accordingly.

Validators seems to not been working on Browser XX.XX?

This first release has only been tested in later versions of Mozilla Firefox and Chrome by now. I haven't had time to test it thoroughly in all browsers. So it is possible some issues could appear.






domingo, 21 de junio de 2009

Yahoo Developer Network – All APIs page

Today while was trying to make a custom control to convert currencies, I faced an ugly problem: The free soap web service that I was planning to use was simply down. A big problem considering the time I had to made that control.

After some goggling I found some sites that perform this kind of job. Some of them were using originally the same web service I was trying to use and because they were facing the same problem as me they decide to change it. They were using somehow the YAHOO finance quotes service to retrieve the exchange rate between two currencies, but they were making the calls directly at the server side (trying to do it using Ajax raises the Cross Site Scripting problem).

Then I was curious about to know if somehow the YAHOO finance service could had some kind of REST API that could help me to obtain this value directly. But I was not lucky and couldn’t find that…

But I found something even better the Yahoo Developer Network - All APIs page and there I found a lot of interesting things… really a lot. But the most impressive think I found was the YQL.

The YQL stands for Yahoo! Query Language. This is a really impressive concept. It basically allows to make calls to almost any web resource (html pages, dynamic pages and any other resource) and query this result using css or xpath to retrieve the parts of the content that are relevant for us in JSON or XML formats. And it supports make Cross Site Scripting calls too!

The potential that I found in this tool is really amazing you can retrieve almost any relevant information from many sites and use it in the way you want.

YAHOO has some good resources. Really good resources!

sábado, 20 de junio de 2009

Testing Windows 7

I just finished the installation of all the programs that I usually use every day on my computer with the RC1 of the Windows 7. And I must admit it was relatively easy to get it working fine. I had some troubles but they were quickly solved.

Some of the aspects about this new Windows version are really nice.

  1. The installation itself was easy. I remember I tried to install Vista RC1 a long time ago, It was just terrible, a lot of components of my computer just won’t work ever on that because the drivers for them simply didn’t exist. This time instead almost of my hardware components were ready to use, just after the installation. The Wireless USB receiver, the USB web cam and my two audio cards were the exception, but I didn’t have any trouble trying to install the vista version of the driver that came with the USB receiver, or with the driver version of Vista for my two audio Cards (Soundblaster Audigy 2 Platinum, and the default integrated audio that came with my Intel DP35DP Motherboard). I found the Driver version for the Intel Integrated Audio on the Intel website, and even when they claim that the driver was beta also it is doing really good right now.
  2. The Aspect of the Desktop. I don’t know if Microsoft copy the new desktop style from others Operative Systems, I will only say that it looks good, I seems a lot like Vista, but with less invasive warning windows (yes they’re still there). Well I must admit I have not used Vista too much, I really didn’t use Vista on a regular basis like to make a fair comparison. But comparing Windows 7 with the well loved Windows XP you really see some good changes in the UI. I’m tempted to believe that this instance of Windows 7 is running faster than my old good XP.

I will post more comments about Windows 7 later… for today it is time to stop!

Bye.

image

image

image

image

image

image

viernes, 19 de junio de 2009

Export to CSV in Unicode format so Excel can read Japanese characters in the right way

To make this history short, here is the problem I had. The Client wants to export the data from a report (basically a table) in csv format. This data could contain Unicode characters (basically Japanese characters). This file was intended to be used to move the data to other programs like excel or others.

Well to solve that requirement i made this method, that basically receive the data ready to be put in the csv format and save it to the response.

protected void ExportToCSV(object sender, EventArgs e)
 {
    if (String.IsNullOrEmpty(CSVData.Value)) return;

    var strFileNameexport = FileNameHidden.Value.Replace(" ", "_");
    Response.Clear();
    Response.ClearContent();
    Response.Buffer = true;
    Response.ContentType = "text/comma-separated-values";

    Response.ContentEncoding = Encoding.UTF8;
    Response.Charset = Encoding.UTF8.HeaderName;
    var data = CSVData.Value;    

    Response.AddHeader("Content-Disposition", string.Format("attachment;Filename={0}.csv", strFileNameexport));

    Response.Write(data);
    Response.End();
}

As you can see as far to this point everything seemed to be working fine. But suddenly when we try to open a exported file that contains Japanese characters, Excel was not able to display those characters. It replace those characters with garbage

So to Solve the Problem we...

  • found that excel expects the csv file to be in "utf-16le" (UCS-2 Little Endian) (weird, really weird).
  • when you put the data in this format, the "," character is not longer a valid column separator (even more weird, weird!!!!) so you need to use other character like "\t" (I know, I know... if you use \t as a separator the mime type should tab separated value files, but Excel seems to don't complain about it.
  • It is also recomendable that you enclose the data for each cell using quotes, this way the values inside won't be interpreted wrong if a separator character is present there.
  • then realize that we were receiving the data in utf-8 format so we first need to convert the bytes from utf-8 to utf-16
  • And the most important note: YOU NEED TO PUT THE MARKER BYTES SO THE PROGRAMS COULD RECOGNIZE THE ORDER OF THE BYTES IN THE FILE TO KNOW IF THEY ARE IN LITTLE ENDIAN OR IN BIG ENDIAN you can found a lot of information about it in the internet. but no one really tells you that this is necessary to make the file recognizeable by Excel as a csv file.
private static byte[] GetUCSStringFromData(string value)
{
    if (String.IsNullOrEmpty(value)) return new byte[] { };

    value = value.Replace("\",\"", "\"\t\"");

    var utf8Encoding = Encoding.UTF8;
    var utfBytes = utf8Encoding.GetBytes(value);

    var ucs2Encoding = Encoding.GetEncoding("utf-16le");
    var ucs2Bytes = Encoding.Convert(utf8Encoding, ucs2Encoding, utfBytes);

    var bytesFinal = new List {0xff, 0xfe};
    foreach (var b in ucs2Bytes)
    {
        bytesFinal.Add(b);
    }

    return bytesFinal.ToArray(); // ucs2Encoding.GetString(ucs2Bytes);

}

protected void ExportToCSVForExcel(object sender, EventArgs e)
{
    if (String.IsNullOrEmpty(CSVData.Value)) return;

    var strFileNameexport = FileNameHidden.Value.Replace(" ", "_");
    Response.Clear();
    Response.ClearContent();
    Response.Buffer = true;
    Response.ContentType = "text/comma-separated-values";

    //Those lines makes it possible to work with UCS2
    Response.ContentEncoding = Encoding.GetEncoding("utf-16le");
    Response.Charset = Response.ContentEncoding.HeaderName;

    var data = GetUCSStringFromData(CSVData.Value);

    Response.AddHeader("Content-Disposition", string.Format("attachment;Filename={0}.csv", strFileNameexport));
    
    Response.BinaryWrite(data);
    Response.End();
} 

So never forget it!

martes, 12 de mayo de 2009

Intellisense in NHibernate Mappings in Visual Studio 2008

I found this good post in StackOverflow, I put it here simply to have it always present.

To enable it, try copying the following files into: C:\Program Files\Microsoft Visual Studio 9.0\Common7\Packages\schemas\xml, or into C:\Program Files\Microsoft Visual Studio 9.0\Xml\Schemas.

I'm not sure which is the right place and I put them into both of mine but it works for me.

  1. nhibernate-configuration.xsd
  2. nhibernate-generic.xsd (I could not find this file in the last version of the code of NHibernate
  3. nhibernate-mapping.xsd

You can get the files from the source of nHibernate

Taken from here

TableTypeString property of Dialect Class is never used in NHibernate

I was wondering why TableTypeString property of Dialect Class is never used inside the NHibernate library, the property is there, but when I try to find usages of this property, no usages were found.

I needed to use this property because I was writing a special Dialect for MySql to be able to generate InnoDb Tables and to make their charset UTF-8 by default in despite of the default charset of the Database.

I found an example of this in this post (Teamwork, MySQL and UTF-8), the code there is for Hibernate in Java, so instead of use the getTableTypeString getter in NHibernate there is a TableTypeString property.

So, I subclass the MySqlDialect to make my own Mysql5InnoDbUtf8Dialect, but it didn’t works. Looking at the code I found that the Table class in Hibernate differs from the NHibernate Class in the SqlCreateString method. At the end of that method we found in the Java class

if ( comment != null ) { 
	buf.append( dialect.getTableComment( comment ) ); 
}  
return buf.append( dialect.getTableTypeString() ).toString(); 

And at the end of the same method in the NHibernate class we found

if(string.IsNullOrEmpty(comment)==false)
{
	buf.Append(dialect.GetTableComment(comment));
}

return buf.ToString();

So as you can see if the TableTypeString property have to be used somewhere, this is the place, and currently is not used(If anyone knows why please, please let me know!)

so I make the change in the code, in the Table Class at the end of the SqlCreateString method (see code below)

if (string.IsNullOrEmpty(comment) == false)
{
	buf.Append(dialect.GetTableComment(comment));
}
			
return buf.Append(dialect.TableTypeString).ToString();
//return buf.ToString();

and recompile again Nhibernate. After that my new Dialect was working very Nice!

I'm not so sure if that is the best way to acomplish what I was needing to do (create tables with UTF-8 charset by default). Sure, if you have control of the database you can create the database with UTF-8 charset by deafult, but I really want to found a way to do it by code and not in the MySql Administrator.

Well let's work again...

jueves, 23 de abril de 2009

Dealing with Back Button and Secured Applications

Today during the development of my current assigned project, the client registered a really tricky bug. In our system we are using ASP.NET 2.0, and some times we do some ajax calls to improve the perfomance of the applications and to avoid been making postbacks when only a very few information really changes.

The problem with that approach was that when the user interacts with one of the pages that has ajax enabled behavior, and then navigates to a new page in the system and then click the back button the page was restored to its original state and the changes that were made using javascript were lost, since the page was served from cache and not for the Server.

The other problem related to the same issue was that once the user has been logged in, navigate to some pages and then logout, if he pressed the back button in the browser the pages where he was navigating were there and that was representing a potential security hole to the system.

in ASP.NET in the PageLoad Event of your page (the master page could be a better place to put it) you can try this

//Turn off cache
Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache);

And Please!!!!! make yourselves a favor and add this line!

Response.Cache.SetNoStore();

Sometimes the browser just ignores the Cache Directive.

I found a post that says that using the beforeunload event the page will be forced to reload the content from the server but it seems not to be working.

More information about this particular issue could be found here:

http://www.hunlock.com/blogs/Mastering_The_Back_Button_With_Javascript

viernes, 20 de febrero de 2009

Mysql UTF8 Encoding, and how to save Chinese/Japanese characters.

One of the requirements of the current application that I’m developing is to be able to save Unicode characters, but when we save the data to the db, the unicode characters were converted to a sequence of question symbols  (like these ??????) and that was really annoying.

Well we do some googling and found the answer here:

http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html

Well to make the story short, if you want to store unicode characters be sure that the my.ini (mysql.cnf in linux) has the following lines in it.

collation_server=utf8_unicode_ci
character_set_server=utf8
character_set_client=utf8

I don’t know why, but It seems than the Mysql Connector for .Net was sending the queries statements  as non unicode, so, when the data arrives to the db it arrives with the wrong encoding and it stores the question symbols instead of the unicode characters.

If you don’t have control of the mysql Server, maybe you could run the equivalent sql statements before the queries, something like this :

SET NAMES UTF-8

I don’t know how to do it when you use NHibernate, (because the sql statements are sent by the NHibernate layer), but I read some posts that said it works.

Hopefully it can helps someone else.

Important note: those lines should be added after the default-character-set to work properly

miércoles, 28 de enero de 2009

Steps to deploy an ASP.NET 2.0 web application in Apache 2 using mod_mono 2.2 (In OpenSuse 11)

this is a quick list of the steps required to deploy .Net applications under Apache 2 and mod_mono in OpenSuse 11

  1. Compile your web application. You can do it on Linux using MonoDevelop or using Visual Studio 2008, we usually compile it on Linux just to be sure the website will no have problems to start.
  2. Create a folder for your application.

    In our case we created a folder named "WebApp " under this directory:

    /usr/share/mono/asp.net/apps/

    just because there were other demo applications that come with mono.

    Be sure to give this folder the right permissions. open a Console and log in as the root user (sudo -s) and move to the folder. Use the chmod command to change the permissions if necessary (chmod 777 ./ will enable all the permissions under this folder, you can try adding only the necessary access level, because 777 enable all of them)

  3. copy the contents of the compiled web application to the new folder created.
  4. navigate to the folder "/etc/apache2/conf.d" and create a text file named "WebApp.conf"
  5. copy this code inside the file
        Alias /WebApp /usr/share/mono/asp.net/apps/WebApp
        MonoApplicationsConfigFile WebApp /etc/xsp/2.0/applications-available/WebApp.webapp
        MonoServerPath WebApp "/usr/bin/mod-mono-server2"
        MonoSetEnv WebApp MONO_IOMAP=all
        <Location /WebApp>
         Allow from all
         Order allow,deny
         SetHandler mono
         MonoSetServerAlias WebApp
        </Location>
    
  6. As you can see in the line 2 we point to a WebApp file that should be located in the /etc/xsp/2.0/applications-available/, so navigate to that folder an create a WebApp.webapp text fileand put this code inside this file:
    <?xml version="1.0" ?>
       <web-application>
        <name>WebApp</name>
        <vpath>/WebApp</vpath>
        <path>/usr/share/mono/asp.net/apps/WebApp</path>
        <enabled>true</enabled>
       </web-application>
    
  7. Now is time to restart apache, so run this command: "apache2ctl restart".
  8. Now open your browser and navigate to http://localhost/WebApp/Default.aspx (if Default.aspx exist or maybe other page that you have in the site)
  9. If all went without errors now you can enjoy your new website running under Apache 2 using mod_mono 2.2

Notes: There a lot of things that could go, wrong, maybe you will need to first Install Apache 2, if you don't already have it in your Linux distro, or maybe the mod_mono 2.2. Those tasks are out of the scope of this post. The present list of steps were written here just to never forget them.if you need help to install apache 2 or mod_mono, or even MONO 2.2, then you will need to do some googling by yourself. sorry :(

martes, 27 de enero de 2009

MONO Formview/ObjectDataSourceView Bug?. Why some of the sections of my website Dissapear?

UPDATE : MONO Has Fixed this Bug in the 2.4 release, at least it seems to be fixed looking at the source code

But it seems to fail when the result is null because it returns a new Object collection with a null element wich seems to be wrong, so this patch could still apply under some circunstances

Well some days ago, while we’re developing our current project release using MONO 1.9.1, MONO 2.0 were released. It was including a lot of bugfixes and new features. So now we were able to compile the application in Linux without make any modification. We were really happy.

But our happiness was futile. Suddenly we realize that some portions of the Website were  not been rendered. We review the rendered code and realized that the formviews were not been rendered properly.

The Gridviews and other ASP.NET controls were rendering good, but, not the formviews. As we had to continue with the project release, we decide to turn back to MONO 1.9.1. At the end of the past Sprint, we decide to rertun and investigate why the the Formviews were not rendering.

First we were suspecting that it could be maybe a Viewstate Issue, (When we turned off the viewstate for the formview controls in MONO 1.9.1 they were not rendered also, turning the viewstate on solved the issue). But turning on or off the viewstate in MONO 2.0.x had no effect. The formview were still not rendered.

So, after some time of digging into the code, creating our custom Formview controls that inherited the ASP.NET Formview, overriding some methods and using the Response as Console for debugging (God! Mono needs a Debugger!) we found the issue.

So, here is:

The problem is located at the ExecuteSelect Method of the ObjectDataSourceView Class that is located in this path inside the MONO Source directory:

mono-2.2\mcs\class\System.Web\System.Web.UI.WebControls\ObjectDataSourceView.cs

(The MONO sources can be obtained from this location)

the method has this lines of code that could be wrong:

if (result is IEnumerable)
return (IEnumerable) result;
else
return new object[] {};

As you can see when you have methods that return only a single instance of an entity, and those methods are used as the SelectMethods of the ObjectDataSource Controls, the ExecuteSelect will consider they’re not IEnumerable instances so it will return an Empty collection, causing that the Formview Controls render nothing at the Aspx pages.

the correct code should be:

if (result is IEnumerable)
return (IEnumerable) result;
return (result != null)? new object [] { result } : new object[] {};

as you can see, now only if the result is null will be returned an empty collection otherwise a collection with exactly one element is returned.

So doing that modification, and recompiling the MONO Sources you could make your Formview Controls work properly again.

I reported the bug, but I’m not so sure if that is really a bug, (because maybe it is intended to work like that in the specs…) or if it will be solved soon by the MONO team.

Well, here is some useful information.

Details of the Bug, and some comments about it:

http://go-mono.com/forums/#nabble-td21435835

To re compile MONO Sources, after do the code change:

http://blog.palehorse.net/2008/11/06/my-adventures-installing-mono-20-on-centos-4-to-work-with-apache-via-mod_mono/

Good Luck, Hopely this could help someone else!

martes, 25 de noviembre de 2008

OpenSuse 11.0 plugin qt_pkg error

Sometime ago I downloaded the VM ware image of OPEN SUSE 11.0 that comes with MONO 2.0, but there were some annoying bugs with this version of MONO that was taking me crazy so as soon as the 2.0.1 version of MONO appeared, I wanted to upgrade to that version.

I launch the YAST2 application just to find that this application was not able to be started because it was missing the qt_pkg plugin. It was so annoying!!!!

After some research in google I finally found the solution in an Italian forum:

http://www.suseitalia.org/modules/newbb/viewtopic.php?topic_id=18739&forum=1&post_id=107616

So, basically to make the story short if you are having this problem too, try this, it worked for me!

  1. open a shell terminal
  2. type : sudo zypper in yast2-qt-pkg yast2-qt
  3. Answer yes to the download question.
  4. Wait and lauch Yast2! Now it should work normally!

Really thanks to “Anubis” for the solution to this really annoying error!

jueves, 2 de octubre de 2008

To Validate or not to Validate, XHTML, Dojo and Custom Attributes

Well, I must admit it. Now I really confused, I was validating the XHTML output of the pages of our current project, and because we used some custom attributes to create some widgets using a combination of Javascript and HTML (a custom attribute is an attribute that is not part of the HTML or XHTML specifications, like in <div id=”dialog” custom_type=”dialog”>, the custom attribute is “custom_type”), I realize the pages will fail the validation process, and as I was suspecting they did, they fail. But I remember that a big and popular Javascript toolkit uses custom attributes too, so, I think, mmm, “let’s look how they did to make their html output be valid XHTML”, and what I found has confused me a lot.

Dojo does not produce valid XHTML, they remove the Dojo namespace from their markup, so their pages don’t validate anymore (http://dojotoolkit.org/book/dojo-porting-guide-0-4-x-0-9/widgets/general). Why? I don’t really understand why?, I really want to know it.

Well, I think they’re tired of the war: “The Parser” posts this:

[...]

There's a big religious war about whether pages validating or not is important and I don't want to beat that dead horse anymore.

[...]

Lucky me, Dojo was not my favorite Javascript toolkit, and in my current project I am not using it, I am using JQuery (Dojo fans, sorry, if you need to make your code valid, as far as I know, you will have to make changes to the parser!!).

But, what can I do now? Do I must forget about Validation issues?

Well I was looking deeper and I found a really nice post from Jonh Resig http://ejohn.org/blog/html-5-data-attributes/

It seems that HTML 5 (http://www.w3.org/html/wg/html5) includes some cool features!, like the data-attribute to declare custom attributes, so in the future, I will not have to deal with custom DTDs or custom XHTML Namespaces! (Namespaces are not used to validate XHTML, Thanks for the comment zcorpan!).

But, now I’m more confused! What should I do?.

Should I still try to make the pages validate or not?

Well I think I could use XHTML Namespaces to make it validate.(I will use the approach of the data-attribute in order to keep compatible with the HTML5 specification) So I will have to do some changes now. A little bit more of work, but at the end of the day I will feel better with myself. But seriously I’m already confused, because the future is not as clear as I was thinking... Ok, don’t you believe me? Take a look to these good articles:

http://xhtml.com/en/future/x-html-5-versus-xhtml-2/#x5

http://www.robertnyman.com/2007/02/05/html-5-or-xhtml-2/

Goodbye.

---

Take a look to this post too:

http://marcgrabanski.com/article/5-tips-for-better-jquery-code

miércoles, 1 de octubre de 2008

Regular Expresions

RegularExpressionLogo

Hi, again…

Regular expressions are extremely useful, you can think on them like “wildcards on steroids” (I like that phrase I found it here: http://www.regular-expressions.info/index.html), they save you a lot of time when you do a search inside a string and want to return the matches based on a pattern or when you want to do replacements based on them. I don’t really remember when I started to use Regular Expressions but now I use them quite often. So here are some tips that I’ve found so far, in Javascript:

(If you already know a lot about Regular Expressions, please go directly to my seven tip, maybe you can find it useful).

1. You can match a specific character using its hexadecimal index in the character set: e.g.: \xA9 matches the copyright symbol in the Latin-1 character set.

This one is really useful when you’re working with Unicode, there are several considerations if you plan to work with Unicode, take in mind that Unicode may encode a single grapheme as two different characters, e.g.: “à” could be “a” and “`” so many regular expressions could fail mysteriously, and it could be hard to find why.

2. Use shorthand characters when possible, e.g. : use \d instead of [0-9] and \w to match any word character (alphanumeric characters plus underscore). The regular expression will be more readable.

3. Take in mind that “.” matches (almost) any character. Well this will work different in IE and in Firefox, in IE the “.” Matches even line breaks, and in Firefox line breaks won’t be matched. This difference is really important to remember.

4. Use capture groups if you plan to do something with the results, you can define a group using “(” and “)” like in (q)(u) (this will match q followed by and u and you will have 2 capturing group, to access each group use $1 and $2 for each group. Please note that the groups index begin in “1”, the group 0 contains the entire match not a specific group.

5. Lazy Repetition feature is useful but it can be expensive, like in <.+?> that matches any html tag (invalid tags inclusive!), if you now the exactly set of characters expected is better to use <[^<>]+>, it will perform better that the “.” Character.

6. You can create a regular expression in Javascript in two ways:

a. Using literal notation: /(q)(?=u)(u)/g

b. Using: var regx = new RegExp(“(q)(?=u)(u)”,g);

Take in mind that for the second way you need to be careful when you use the special characters like “\”.

E.g.:

/((ht|f)tp(s?):\/\/)?((W){3}\.)?(\w)+((\.)(([a-zA-Z])+/?)?)+/g

Var reg = new RegExp(“((ht|f)tp(s?): / /)?((W){3}\\.)?(\w)+((\\.)(([a-zA-Z])+/?)?)+”,g)

Please note that the “\.” in the literal notation is translated to “\\.” when you use the constructor notation.

7. Make yourself a big favor (a really big favor, even if you’re a Regular Expression Guru like my friend Paolo, he is really good with Regular Expressions!), and consider use this free tool:

http://www.gskinner.com/RegExr/

gskinnertool

This online tool is as simply as impressive, it is really complete and the regular expressions created there work quite well in Javascript, you can construct your regular expressions and test them on the fly! (this tool comes to you as a courtesy of my good friend Hans who recommended me to use it, and now I simply can’t imagine work with Regular Expressions without it)

There is also a Desktop version located here: http://www.gskinner.com/RegExr/desktop/ (it needs Adobe Air installed)

or use this other tool:

http://osteele.com/tools/rework/

rework-tool

is really impresive too, and had a lot of features and it is programmed in javascript , but i don’t know why I prefer the first one :P, maybe because it looks nicer.

So that’s all so far.

miércoles, 3 de septiembre de 2008

Google Chrome – just another browser? Or "the" one?

chrome
Well, I must admit, it’s still a young project but it looks really nice. The project was keep in secret for more than one year. I cannot wait to try it, so I downloaded it and installed it. It’s a minimalist browser, it has tabs, and a clean UI.
It seems that it is based on Mozilla and Webkit, and it’s really fast when it comes to javascript performance, it is really fast.
They have created an entirely new browser from the scratch. Why? Well they have collected an entire set of reasons into this clear and funny comic style “googlebook”: http://www.google.com/googlebooks/chrome/
What’s new with this browser?
  1. It’s free, open source
  2. It has support for standards.
  3. It’s designed for the today’s demanding web applications
  4. It has a faster Javascript VM (Yes! a Virtual Machine, so it compiles Javascript instead of just interpret it!!, impressive). Developed by the V8 Team
  5. It provides each tab with his own isolated environment called the Sandbox, so the risk from attacks and from malware on the web are minimized (not completed eliminated, that’s really hard to accomplish even for google!!)
  6. Improved Garbage Collection. (No more memory leaks like in IE?, well, I have to test it!!!)
  7. Nice UI, simple and consistent.
  8. A simpler popup blocker.
  9. It has Google Gears included.
So what’s bad with this browser?
1. I can’t find easily my favorites. (well to be honest, my friend Paolo didn’t find them)
2. They say that each tab runs on an entirely separated process, so, having 10 tabs open, we have then 10 process with all the memory and the resources they need to be opened. Mmm, they claim that his memory management does a great job, and can cope with the challenge… but, let’s try it and look what happens.
3. It has a kind of firebug addon integrated, but, It’s not dockable like the firebug plugin for Mozilla, so it’s a little bit hard to work with it.
So, to resume all in just one sentence…
Google Chrome is not only a Web Browser. It’s an application platform to run Web Applications.
Nice, isn’t it? Well, IMHO, the competence is good for the Web and for us.

martes, 24 de junio de 2008

REST

Representational State Transfer

Roy Fielding's explanation of the meaning of Representational State Transfer

"Representational State Transfer is intended to evoke an image of how a well-designed Web application behaves: a network of web pages (a virtual state-machine), where the user progresses through an application by selecting links (state transitions), resulting in the next page (representing the next state of the application) being transferred to the user and rendered for their use"


Basicamente REpresentational State Transfer que podría ser traducido como Transferencia del Estado de Representación, es un estilo de arquitectura, que pretende aprovechar los factores que han hecho que la WWW sea tan exitosa.

La Web puede verse como una serie de recursos, los cuales contienen información directamente consumible y/o enlaces a otros recursos, cada vez que un recurso es pedido al servidor se está accediendo a un Representación del mismo, y esta representación pone a la aplicación cliente en un estado. Por ejemplo, al pedir la página http://fooserver/products/ (la dirección no existe, es solo de ejemplo) estamos accediendo a un recurso que nos muestra un listado de productos y coloca a la aplicación en el estado A, y si al hacer click sobre el link del producto accedemos a su descripción estaríamos siendo transferidos hacia otro Recurso y por tanto cambiando de estado digamos a un estado B. de allí el nombre de REpresentational State Transfer.

En realidad el concepto no es algo totalmente nuevo, se basa en la idea de cada recurso debe poder ser:

  • Único
  • Accesible
  • Humanamente Legible
  • Independiente del Estado, o agnostico de los Estados Anteriores
  • Bookmarkable
  • Usar sustantivos en los recursos en lugar de verbos. por ejemplo ...products/parts/0012, en lugar de ...products/getPart?Id=0012

Hemos venido usando RESTful Services todo el tiempo, pues es la forma inherente en que funciona la web misma.

Habrá que seguir investignado acerca de REST

sábado, 21 de junio de 2008

Zend Framework + Smarty vs Simple Zend View Script

Smarty

Descripción

Smarty es un Template Engine, o más propiamente un Template Framework. Sus características van más allá del simple reemplazo de variables o reemplazo de tags. Su principal característica es que las plantillas (Templates) solo son leídas e interpretadas una sola vez, como resultado de esta lectura se crea un archivo con código PHP el cual es ejecutado durante los subsiguientes pedidos de las plantillas. Esta característica es conocida como Template Compiling.

Beneficios

  • Es rápido, (ellos ponen en este acápite, EXTREMADAMENTE RÁPIDO).
  • Es eficiente dado que las plantillas se compilan a código PHP, reduciendo el overhead después del primer pedido de la plantilla.
  • Las plantillas se recompilan solo si es que estas han sido modificadas
  • Se puede configurar a gusto, desde los delimitadores, hasta las funciones y modificadores de variables, haciendo que su lenguaje sea realmente extensible.
  • Las estructuras de control (Sections, if, etc) pueden estar anidadas y ser tan complejas como se requiera.
  • Se puede incluir código PHP directamente en la plantilla, pero NO ES RECOMENDADO, dado que va en contra del espíritu de la plantilla.
  • Soporte de Cache integrado. Es decir que se guarda el resultado de la ejecución de una plantilla para un request dado, si otro request con los mismos parámetros es hecho luego se devolverá la página que se tiene en Cache. Puede manipularse que secciones de la plantilla no deben guardarse en Cache.
  • Se puede modificar la función de manejo de Cache (Cache Handler Function) por ejemplo para utilizar una base de datos como proveedor de Cache en lugar del Filesystem.
  • Es extensible a través de su arquitectura de Plugins

Desventajas

  • Programar las Plantillas (Templates) (o Diseñarlos) requiere que la persona encargada (usualmente el diseñador) aprenda un lenguaje de tags y expresiones que pueden serle igual de complejos que aprender la sintaxis del mismo PHP.
  • Sin el uso del Cache de Smarty, el rendimiento decae considerablemente. Y aún cuando se use el Cache, la lectura de un template durante un request es una operación costosa (por el acceso al sistema de archivos) lectura que al parecer siempre se hace, para verificar si el archivo de plantilla ha cambiado y por tanto necesita ser recompilado.
  • Aun cuando se separa claramente la lógica de la Vista de la lógica de Negocio los editores de HTML (como el dreamweaver) no siempre hacen un buen trabajo interpretando los tags del Template System. (aunque hay algunas extensiones para el caso del dreamweaver para que soporte Smarty).

 

View Script (Zend View Default)

Descripción

Zend utiliza por defecto para las vistas los View Scripts, que no son otra cosa más que archivos php (con toda la sintaxis del mismo php) que se ejecutan dentro del scope de la instancia de la vista que lo ha llamado (Zend_View instance) por tanto todas las referencias a $this dentro del archivo de scripts hacen referencia a las variables asignadas a la instancia de la vista. Por ejemplo si en el controller tenemos

$ZendView->Something = ‘here is something’ 

En el View Script se accesa a la variable de esta forma

$this->Something 

Beneficios

  • PHP es por si mismo un Template Engine, los View Script están escritos en PHP, por lo que no sería necesario un Template Engine encima de él.
  • Mayor velocidad en la ejecución de los View Scripts, (Son ya código PHP, por lo que no necesitan ser compilados)
  • No se necesita aprender un nuevo lenguaje, si se sabe PHP se sabe programar View Scripts
  • Se tiene acceso a todo y se puede ejecutar todo tipo de código dentro del View Script pues es un archivo .php común. No se depende solo de las funciones que un Template Engine provee o de los plugins que existan para el mismo.

Desventajas

  • El código php puede no ser tan claro como los tags usados dentro de una plantilla
    • Por ejemplo

SMARTY

<body>	<div>{$variable}</div></body>

VIEW SCRIPT

<body>	<div><? $this->variable ?></div></body>
  • Un diseñador común no suele tener conocimientos de PHP y puede parecerle más fácil aprender el lenguaje de los Templates Engines que un lenguaje como PHP.
  • No tiene estructuras de control ni plugins, por lo que hay que escribir bloques de código php para manejar los loops y la generación automática de html.

 

Conclusión

La elección de Smarty como Template Engine para manejar las vistas dentro del Zend Framework, pasará por la evaluación de ítems como:

  • Experiencia de la gente involucrada en el proyecto
  • Necesidad de tiempo de respuesta de la aplicación (Siempre y cuando el tema del tiempo de respuesta sea algo realmente vital) ver enlance: http://template-bench.iliakantor.ru/. De hecho al ser simplemente archivos PHP los View Script tienen la ventaja. Pues integrar Smarty al Zend Framework involucra un overhead que podría evitarse si se utiliza solamente los View Scripts. Aún cuando este overhead podría ser asumible teniendo en cuenta que Smarty provee un diseño de la Vista “más Limpio”.
  • Experiencia de los diseñadores web involucrados en el proyecto.

En particular me inclinaría por recomendar el uso de Smarty, por ser un Template Framework bastante extendido y bastante fiable y que al parecer no representaría mayores inconvenientes integrarlo con el Zend Framework.

La integración podría realizarse de varias formas. Una de las cuales está incluso documentada en la misma página de Referencia del Zend Framework.

Otras implementaciones incluyen la construcción de una clase Factory que permita intercambiar fácilmente entre plantillas de Smarty y View Scripts de Zend, e integrarla haciendo uso de las clases utilitarias del Zend framework.

Fuentes

Vínculos Web