Wednesday, July 13, 2011

A reading summary of Android Dev Fundamentals

A reading summary of Android Dev Fundamentals
Android -- Linux, multi-user OS and middleware, key applications
support : 2D, 3D graphics, SQLite, webkit browser

A application is composed of one or more different components.
Components: Service, Activity, Content Provider, Broadcast Receiver
Manifest file: must declare all components in the application, minimun version of Android required, hardware required.
Non-code application resources (images, layout files, strings) should include alternatives for different device configuration (such as different layout files for different size of screen)

Activity: a single screen with a user interface

A example to illustrate activities

Service: work in the background, perform long-running operations or fetch data over the network ex: playing music in the background, doesn't provide an interface


Content Providers: manage a shared data for applications, Ex: a content provider which manage user's contact information


Broadcast Receivers: a component that responds to system-wide broadcast announcements.
announcements can be originated from system or application. it doesn't display a user interface, but may
create a status bar notification. Broadcast receivers are activated by an asynchronous message called Intent

Activation of components

Intent: An asynchronous message defines an action for a specific (or specific type ) of components to perform.
bind individual components to each other at run time. Ex: convey a request to show an image or to open a web page.



The Content Resolver handles all direct transactions with the content provider






Resources
images, audio files anything related to the visual presentation of the application. Define animations, menus, styles, colors and the layout of activity user interface with XML. Provide resource separate from your code and provide alternative resources for different device configurations. qualifier for alternative resource: a short string that you include in the name of your resource directories in order to define the device configuration.








Saturday, July 9, 2011

HTML5

A reading summary of "HTML5: Up and Running" by Mark Pilgrim
New HTML5 features:
(1) new semantic elements
<section> <nav> <article> <aside> <hgroup> <header> <footer> <time> <mark>
<nav> for navigation, <hgroup> for h1,h2,...
<time datetime="2009-10-29" pubdate>Oct 29,2009 </time>
if you want to include time
<time datetime="2009-10-29T13:59:59-04:00">
04:00 -- time zone offset
pubdate means one of two thigns if the time is in an article, it means the publication date of the article,
else it's the publication date of the entire document

(2) Canvas
(3) Video
"there is no single combination of containers and codecs that work with all HTML5 browsers, (this situation) is not likely to change recently". "You may need to encode your video more than once to make your video watchable across all browsers"
containers means the formats of the video, such as MPEG,... codec = coder + decoder,
Fireogg -- a firefox extension for encoding video to ogg format, ogg is a one kind of container which is acceptable in many browsers.
(5) geolocation API
which lets you to share your location with trusted website
(6) local storage
provides a way for wesites to store information in your local side computer. the concept is similar to cookies, but cookies is much smaller in size."cookies are limited in size and browsers send them back to the web server every time it requests a new page". Web sites can only access its own values which are stored in the local storage.
(7)Add many Input types 
<input type="password" ...>
there are many other types like:
"search" -- search box
"number" -- spin box
"range" -- sliders
"color" -- for color pickers
"tel" -- for telephone numbers
"url" -- for www address
"email", "week", "day", "month", "time"(time stamps), "datetime", "dateitmelocal"
Automatic validation of input files for email, numbers and www address
(8)Web workers
provide a way for javascripts to run in background as like multiple threads
(9)Offline web applications
such as using google doc offline, cashed the updated results in the local side and update with the server side when connect to the remote server. the web application need to have a cache ability.
(10) placeholder text
"when the input box is not in focus, put the place holder text in the input field, as soon as you click on the input field, the placeholder text disappears"
(11) Auto focus
Browser support auto focus to a text field ('input') which was supported by javascript, it moves focus to a particular input field using mark-up instead of script


Modernizr: A HTML5 detection javascript library that detects support for HTML5 and CSS3 feature
Ex: Modernizr.canvas -- if the browser support canvas
Modernizr.canvastext -- if the browser support canvas text
Modernizr.localstorage -- if the browser support local storage
Modernizr.inputtypes.date -- if the browser support date as an input type

without Moderizer:
if(!!document.createElement('canvas').getContext()) return;
when you create element like canvas, if your browser support canvas then the DOM object will have a canvas element and the element will have 'getContext()' method, else the element will only have common properties.

i = document.createElement("input")
i.setAttribute("type","date")
return i.type != text

check the browser's support for placeholder text
i = document.createElement("input")
return 'placeholder' in 'i'
or Modernizr.input.placeholder

if(Modernizr.geolocation){
navigator.geolocation.getCurrentPosition(show_map);
}else{
}
navigator is a javascript global object
show_map: call back function

Other resources: HTML5 Demos and Examples

Tuesday, May 17, 2011

Project Notepad



I found myself keep having an impulse to take notes on whatever little tricks or
usage of important commands when I was developing applications. However, I didn't know if there is a good way to keep track of the developing process. Of course, writing a blog or a twit may help me to some extent. But, after all, they are not designed for the purpose. I want a simple application, which can record a small piece of command or code, some description for that command, and allow me to search quickly after. I often got into a problem that I was looking for same piece of information over and over again. And don't know if I have taken notes for it somewhere (in my notebook? or in some small piece of paper?) I didn't try to find a killer application to solve my problem, since I think this application is so easy that I can make by myself.

Therefore, I created a small application called "Project Notepad" using PHP+MySQL.
In order to practice Ajax and Javascript, so I used much of them as well.
In "Project Notepad", I can create, delete projects, create, delete, search memos by tags. Each memo is comprised of three elements: command, description and tags.
Tagging facilitate the searching afterwards.
The reason why I used PHP is because I want to use it in my computer and so far as I know the PHP interpreter can hook on the IIS server of Window7, so I can execute the application in my local host. Secondly, PHP is handy in developing such a small applications.

I spend some time in layout and design. I found a very handy tool in arranging colors:
ColorSchemeDesigner
It provides me a set of primary, secondary and complementary colors based on the hue,saturation,brightness and contrast I selected. I used colors from the suggested set of colors and build a nice-looking website quickly.

Here is my application:
Project Notepad

Some work still needs to be done. For example, providing a log-on/in mechanism, then more people can use it and export the memos in xml,text file then users can make a backup in their local machine. At the current moment, it meets my needs well :)

Update

The registration system was done! Now it allows multiple users :)
Give it a try and give feedback or report bugs at the bottom link of "report bugs" :)

Tuesday, April 5, 2011

Rails3 + GeoKit (part I)

GeoKit is a great plugin by Andrew Lewis, which can calculate distance between two points on the earth, search points in your database within a specified distance from an origin, geocoding from multiple providers (convert address to (lat,lng) or vice versa),and find the city,lat,lng of an IP address. Clear explanations: here
Since I am using Rails3, I can not use the old plugin of Geokit. I found many tutorials on how to install Geokit, but most are for the previous version.
Here is page of the new version of Geokit for Rails3. this, However, not all the functions in the old version of Geokit has been updated.

Follow the installation guide

1. put this line gem 'geokit-rails3' in the Gemfile
2. execute bundle install

Then the installation is done

In the code, add acts_as_mappable to an ActiveRecord::Base

class Location < ActiveRecord::Base
acts_as_mappable
end

Then in a controller, you can play with it.
geoencoing example:

@res=MultiGeocoder.geocode('6224 5th Ave. Pittsburgh, PA')
@rev=GoogleGeocoder.reverse_geocode([40.4527037, -79.9219421])

In the view
The (lat,lng) of 6224 5th Ave. Pittsburgh, PA
lat : <%=@res.lat%>
lng : <%=@res.lng%>
The address of
(lat,lng) = (40.4527037, -79.9219421)
<%=@rev.full_address%>


GeoKit for Rails3
GeoKit for previous Rails

Sunday, March 27, 2011

Google Map + RoR

Here I share my experience integrating Google Maps and Ruby on Rails. My platform: Window OS + Rails 3.0.3 + Ruby 1.9.2. There is a bunch of tutorial on how to install the Plug-in for Google Maps in RoR and generate your first map in the RoR.

I followed this tutorial to install the plug-in. I tried the second way of using Github, but it didn't work for me. I got an ym4r_gm folder in my vendor/plugins/ directory, but it was empty. So I used the third way -- manually download the plugin, unzipped the file, put them in the vender/plugins/ym4r_gm. Then copy the javascript/*.js to my public/javascript/ folder. And copy the gmaps_api_key.yml.sample to my config/ folder, renamed as gmaps_api_key.yml

After the installation is done. I didn't apply for the Google Map API key and put it in the gmaps_api_key.yml since I develop and test it in my local machine at current time.
Here is the code:

in the home_controller.rb:

class HomeController < ApplicationController
def index
@map = GMap.new("map_div")
@map.control_init(:large_map => true,:map_type => true)

@map.center_zoom_init([75.5,-42.56],4)
@map.overlay_init(GMarker.new([75.6,-42.467],:title => "Hello", :info_window => "Info! Info!"))
end
end

in the index.html.rb. Because I separate the layout in the application.html.rb, there is only one line in this file.

<%= @map.div(:width => 600, :height => 400) %>


in the application.html.rb
<!DOCTYPE html>
<html>
<head>
<title>Housing</title>
<%= stylesheet_link_tag :all %>
<%= javascript_include_tag :defaults %>
<%= csrf_meta_tag %>
<% unless @map == nil %>
<%= GMap.header %>
<%= @map.to_html %>
<% end%>
</head>
<body>
<%= yield %>
</body>
</html>


At the beginning, I didn't realized I separate my layout and content. So I just paste the example on my index.html.rb, but it turns out to be html code in the index.html.rb such as <html><body> becomes plain text, instead of html code. After I realized I actually separate the layout and content in application.html.rb and home.index.rb, I put the code in red lines to the application.html.rb and leave only one line in the home.index.rb

After I have done the things above, I met another problem:
In application.html.rb, when it calls GMap.header, it should print out the Google Map information in the header such as :
<script src="http://maps.google.com/maps?file=api&v=2.x&key=ABQIA..." type="text/javascript"></script>
but the '<' all becomes & lt; , I changed a bit the 'header' and 'div' method in map.rb, using html_safe when it outputs html code. Tell it not to transform '<' to & lt;

The last thing is in the 'header' method of map.rb, "ActionController::Base.relative_url_root"
is said to be a deprecated method, so it could not locate the ym4r-gm.js
So I change

#{ActionController::Base.relative_url_root}/javascripts/ym4r-gm.js

to

/javascripts/ym4r-gm.js

Here are some other useful information:
another tutorial using ym4r_gm and geokit
A tutorial in Chinese (中文)
Geokit

Thursday, March 17, 2011

Saving changes is not permitted -- SQL 2008

When I try to modify a table, for example, change the "allow null" property of a column, or add a new column to the table, I encounter the message like this:


Saving changes is not permitted. The changes that you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created.


It is said that you may change the metadata structure of the table and cause data loss in 'change tracking information'. However, it is so annoying that at the beginning of developmental stage, when the structure of table is subject to change, that we need to re-create the tables.

Here is the way to turn off the feature:
in SQL2008, Tools->Options->Designers->Table and Database Designers
uncheck "Prevent saving changes that require table re-creation".

Microsoft support: see this

StoredProcedures

Recently, I start to use MS-SQL StoredProcedures instead of hard-coding SQL query in the program. Using StoredProcedure is a good way of separating database queries and ASP.NET code. However, there is slight difference. For example, I want to execute a query like the following:

using (SqlConnection conn = new SqlConnection(connStr))
{
SqlCommand cmd = new SqlCommand("select * from Employee where eid in (15,16,17)", conn);
conn.Open();
SqlDataReader rs = cmd.ExecuteReader();
GridViewResChanged.DataSource = rs;
GridViewResChanged.DataBind();
}

It works perfectly. But if I want to send '(15,16,17)' as a varchar parameter to the StoreProcedure, then it failed:

using (SqlConnection conn = new SqlConnection(connStr))
{
var eids = '(15,16,17)';
SqlCommand cmd = new SqlCommand("queryEmployee", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@eids", SqlDbType.VarChar).Value = eids;
conn.Open();
cmd.ExecuteNonQuery();
}

It is said to be insecure if web users maliciously insert a random string into the database server:
How to pass a list of values or array to SQL Store Procedures

If I insisted using StoreProcedures, I need to learn how to loop the string and get those comma-separated input out in T-SQL.
It is sometimes pain in the ass when the code works perfectly before but failed in a new way of implementation.

Wednesday, March 9, 2011

empty string -- ASP.NET textbox

When I work with TextBox in C# ASP.NET, empty string in TextBox cause problems when it is an input to the sql queries. Because TextBox.Text does not return null value while the textbox is empty.

Empty text is converted to null value in default configuration as I use "SqlDataSource" connection string. But when I need to tackle this manually, here is a handy way:

TextBox tb;
String value = String.IsNullOrEmpty(tb.Text) ? null:tb.Text;

value is the new input to the database.

Tuesday, March 8, 2011

copy StoredProcedures between servers

MS-SQL Stored Procedures is one way that we don't need to ugly hard-code the SQL queries
in the program. However, recently, we have several versions of database update. To export procedures in old database to the new one:

In Microsoft SQL Server Management Studio, Object Explorer,
right-click on the stored procedure, select "Script Stored Procedure as CREATE TO", then either save the stored procedure as a SQL file or create a new SQL window and execute the query file in the new database. After the execution, the stored procedure is created in the new database.
But one thing to be noticed: in the head of the query file, if the names of databases are different,
then the database name need to be changed in "USE [database_name]".

Monday, March 7, 2011

create an overlay on top of an image



recently, while I am editing my web page of project description, I was thinking of creating an overlay on top of the image. It is a feature commonly seen in web pages nowadays.


lets say, we have one outer div, two overlay div, and one image. The overlay divs are smaller and contained in the outer div.

<div class="outer">
<img src="some.png" alt="image" />
<div class="overlay" id="overlay1">This is an overlay1</div>
<div class="overlay" id="overlay2">This is an overlay2</div>
</div>


then set the CSS as:

div.outer
{
width: 570px;
height: 420px;
position: relative;
float: left;
}

div.overlay
{
position: absolute;
opacity: 0.5;
background-color: green;
}

#overlay1
{
left: 20px;
top: 20px;
width: 100px;
height: 40px;
}

#overlay2
{
left: 150px;
top: 100px;
width: 80px;
height: 30px;
}

the most important thing, is the overlay div "position: absolute" and the outer div "position: relative".

Monday, February 14, 2011

jQuery and XML

It is delightful to find an elegant way to read, parse XML file and put parts of its content to the HTML file on the fly. It would be cumbersome for a HTML file if it
keeps all the content in itself. And we can separate the content and its way of presentation. Thanks to the jQuery Ajax function. Terse and easy. Save me lots of efforts!

1. First you may have a XML file like this:
<project type="group">
<name>MyEBag</name>
<time>2009 Fall</time>
<description>Online Transaction Processing</description>
<skill>Oracle</skill>
<skill>SQL</skill>
</project>
<project type="group">
<name>MOCC</name>
<time>2010 Fall</time>
<description>Museum website</description>
<skill>JSP</skill>
<skill>Javascript</skill>
<skill>SQL</skill>
</project>

2. in the HTML file,
//put the code in the jQuery document ready function, the code will be loaded after the page is loaded
$(document).ready(function(){

$.ajax({
type: "GET",
url: "project.xml", //the xml file name
dataType: "xml",
success: function(xml){ // if the xml file is loaded successfully then execute....
//for each project, append its name to the html element id=#prjdesc
//"project" and "name" are the labels in the xml file
$(xml).find("project").each(function(){
$("#prjdesc").append("<h3>"+$(this).find("name").text()+"</h3>");
$("#prjdesc").append($(this).attr("type"));
$("#prjdesc").append($(this).find("time").text());
});
}
});

3. the html file may end like this
<div id="#prjdesc">
<h3>MyEBag</h3>
group2009Fall
<h3>MOCC</h3>
group2010Fall
</div>




Reference: XML.com

Saturday, February 12, 2011

CSS- Two layer Navigation bar


Two-layer navigation bar is neat and commonly seen. Today while I was going through some jQuery examples, I found it can be implemented purely through editing CSS style-sheet

image reference

First, edit the navigation bar to be two layer UL (unordered list) like this:
Then edit the CSS Style-sheet
(1) let's say the class="nav" for the first layer ul element
(2) how to remove the marker in front of list-item? and remove margin and padding from list:

.nav,.nav ul{

list-style: none;
margin: 0px;
padding: 0px;
}

(3) how to display the first layer of navigation as horizontal?

.nav li{

float: left;
position: relative;
}

(4) how to display the second layer of navigation vertically while the first layered of navigation link is hovered?
a. hide the second layer of navigation at first by setting its absolute position (relative to its first parent) as a very negative number (such as -1000px, out of window)

.nav ul{
width: 100px;
position: absolute;
top: -1000px;
left: -1px;
}

b. set the width of the second layer as 100px. If the width is too long or the font-size of list-item is small, there might be more than one list-items appear in the same row.

.nav a{
font: bold 25px Arial;
display: block;
}

c. while the list item of the first navigation layer is hovered, its descendent ul appears relative to it

.nav li:hover ul{
top:25px;
}

(5)change the background color of a link in the second navigation list when it is hovered

.nav ul a:hover {
background: #ccc;
color: #000;
}

A great example: here
You can click on "View" the source code to see its stylesheet. :)

Wednesday, February 9, 2011

prevent robot from crawling your site

Today, my prof. asked me to prevent our website from robot's crawling. After google, I found it is quite simple. There are two ways to prevent robots from crawling your web pages
One way is to ask search engine to remove your whole site from index and prevent its crawling in the future. And the other way is to control access to your website on a page-by-page basis.

To prevent robot from crawling your website, put an robot.txt in your root directory
The content of robots.txt is like:
User-agent: *
Disallow: /
To control the access to your website on a page-by-page basis:

Add the following tag to the head in the web page you are going to restrict the access
<meta name="robots" content="noindex">

How to check your robots.txt?
The Google Webmaster Tools help to check. But you must have a google account.
Block or remove pages from using a robots.txt , click on 'Test A robots.txt file'

Reference
Using Meta Tags to Block Access to your site
About the Robot Meta Tag

Saturday, January 29, 2011

ASP.NET Validator

1. add a validator to a field such as textbox
2. set the "cause validation" property true for the textbox
3. set the "autopostback" property true for the textbox
4. while click on a button, check if Page.isValid
This is server-side examination to avoid 'javascript' being turned off maliciously in client-side browser.
If we want to validate manually, skip 2, 3,
then in 4, call page.Validate("VGroup"), before check Page.isValid.
"VGroup" is the name of the validation group the textbox belongs to.
set the "validation group" property as "VGroup" for textbox.

There are some kinds of validator available, such as 'RequireValidation' and 'RangeValidation'.
'RequireValidation' means the field is required and the validator will check if this field is filled up.
'Range Validation' is to check the input value of the field.

Thursday, January 13, 2011

ASP.NET Ajax Calendar

Calendar is a handy feature in booking systems and is one of the comprehensive features integrated in ASP.NET 3.5.
First, you should download Ajax Control Toolkit
(remember to copy the AjaxControlToolkit.dll into the /bin folder of the web site application.)

Then, add the toolkit into the Visual Studio, see get started with the Ajax Control Toolkit (C#)
  • On the Toolbox window, right click and select "Add Tab", the tab name as "AJAX Control Toolkit"
  • Right click on the tab, select "Choose Items", then browse the directory where you put AjaxControlToolkit.dll, select it.

Last, implement calendar in your program, see Display a simple popup calendar
Calendar Samples shows several calendar types using Ajax Control Toolkit
  • Add a ToolkitScriptManager
  • Add a Textbox
  • Add a CalendarExtender

Tuesday, January 11, 2011

SQL-Exercise

A good website for rookies to review and practice SQL: SQL Practice

Registration for free. There are more than 100 SQL exercises in 4 difficulty levels. It records the progress for users. That means, you can leave and log in to resume the unsolved questions. Pretty handy. Questions are well-designed and helpful to refresh SQL concepts.

Sunday, January 9, 2011

Section 508

'508 web accessibility compliance' was made to facilitate users with vision impairment to browse Federal web.

Youtube video:
Web Accessibility - through the "eyes" of a screen reader made me realized the importance of section 508 for people with disabilities.

1194.22 Web-based intranet and internet information and applications.
from Electronic and Information Technology Accessibility Standards (Section 508)

(a) A text equivalent for every non-text element shall be provided (e.g., via “alt”, “longdesc”, or in element content).

(b) Equivalent alternatives for any multimedia presentation shall be synchronized with the presentation.

(c) Web pages shall be designed so that all information conveyed with color is also available without color, for example from context or markup.

(d) Documents shall be organized so they are readable without requiring an associated style sheet.

(e) Redundant text links shall be provided for each active region of a server-side image map.

(f) Client-side image maps shall be provided instead of server-side image maps except where the regions cannot be defined with an available geometric shape.

(g) Row and column headers shall be identified for data tables.

(h) Markup shall be used to associate data cells and header cells for data tables that have two or more logical levels of row or column headers.

(i) Frames shall be titled with text that facilitates frame identification and navigation.

(j) Pages shall be designed to avoid causing the screen to flicker with a frequency greater than 2 Hz and lower than 55 Hz.

(k) A text-only page, with equivalent information or functionality, shall be provided to make a web site comply with the provisions of this part, when compliance cannot be accomplished in any other way. The content of the text-only page shall be updated whenever the primary page changes.

(l) When pages utilize scripting languages to display content, or to create interface elements, the information provided by the script shall be identified with functional text that can be read by assistive technology.

(m) When a web page requires that an applet, plug-in or other application be present on the client system to interpret page content, the page must provide a link to a plug-in or applet that complies with §1194.21(a) through (l).

(n) When electronic forms are designed to be completed on-line, the form shall allow people using assistive technology to access the information, field elements, and functionality required for completion and submission of the form, including all directions and cues.

(o) A method shall be provided that permits users to skip repetitive navigation links.

(p) When a timed response is required, the user shall be alerted and given sufficient time to indicate more time is required.

This tutorial page provides more details about the standard:
Web-based Intranet and Internet Information and Applications (1194.22)

This is a more elaborate tutorial
Web accessibility for section 508

Friday, January 7, 2011

Rules of thumb on web design

I browsed some good articles about rules of web design for reference

(1) Rules of Thumb for Web Design

(2) 10 Web Design Rules That You Can Break
Although this article is trying to stimulate reader's thought, I would conservatively stick to these rules in my design:
  • Do not display the horizontal bar
  • Use a minimal number of font faces
  • Do not use too many colors
  • Make your site's goal obvious
  • Navigation should be easy to figure out
  • Use different colors for text and background
  • Don't put animation in the way of your content
  • Stick to web-safe fonts
  • Don't have a splash/landing page
  • Don't use tables

(3) 5 Basic Rules of web page design and layout
Your web site should be......
  • easy to read
  • easy to navigate
  • easy to find
  • web page layout and design be consistent through out the site
  • quick to download

Thursday, January 6, 2011

50 Fresh Porfolio Websites for Your Inspiration -- Smash magazine

Recently while I started preparing for my personal website and portfolio, I bumped into this:
50 Fresh Porfolio Websites for Your Inspiration -- Smash magazine

I just browsed the first few websites and was surprised by the visualization and interactive effects they made. My first observation was that, they used a lot of javascript. Yet a question comes to my mind: how do they manipulate those technologies and combine them with design so elegantly that doesn't look abrupt?


Among these fantastic pieces of work, here are some of them that most arouse my attention:
This is a portfolio site of a company based on UK. It sounds sarcastic and self-content that they put "We made our mN online home using blood, sweat and a thing called Flash" on their website. Their work is definitely stimulating and fun however just a little bit arbitrary that I couldn't get how to use it at first.

This one arouse my interests is because of its color scheme: besides simple and neat, a naughty cat icon make me feel irresistible to the design.