Custom Tags on IE
December 19, 2008 | Leave a Comment
Internet Explorer has provided a way to implement custom tags since version 5.
While other browsers have similar ways to define custom tags, IE has its own method.
To define a custom tag, you just have to use it. Even if you dont specify how to handle it, IE will display its contents, using the default behavior for all tags (meaning, it just renders whatever it’s enclosed in the tag as plain text).
<customtag>This is a custom tag</customtag> |
outputs:
This is a custom tag
As simple as that.
Custom tags become much more useful after defining a behavior for it. Behaviors are applied to elements on a page, the same way styles are, using CSS attributes.
The behavior tells IE’s render how to processes an HTML tag (custom or not). Everytime IE encounters a tag that it doesn’t recognize,
it checks to see if a custom behavior has been defined for it. If so, it will change from the default action of just render plain text to whatever you have coded.
index.htm:
<html xmlns:customtag>
<style>
@media all {
customtag\:default {
color:#00FF00;
}
}
</style>
<body>
<customtag:default>
This is a custom tag
</customtag:default>
</body>
</html> |
Now, our tag prints all the text in green:
This is a custom tag
Granted, that’s not very interesting, but it demonstrates the point. Our new tag has been properly defined, and now it can be styled.
This doesn’t offer much flexibility. That’s why we can take a further step and fine tune the behavior through JS.
Using an external file, with an .htc extension, we can modify the way IE acts around our tag.
Let’s declare our behavior file
customtag\:default {
behavior:url(customtag.htc);
And the external file that defines the behavior:
customtag.htc:
<PUBLIC:HTC URN="customtag">
<PUBLIC:ATTACH EVENT="onmouseover" HANDLER="Blue" />
<SCRIPT LANGUAGE="jscript">
function Blue() {
ctag = window.event.srcElement;
ctag.style.color = "#0000FF";
}
</SCRIPT>
</PUBLIC:HTC>
<style>
.customStyle {
behavior: url(behaviorCode.htc)
}
</style> |
With this, you can customize or extend a specific behavior to existing tags.
You can also create you own tags, that group together common CSS styles, and apply them to all the text they wrap.
Finally, you can define new tags with an associated behavior.
JL T
Absolute Centering a “flash movie” in HTML with CSS.
December 12, 2008 | Leave a Comment
This code snippet focuses a flash movie in the middle
of the browser, regardless of the resolution of the monitor.
This code is valid for IE and Firefox.
<html>
<head>
<title>Center Flash Movie</title>
<script src="AC_RunActiveContent.js" type="text/javascript"></script>
<style type="text/css">
#center {
position: absolute;
top: 50%;
left: 50%;
margin-top: -240px; /*Half the height of the movie*/
margin-left: -320px; /*Half the width of the movie*/
}
</style>
</head>
<body>
<div id="center">
<script type="text/javascript">
AC_FL_RunContent('codebase',
'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0',
'width','movie_width','height','movie_height','src','my_movie',
'quality','high','pluginspage',
'http://www.macromedia.com/go/getflashplayer','movie','my_movie' ); //end AC code
</script>
</div>
</body>
</html> |
A.T
Bulk insert with Selenium!
December 10, 2008 | Leave a Comment
We all know that when you don’t have access and writing privileges in a database, doing a bulk insert of anything can be nearly impossible.
Some time ago, a customer came to us with the following request:
- He had an excel file with his customer’s data (formatted in a friendly way; ie: one column for each data field)
- He had access to the company web portal where he needed to enter this data
So he requested that we find a solution to uploading the content of that excel file to the website.
We didn’t have access to the database or any information about tables and schema.
At that same time we were using Selenium IDE to automate test cases in a different project.
http://selenium.openqa.org/
http://www.openqa.org/
Since Selenium is able to interact with Internet Explorer, Firefox and other web browsers, we thought of trying to use it to do this automation.
We thought that if we could write a Selenium “test case” to automate the creation of a single customer, we would have half of the project solved. Then we realized that Selenium can export the test cases to C# code.
So we downloaded Selenium Remote Control files that also have .Net client driver from http://selenium-rc.openqa.org/.
When we were able to automate a single customer creation, we looked at the C# code generated by Selenium and saw that we could place a loop inside the code to create as many customers as needed.
selenium.Open("http://MyCompanyWeb/Customer/create.do"); //open web page selenium.Type("txtusername", "myUser"); //enter username selenium.Type("txtpassword", "MyPassword"); //enter password selenium.Click("//input[@value='Access']"); //click access button selenium.WaitForPageToLoad("3000"); selenium.Click("link=Customer Creation"); //click create new customer link selenium.SelectFrame("main"); //set active frame selenium.Type("name", name); //enter name selenium.Type("age", age); //enter age selenium.Select("gender", gender); //enter gender selenium.Type("address1", address); //enter address1 selenium.Type("phone", telephone); //enter phone selenium.Click("action"); //click submit button selenium.WaitForPageToLoad("2000"); Assert.IsTrue(selenium.IsTextPresent("Customer Successfully Created")); //validate congrats message. if congrats message is not displayed, will throw an assertion exception selenium.SelectFrame("relative=up"); //set active frame |
So we created an empty c# project, added the references to nunit and thoughtworks dll’s, then added a winform object and replaced the code of that winform with the code generated by Selenium for a single customer creation.
We updated that code to be able to create as many customers as needed (added the loop) and finally, added the Excel Interop library to be able to read and write excel files from the project.
int index = 0; object rowIndex = 2; //data starts at row 2 while (((Excel.Range)workSheet.Cells[rowIndex, 1]).Value2 != null) //loop until cell(n,1) is null { //do automatic load process (almost same code as above) index++; rowIndex = 2 + index; //move to next row } |
The only part that wasn’t too clear was that you needed to start Selenium server inside your project before using any nUnit or ThoughtWorks functions. Otherwise, it will throw an error when executing.
System.Diagnostics.Process.Start("selenium-server.jar"); |
By the way, don’t forget to stop Selenium server when finishing your process.
//kill selenium server process Process[] localByName = Process.GetProcessesByName("javaw"); foreach (Process p in localByName) { p.Kill(); } |
You can download an example of the code here:
Download Selenium automation code
Happy coding!
SC
Extracting a plain text file from a URL with VB8
November 25, 2008 | Leave a Comment
In order to get a web page in a plain text format, you can parse it how you’d like and extract the data you are interested in, for example, a list or the content of a grid:
Dim Parameters as String = "?zone=florida&city=miami&page=1"
Dim WebReq As Net.WebRequest = Net.WebRequest.Create(www.Houses4Sale.com & Parameters)
Dim WebRes As System.Net.WebResponse = WebReq.GetResponse()
Dim Enc As Text.Encoding = Text.Encoding.GetEncoding("latin1")
Dim St As IO.Stream = WebRes.GetResponseStream()
Dim Sr As New IO.StreamReader(St, Enc)
Dim WebPageText As String = Sr.ReadToEnd()
Sr.Close()
WebPageText is a plain text file (HTML code) containing the whole web page.
From here you may parse the data you need from the web page.
C.H.
Running Javascript code inside VB8
November 21, 2008 | Leave a Comment
This is a brief explanation about how to run javascripts from VB side code in web projects.
In Visual Studio 2003 (Visual Basic), you used the following sentence…
Page.RegisterStartupScript("",YourScript)
In Visual Studio 2005 (Visual Basic), it was changed to…
ClientScript.RegisterStartupScript("".GetType, "", YourScript)
As this is well known by web developers, but it is necessary to add a “\n” (javascript) in order to get a carry return in a single text. But, it seems this doesn’t work with the VS (Visual Basic) sentences described above.
In order to get this to work with them, it is necessary to separate the text with the famous Visual Basic “vbCrLf”.
C.H.
Leading with formats in Java
November 20, 2008 | Leave a Comment
When you are working on a multi-language project that has to work with an undefined number of languages that are used by people from different countries, presentation problems appear with the different formats. But if you are working with Java on a Swing project or a JSP project, you don’t have to worry about these types of issues.
An example of the format presentation problems could be to show the same number to users from different countries. The numbers, as you can see below, are shown in different formats depending on the country.
| Locale | Formatted Numbers |
| German (Germany) | 123.456,789 |
| German (Switzerland) | 123′456.789 |
| English (United States) | 123,456.789 |
A simple way of presenting formatted dates, numbers and currencies in Java is using the Java Locale libraries (java.util.Locale).
By creating an instance of a Locale Object and giving it a specific language code and a specific country code, you will be able to show for example a number in many different formats, depending on the geographic locations that you prefer to use.
Example Code
import java.util.*; Locale enLocale = new Locale(“en”, “US”); NumberFormat nf = NumberFormat.getInstance(enLocale); System.out.println(nf.format(new Float(123456.789))); //it will print “123,456.789” |
Note that the two parameters received by the Locale constructor are (1) “en” that references the English language and (2) “US” that references the USA country. This is one of the many combinations that you can use. To see the available combinations you have to use the “getAvailableLocales()” method. To see all the available geography combinations search for the reference tables on Java api.
Example Code
Locale list[] = DateFormat.getAvailableLocales(); for (int i = 0; i < list.length; i++) { System.out.println(list[i].getLanguage() + " " + list[i].getCountry()); } |
You don’t have to be an expert to use these libraries. Understanding some of these methods is all that you will need to know to get your multi-language application working.
For numbers
NumberFormat.getInstance(). format(number); NumberFormat.getCurrencyInstance(). format(currency); NumberFormat.getPercentInstance(). format(percent); |
For Dates
DateFormat.getDateInstance().format(date) |
Optimizing Images for Web
November 18, 2008 | Leave a Comment
Here I am writing again, this time I’m going to talk about the web images, but in this case, as a simple and pure object.
When you are working on a website and you need to embed images, you must respect some features to optimize your work.
We have three types of formats, below I´ll show you the main features.
- ALWAYS: Images in 72 dpi ( deep per inch )
- Image at the exact height and width ( recommended )
- JPEG, GIF or PNG format ( it depends on the use )
JPEG: Joint Photographic Experts Group ( jpg, jpeg or jpe )
- 10 to 1 compression with little perceivable loss in image quality.
- No Transparency
- Good Quality, less weight, ideal for the web
- 256 distinct colors from the 24-bit RGB color space
- Transparency Available
- Animated Graphics Low Quality
- Middle Quality, less weight, ideal for web graphics with a few colors
- Loses data decompression
- Transparency Available
- Animated Graphics High Quality
- supports palette-based (palettes of 24-bit RGB colors), greyscale or RGB images
- Best Quality, high weight
Now we´ll talk about programs to optimize images for web.
There are a few like PhotoShop, FireWorks, Paint Shop Pro, Gimp (Linux), etc.
I always use PhotoShop, it has a great tool for exporting images to the web.
How to use this tool:
- Open any file or create whatever you want
- Choose File menu -> Save as for Web
- Choose the type of file using Quality Settings Panel
- You can change measurements using Image Size Panel
- You can change color palette using Image Color Panel
You could use this tool with any kind of images or graphics.
Here we have some examples:
| Example # 1 | ||
|---|---|---|
|
|
|
|
|
Original Picture 69.4 kb 300 x 225 px Without any compression |
Saved for web with PS 12.4 kb 300 x 225 px JPEG High Quality (60) |
Saved for web with PS 6.14 kb 300 x 225 px JPEG Medium Quality (30) |
| Example # 2 | ||
|---|---|---|
|
|
|
|
|
Original Picture 111 kb 300 x 343 px Without any compression |
Saved for web with PS 23.6 kb 300 x 343 px JPEG High Quality (60) |
Saved for web with PS 10.7 kb 300 x 343 px JPEG Medium Quality (30) |
Thank you and see you next time.
Julián J. Lamanna
Mainward Web Designer
Bibliography:
http://inobscuro.com/tutorials/read/35/
Enhancement the gui of web apps using Javascript - Part I
November 17, 2008 | Leave a Comment
Using Javascript’s modern libraries, it is easy to modify the existing
GUI’s of web apps without editing the source code.
You can take advantage of this option when you need to modify the
behavior or the look & feel of stuff that appears all over the app.
For example editing the HTML of an Open Source app., even if they are
separated in a layer using templates, implies that in the future you
will need to merge all the files for every new version. Using javascript
you only have to add the same link at the top of your html’s header.
Following the example above, I used JQuery (a Javascript library) to add
a filter on every SELECT having more than 5 options.
/** * Filter the select options keeping only the ones that match the text in the text input. */ function select_filter(input,select_id) { var select = $('#'+select_id); if(input.options == null) /* Store the orginals options as an attribute of the text input. */ { input.options = Array(); var i = 0; $('#'+select_id + ' option').each(function(){ input.options[i] = Array($(this).text(),$(this).val()); i++; }) } select.empty(); /* Clear the select. */ for(var x = 0; x < input.options.length - 1; x++) { var text = input.options[x][0]; var value = input.options[x][1]; var expr = new RegExp(input.value + '.*'); if(text.match(expr)) /* Add a new option for each matching entry in the original list. */ { var textnd = document.createTextNode(text); var option = document.createElement('option'); option.value = input.options[x][1]; option.appendChild(textnd); select.append(option) } } return true; } /** * Create an input text after every select containing more than 12 options. */ $(document).ready(function(){ var x = 0; $('select').each(function(){ if($(this).find('option').size() > 12) { id = 'select_' + x; $(this).attr('id',id); $(this).css('width','250px'); $(this).after('<br/><input type="text" style="color:#bbb; width:250px;" id="select_handler_' + x + '" onkeyup="select_filter(this, \'' + id + '\')" value="Filter...">'); x++; if($(this).attr('multiple') == 1) { var size = $(this).attr('size'); $(this).attr('size',((size - 1) > 0) ? size - 1 : size); } } } ) }) |
In the next article I’m going to show you a more complex example.
JPF
Converting Mac OSX fonts to the TTF format
November 11, 2008 | Leave a Comment
Sometimes we have the need to use a font file from a Mac OsX system. These files have a strange format. Let’s take a quick look at it.
FontName.sitx (Compressed File) * Font Name Folder Font Name Folder Font1 (0 bytes) Font2 (0 bytes) Fontx (0 bytes) __MACOSX Font Name Folder Font Name ._Font1Regular (these are the real fonts) ._Font2Italic ._Font3Bold
-First you have to extract the sitx file
Inside a folder named _MACOSX you will find the real font files. Note that you also have some files under the Font Name Folder, but these are fake ones.
To convert the font files to a format recognized by Linux you need to grab the utility ‘t1unmac’ wich is in included on the t1utils package.
Under Ubuntu/Debian:
# apt-get install t1utils |
Then run the t1unmac command:
#t1unmac -b ._Font1 > font.pfb |
The -b option tells t1unmac to convert the file to a binary postcript format, font.pfb is the name of the resulting postcript font file
You can also use this simple script to run the command for all the files in the directory:
#! /bin/bash for a in $( ls -a ); do /usr/bin/t1unmac -b $a > ~/fonts/$a.pfb done |
That’s it, these fonts are ready to be used under a Linux system, but if you plan to use them on a os that doesn’t support them (i.e. windows) you need to convert them to ttf using a program like F ontforge. In this case we will user Fontforge through its command line interface.
Let’s do it!
First you need to get and install Fontforge
Under Ubuntu/Debian:
#apt-get install fontforge |
Then create a file named pfb2ttf with the lines shown below and place it inside the /usr/local/bin directory with execution permissions.
#!/usr/bin/fontforge # Quick and dirty hack: converts a font to truetype (.ttf) i=1 if($argv[1] == "--nohint") i = i+1 endif while ( i<$argc ) Print("Opening : " +$argv[i]); Open($argv[i]) Print("Saving : " +$argv[i]:r+".ttf"); # ScaleToEm(2048) if($argv[1] == "--nohint") Print("---- No autohinting ----"); ClearHints() DontAutoHint() endif RoundToInt() Generate($argv[i]:r + ".ttf") i = i+1 endloop |
Then run this command for each file you want to convert in the following way:
pfb2ttf font.pfb
The result will be a file in True Type format (ttf). And that is pretty much it.
Enjoy!
JMS
jWYSIWYG: Lightweight rich editor for JQuery
October 22, 2008 | Leave a Comment
jWYSIWYG is an XHTML compliant rich editor, written as a JQuery plugin. Compared to other alternatives such as TinyMCE or WYMEditor, which is also a JQuery plugin, jWYSIWYG is amazingly lightweight, at only 7k when packed. Despite that, it’s still very powerful and, following the JQuery philosophy, it’s also easy to use and integrate with your projects.
Some usage examples
Attach an editor to all textareas:
$('TEXTAREA').wysiwyg(); |
Hide some options:
$('#myeditor').wysiwyg({ controls : { insertImage : { visible : false }, decreaseFontSize : { visible : false }, increaseFontSize : { visible : false } }, }); |
You can even attach a style sheet to be used with the content being edited, for example to allow the user to preview how the content will look in it’s final destination:
$('#myeditor').wysiwyg({ css : 'styles/editorpreview.css' }); |
Finally, you can add custom controls to the editor panel
$('#myeditor').wysiwyg({ controls : { myControl : { visible : true, exec : function() { alert('Hello Dolly'); }, className : 'myControl' } } }); $('.myControl').css('background',"url('imgs/myControlBg.png') no-repeat !important;"); |
MC