Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Tuesday 18 October 2011

Need Firefox/Safari fix: Text floats over image

Someone recently asked me about this technique and my first reaction was that it was probably a little too mundane to cover as a tutorial. But then I got to thinking that there is actually a few interesting things happening here and the style is trendy enough people might be interested.

The idea is just to overlay some text over an image, but as blocks that stick out from the left with an even amount of padding all the way around the variable-length text. Here is an example: Please Click here to go to the Example

Friday 14 October 2011

XNA Beginners Video Tutorial

CS & IT Symposium 2010: Computer Science, Game Development, and the XNA Game Studio Platform 

Computer Science Teachers Association
Computer Science & Information Technology Symposium 2010
July 13, 2010

Computer Science, Game Development and the XNA Game Studio Platform
Presented by Alfred Thompson & Steve Scanlan


This presentation talks about creating and implementing a high school game development curriculum using the (free) XNA Game Studio. We present the reasoning behind this type of course, show screenshots and a video introduction to student projects, as well as show examples of the sort of code students can create. We also talk about how freely available curriculum has been used and modified with real students. We present a collection of helpful resources including websites, tutorials and videos from Microsoft and independent web sites.

For more information, please see http://csta.acm.org/





XNA Beginners Video Tutorial1 Part1




XNA Beginners Video Tutorial2 Part1




XNA Beginners Video Tutorial2 Part2


Microsoft XNA Game Programming


Microsoft XNA is a set of tools with a managed runtime environment provided by Microsoft that facilitates video game development and management. XNA attempts to free game developers from writing "repetitive boilerplate code" and to bring different aspects of game production into a single system. The XNA toolset was announced March 24, 2004, at the Game Developers Conference in San Jose, California. A first Community Technology Preview of XNA Build was released on March 14, 2006. XNA Game Studio 2.0 was released in December 2007, followed by XNA Game Studio 3.0 on October 30, 2008. XNA Game Studio 4.0 was released on September 16, 2010 along with the Windows Phone 7 Development Tools.
XNA currently encompasses Microsoft's entire Game Development Sections, including the standard Xbox Development Kit and XNA Game Studio.

The name "XNA" originated out of the project's development name, Xbox New Architecture. Instead of being released under the Xbox name, the Xbox 360 was released (2005), and XNA came to stand for "XNA is Not an Acronym".

XNA Framework

The XNA Framework is based on the native implementation of .NET Compact Framework 2.0 for Xbox 360 development and .NET Framework 2.0 on Windows. It includes an extensive set of class libraries, specific to game development, to promote maximum code reuse across target platforms. The framework runs on a version of the Common Language Runtime that is optimized for gaming to provide a managed execution environment. The runtime is available for Windows XP, Windows Vista, Windows 7, Windows Phone 7 and Xbox 360. Since XNA games are written for the runtime, they can run on any platform that supports the XNA Framework with minimal or no modification. Games that run on the framework can technically be written in any .NET-compliant language, but only C# in XNA Game Studio Express IDE and all versions of Visual Studio 2008 and 2010 (as of XNA 4.0) are officially supported. Support for Visual Basic .NET was added in 2011.

The XNA Framework encapsulates low-level technological details involved in coding a game, making sure that the framework itself takes care of the difference between platforms when games are ported from one compatible platform to another, and thereby allowing game developers to focus more on the content and gaming experience. The XNA Framework integrates with a number of tools, such as the Cross-platform Audio Creation Tool (XACT), to aid in content creation. The XNA Framework provides support for both 2D and 3D game creation and allows use of the Xbox 360 controllers and vibrations. XNA framework games that target the Xbox platform can currently only be distributed by members of the Microsoft XNA Creator's Club which carries a $99/year subscription fee. Desktop applications can be distributed free of charge under Microsoft's current licensing.

XNA Build

XNA Build is a set of game asset pipeline management tools, which help by defining, maintaining, debugging, and optimizing the game asset pipeline of individual game development efforts. A game asset pipeline describes the process by which game content, such as textures and 3D models, are modified to a form suitable for use by the gaming engine. XNA Build helps identify the pipeline dependencies, and also provides API access to enable further processing of the dependency data. The dependency data can be analyzed to help reduce the size of a game by finding content that is not actually used. For example, XNA Build analysis revealed that 40% of the textures that shipped with MechCommander 2 were unused and could have been omitted.




XNA Game Studio

XNA Game Studio is an integrated development environment (IDE) for development of games. Five revisions have been released so far.

XNA Game Studio Express

XNA Game Studio Express, the first release of XNA Game Studio, was intended for students, hobbyist, and independent (and homebrew) game developers. It was available as a free download. Express provides basic "starter kits" for rapid development of specific genres of games, such as platform games, real-time strategy, and first-person shooters. Developers could create Windows games for free with the XNA Framework, but to run their games on the Xbox 360 they will have to pay an annual fee of US$99 (or a four-month fee of US$49) for admission to the Microsoft XNA Creator's Club. The initial release had no way of shipping precompiled binaries to other Xbox 360 players, but this was changed in "XNA Game Studio Express 1.0 Refresh" which made it possible to compile Xbox 360 binaries and share them with other Microsoft XNA Creator's Club members.

The first beta version of XNA Game Studio Express was released for download on August 30, 2006, followed by a second version on November 1, 2006. Microsoft released the final version on December 11, 2006.


On April 24, 2007, Microsoft released an update called XNA Game Studio Express 1.0 Refresh.

XNA Game Studio 2.0

XNA Game Studio 2.0 was released on December 13, 2007. XNA Game Studio 2.0 features the ability to be used with all versions of Visual Studio 2005 (including the free Visual C# 2005 Express Edition), a networking API using Xbox Live on both Windows and Xbox 360 and better device handling.

XNA Game Studio 3.0

XNA Game Studio 3.0 (for Visual Studio 2008 or the free Visual C# 2008 Express Edition) allows production of games targeting the Zune platform and adds Xbox Live community support. A beta of the toolset was released in September 2008. The final release was released on 30 October 2008. XNA Game Studio 3.0 now supports C# 3.0, LINQ and most versions of Visual Studio 2008. There are several more new features of XNA Game Studio 3.0 also, such as a trial Mode added to XNA Game Studio 3.0 that will enable creators to easily add the required trial feature to their games, Xbox LIVE multi-player features like in-game invites, create cross-platform games that work on Windows, Xbox 360 and Zune.

XNA Game Studio 3.1

XNA Game Studio 3.1 was released on June 11, 2009. The API includes support for video playback, a revised audio API, Xbox LIVE Party system and support for games to use the Xbox 360 Avatars.

XNA Game Studio 4

XNA Game Studio 4 was announced and initially released as a "Community Technical Preview" at Game Developers Conference (GDC) on March 9, 2010, and in its final form on September 16, 2010. It adds support for the Windows Phone 7 platform (including 3D hardware acceleration), framework hardware profiles, configurable effects, built-in state objects, graphics device scalars and orientation, cross-platform and multi-touch input, microphone input and buffered audio playback, and Visual Studio 2010 integration.

XNA Framework Content Pipeline

The XNA Framework Content Pipeline is a set of tools that allows Visual Studio and XNA Studio to act "as the key design point around organizing and consuming 3D content".

XDK Extensions

Formerly known as XNA Game Studio Professional, XDK Extensions is an add-on to XNA Game Studio and requires the Microsoft Xbox 360 Development Kit. Both are only available for licensed Xbox developers. The extensions include additional managed APIs for achievements, leaderboards, and other features reserved for licensed game titles. Titles developed using XDK Extensions include winners of Microsoft's Dream-Build-Play competition among others. The most heavily publicized of these was The Dishwasher: Dead Samurai.

License agreement

The Microsoft XNA Framework 2.0 EULA specifically prohibits the distribution of commercial networked games that connect to Xbox Live and/or Games for Windows Live in the absence of a specific agreement signed by both the developer and Microsoft. This means that XNA Game Studio can still be used to develop commercial games and other programs for the Windows platform, although Microsoft's networking support code for Xbox/Windows Live cannot be used. Self-developed network code can still be used inside the developer's XNA project.

Games created using XNA Game Studio may be distributed via Xbox Live Indie Games and Windows Phone 7 marketplace. The software may also be used to create commercial games which target Windows.

XNA Indie Games

Xbox 360 games written in XNA Game Studio can be submitted to the App Hub, for which premium membership is required, this costs US$99/year. All games submitted to the App Hub are subjected to peer review by other creators. If the game passes review then it is listed on Xbox Live Marketplace. Creators can set a price of 80, 240 or 400 points for their game. The creator is paid 70% of the total revenue from their game sales as a baseline. Microsoft originally planned to take an additional percentage of revenue if they provided additional marketing for a game, but this policy was rescinded in March 2009, leaving the flat rate intact regardless of promotion.




Microsoft also distributes a free year premium App Hub subscription for educational establishments through their DreamSpark program and MSDNAA. These accounts allow students to develop games for the Xbox 360, but developers still need a premium Xbox Live account to submit their game to the marketplace.

Alternative implementations

A project called Mono.XNA was formed to port XNA to the open source and cross-platform Mono framework.



From the codebase of Mono.XNA and SilverSprite a new project called MonoGame was formed to port XNA to several mobile devices. As of 2011, support is stable for iOS (using MonoTouch) and limited for Google Android and Mac App Store.

An open source project called Grommet contains a limited port for embedded devices using the .NET Micro Framework

Google Code Jam

Google Code Jam is an international programming competition hosted and administered by Google. The competition began in 2003 as a means to identify top engineering talent for potential employment at Google The competition consists of a set of algorithmic problems which must be solved in a fixed amount of time. Competitors may use any programming language and development environment to obtain their solutions.

In 2008, over 11,000 people from more than 128 countries competed for prize money totaling over $80,000, including a top prize of $10,000

In 2009, total 8605 people competed. The winner was Lou TianCheng from China followed by Qi ZiChao (China) and Iwata Yoichi (Japan).

In 2011, over 30,000 people competed. The winner was Makoto Soejima from Japan followed by Ivan Metelsky(Belarus) and Jakub Pachocki(Poland).

Tournament 1st place         2nd place                      3rd place
2011 Makoto Soejima         Ivan Metelsky                      Jakub Pachocki
2010 Egor Kulikov       Erik-Jan Krijgsman               Sergey Kopeliovich
2009 Tiancheng Lou           Zichao Qi                         Yoichi Iwata
2008 Tiancheng Lou         Zeyuan Zhu                         Bruce Merry
2006 Petr Mitrichev          Ying Wang               Andrey Stankevich
2005 Marek Cygan     Eric-Jan Krijgsman                       Petr Mitrichev
2004 Sergio Sancho         Po Ruh Loh                           Reid Barton
 

Wednesday 12 October 2011

Android’s HTTP Clients

Most network-connected Android apps will use HTTP to send and receive data. Android includes two HTTP clients: HttpURLConnection and Apache HTTP Client. Both support HTTPS, streaming uploads and downloads, configurable timeouts, IPv6 and connection pooling.

Apache HTTP Client

DefaultHttpClient and its sibling AndroidHttpClient are extensible HTTP clients suitable for web browsers. They have large and flexible APIs. Their implementation is stable and they have few bugs.
But the large size of this API makes it difficult for us to improve it without breaking compatibility. The Android team is not actively working on Apache HTTP Client.

HttpURLConnection

HttpURLConnection is a general-purpose, lightweight HTTP client suitable for most applications. This class has humble beginnings, but its focused API has made it easy for us to improve steadily.
Prior to Froyo, HttpURLConnection had some frustrating bugs. In particular, calling close() on a readable InputStream could poison the connection pool. Work around this by disabling connection pooling:
private void disableConnectionReuseIfNecessary() {
    // HTTP connection reuse which was buggy pre-froyo
    if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
        System.setProperty("http.keepAlive", "false");
    }
}
In Gingerbread, we added transparent response compression. HttpURLConnection will automatically add this header to outgoing requests, and handle the corresponding response:
Accept-Encoding: gzip
Take advantage of this by configuring your Web server to compress responses for clients that can support it. If response compression is problematic, the class documentation shows how to disable it.
Since HTTP’s Content-Length header returns the compressed size, it is an error to use getContentLength() to size buffers for the uncompressed data. Instead, read bytes from the response until InputStream.read() returns -1.
We also made several improvements to HTTPS in Gingerbread. HttpsURLConnection attempts to connect with Server Name Indication (SNI) which allows multiple HTTPS hosts to share an IP address. It also enables compression and session tickets. Should the connection fail, it is automatically retried without these features. This makes HttpsURLConnection efficient when connecting to up-to-date servers, without breaking compatibility with older ones.
In Ice Cream Sandwich, we are adding a response cache. With the cache installed, HTTP requests will be satisfied in one of three ways:
  • Fully cached responses are served directly from local storage. Because no network connection needs to be made such responses are available immediately.
  • Conditionally cached responses must have their freshness validated by the webserver. The client sends a request like “Give me /foo.png if it changed since yesterday” and the server replies with either the updated content or a 304 Not Modified status. If the content is unchanged it will not be downloaded!
  • Uncached responses are served from the web. These responses will get stored in the response cache for later.
Use reflection to enable HTTP response caching on devices that support it. This sample code will turn on the response cache on Ice Cream Sandwich without affecting earlier releases:
private void enableHttpResponseCache() {
    try {
        long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
        File httpCacheDir = new File(getCacheDir(), "http");
        Class.forName("android.net.http.HttpResponseCache")
            .getMethod("install", File.class, long.class)
            .invoke(null, httpCacheDir, httpCacheSize);
    } catch (Exception httpResponseCacheNotAvailable) {
    }
}
You should also configure your Web server to set cache headers on its HTTP responses.

Which client is best?

Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best choice for these releases.
For Gingerbread and better, HttpURLConnection is the best choice. Its simple API and small size makes it great fit for Android. Transparent compression and response caching reduce network use, improve speed and save battery. New applications should use HttpURLConnection; it is where we will be spending our energy going forward.

Topic taken from http://android-developers.blogspot.com/?hl=en

Monday 3 October 2011

Introduction to TCP client server in C#

 

Introduction

This is a simple implementation of a TCP client server relationship.

To use

Compile the server and client programs separately. Before compiling change the IP address in both programs to match that of your machine (NOTE : to get your IP address run 'ipconfig' from the command prompt in Windows NT/2000 m/c's)
When the server program is run, it will indicate at which IP it is running and the port it is listening to. Now run the client program is run , so as to establish a connection with the server.
When a connection is established the server will display the IP address and Port from where it has accepted the connection and client will ask for the string which is to be transmitted to the server.
The server on reciept of the string will display it, send an acknowledgement which will be recieved by the client.
The client can be either run from the same machine as the server or from a different machine. If run from a different machine then a network connection should exist between the machines running the server and client programs
//

/*   Server Program    */
                 
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

public class serv {
    public static void Main() {
    try {
        IPAddress ipAd = IPAddress.Parse("172.21.5.99");
         // use local m/c IP address, and 

         // use the same in the client


/* Initializes the Listener */
        TcpListener myList=new TcpListener(ipAd,8001);

/* Start Listeneting at the specified port */        
        myList.Start();
        
        Console.WriteLine("The server is running at port 8001...");    
        Console.WriteLine("The local End point is  :" + 
                          myList.LocalEndpoint );
        Console.WriteLine("Waiting for a connection.....");
        
        Socket s=myList.AcceptSocket();
        Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
        
        byte[] b=new byte[100];
        int k=s.Receive(b);
        Console.WriteLine("Recieved...");
        for (int i=0;i<k;i++)
            Console.Write(Convert.ToChar(b[i]));

        ASCIIEncoding asen=new ASCIIEncoding();
        s.Send(asen.GetBytes("The string was recieved by the server."));
        Console.WriteLine("\nSent Acknowledgement");
/* clean up */            
        s.Close();
        myList.Stop();
            
    }
    catch (Exception e) {
        Console.WriteLine("Error..... " + e.StackTrace);
    }    
    }
    
}

--------------------------------------------------------------------

/*       Client Program      */

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;


public class clnt {

    public static void Main() {
        
        try {
            TcpClient tcpclnt = new TcpClient();
            Console.WriteLine("Connecting.....");
            
            tcpclnt.Connect("172.21.5.99",8001);
            // use the ipaddress as in the server program

            
            Console.WriteLine("Connected");
            Console.Write("Enter the string to be transmitted : ");
            
            String str=Console.ReadLine();
            Stream stm = tcpclnt.GetStream();
                        
            ASCIIEncoding asen= new ASCIIEncoding();
            byte[] ba=asen.GetBytes(str);
            Console.WriteLine("Transmitting.....");
            
            stm.Write(ba,0,ba.Length);
            
            byte[] bb=new byte[100];
            int k=stm.Read(bb,0,100);
            
            for (int i=0;i<k;i++)
                Console.Write(Convert.ToChar(bb[i]));
            
            tcpclnt.Close();
        }
        
        catch (Exception e) {
            Console.WriteLine("Error..... " + e.StackTrace);
        }
    }

}

Network Programming in C#


The .NET framework provides two namespaces, System.Net and System.Net.Sockets for network programming. The classes and methods of these namespaces help us to write programs, which can communicate across the network. The communication can be either connection oriented or connectionless. They can also be either stream oriented or data-gram based. The most widely used protocol TCP is used for stream-based communication and UDP is used for data-grams based applications.
The System.Net.Sockets.Socket is an important class from the System.Net.Sockets namespace. A Socket instance has a local and a remote end-point associated with it. The local end-point contains the connection information for the current socket instance.
There are some other helper classes like IPEndPoint, IPADdress, SocketException etc, which we can use for Network programming. The .NET framework supports both synchronous and asynchronous communication between the client and server. There are different methods supporting for these two types of communication.

A synchronous method is operating in blocking mode, in which the method waits until the operation is complete before it returns. But an asynchronous method is operating in non-blocking mode, where it returns immediately, possibly before the operation has completed.


Dns Class
The System.net namespace provides this class, which can be used to creates and send queries to obtain information about the host server from the Internet Domain Name Service (DNS). Remember that in order to access DNS, the machine executing the query must be connected to a network. If the query is executed on a machine, that does not have access to a domain name server, a System.Net.SocketException is thrown. All the members of this class are static in nature. The important methods of this class are given below.
public static IPHostEntry GetHostByAddress(string address)
Where address should be in a dotted-quad format like "202.87.40.193". This method returns an IPHostEntry instance containing the host information. If DNS server is not available, the method returns a SocketException.
public static string GetHostName()
This method returns the DNS host name of the local machine.
In my machine Dns.GetHostName() returns vrajesh which is the DNS name of my machine.
public static IPHostEntry Resolve(string hostname)
This method resolves a DNS host name or IP address to a IPHostEntry instance. The host name should be in a dotted-quad format like 127.0.01 or www.microsoft.com.
IPHostEntry Class
This is a container class for Internet host address information. This class makes no thread safety guarantees. The following are the important members of this class.
AddressList Property
Gives an IPAddress array containing IP addresses that resolve to the host name.
Aliases Property
Gives a string array containing DNS name that resolves to the IP addresses in AddressList property.
The following program shows the application of the above two classes.
using System;
using System.Net;
using System.Net.Sockets;
class MyClient
{
public static void Main()
{
IPHostEntry IPHost = Dns.Resolve("www.hotmail.com");
Console.WriteLine(IPHost.HostName);
string []aliases = IPHost.Aliases;
Console.WriteLine(aliases.Length);
IPAddress[] addr = IPHost.AddressList;
Console.WriteLine(addr.Length);
for(int i= 0; i < addr.Length ; i++)
{
Console.WriteLine(addr[i]);
}
}
}

IPEndPoint Class
This class is a concrete derived class of the abstract class EndPoint. The IPEndPoint class represents a network end point as an IP address and a port number. There is couple of useful constructors in this class:
IPEndPoint(long addresses, int port)
IPEndPoint (IPAddress addr, int port)
IPHostEntry IPHost = Dns.Resolve("www.c-sharpcorner.com");
Console.WriteLine(IPHost.HostName);
string []aliases = IPHost.Aliases;
IPAddress[] addr = IPHost.AddressList;
Console.WriteLine(addr[0]);
EndPoint ep = new IPEndPoint(addr[0],80);


Socket Programming: Synchronous Clients
The steps for creating a simple synchronous client are as follows.
  1. Create a Socket instance.
  2. Connect the above socket instance to an end-point.
  3. Send or Receive information.
  4. Shutdown the socket
  5. Close the socket
The Socket class provides a constructor for creating a Socket instance.
public Socket (AddressFamily af, ProtocolType pt, SocketType st)
Where AddressFamily, ProtocolType and SocketTYpe are the enumeration types declared inside the Socket class.
The AddressFamily member specifies the addressing scheme that a socket instance must use to resolve an address. For example AddressFamily.InterNetwork indicates that an IP version 4 addresses is expected when a socket connects to an end point.
The SocketType parameter specifies the socket type of the current instance. For example SocketType.Stream indicates a connection-oriented stream and SocketType.Dgram indicates a connectionless stream.
The ProtocolType parameter specifies the ptotocol to be used for the communication. For example ProtocolType.Tcp indicates that the protocol used is TCP and ProtocolType.Udp indicates that the protocol using is UDP.
public Connect (EndPoint ep)
The Connect() method is used by the local end-point to connect to the remote end-point. This method is used only in the client side. Once the connection has been established the Send() and Receive() methods can be used for sending and receiving the data across the network.
The Connected property defined inside the class Socket can be used for checking the connection. We can use the Connected property of the Socket class to know whether the current Socket instance is connected or not. A property value of true indicates that the current Socket instance is connected.
IPHostEntry IPHost = Dns.Resolve("www.c-sharpcorner.com");
Console.WriteLine(IPHost.HostName);
string []aliases = IPHost.Aliases;
IPAddress[] addr = IPHost.AddressList;
Console.WriteLine(addr[0]);
EndPoint ep = new IPEndPoint(addr[0],80);
Socket sock = new
Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
sock.Connect(ep);
if(sock.Connected)
Console.WriteLine("OK");

The Send() method of the socket class can be used to send data to a connected remote socket.
public int Send (byte[] buffer, int size, SocketFlags flags)
Where byte[] parameter storing the data to send to the socket, size parameter containing the number of bytes to send across the network. The SocketFlags parameter can be a bitwise combination of any one of the following values defined in the System.Net.Sockets.SocketFlags enumerator.

SocketFlags.None
SocketFlags.DontRoute
SocketFlags.OutOfBnd

The method Send() returns a System.Int32 containing the number of bytes send.Remember that there are other overloaded versions of Send() method as follows.
public int Send (byte[] buffer, SocketFlags flags)
public int Send (byte[] buffer)
public int Send (byte[] buffer,int offset, int size, SocketFlags flags)

The Receive() method can be used to receive data from a socket.
public int Receive(byte[] buffer, int size, SocketFlags flags)
Where byte[] parameter storing the data to send to the socket, size parameter containing the number of bytes to send across the network. The SocketFlags parameter can be a bitwise combination of any one of the following values defined in the System.Net.Sockets.SocketFlags enumerator explained above.
The overloaded versions of Receive() methods are shown below.
public int Receive (byte[] buffer, SocketFlags flags)
public int Receive (byte[] buffer)
public int Receive (byte[] buffer,int offset, int size, SocketFlags flags)

When the communication across the sockets is over, the connection between the sockets can be terminated by invoking the method ShutDown()
public void ShutDown(SocketShutdown how)
Where ‘how’ is one of the values defined in the SocketSHutdown enumeration. The value SoketShutdown.Send means that the socket on the other end of the connection is notified that the current instance would not send any more data.
The value SoketShutdown.Receive means that the socket on the other end of the connection is notified that the current instance will not receive any more data and the value SoketShutdown.Both means that both the action are not possible.
Remember that the ShutDown() method must be called before the Close(0 method to ensure that all pending data is sent or received.
A socket can be closed by invoking the method Close().
public void Close()
This method closes the current instance and releases all managed and un-managed resources allocated by the current instance. This method internally calls the Dispose() method with an argument of ‘true’ value, which frees both managed and un-managed resources used by the current instance.
protected virtual void Dispose(bool)
The above method closes the current instance and releases the un-managed resources allocated by the current instance and exceptionally release the managed resources also. An argument value of ‘true’ releases both managed and un-managed resources and a value of ‘false’ releases only un-managed resources.
The source code for a simple synchronous client by using the sockets is show below. The following program can send an HTTP request to a web server and can read the response from the web server.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MyClient
{
public static void Main()
{
IPHostEntry IPHost = Dns.Resolve("
www.google.com
");
Console.WriteLine(IPHost.HostName);
string []aliases = IPHost.Aliases;
IPAddress[] addr = IPHost.AddressList;
Console.WriteLine(addr[0]);
EndPoint ep = new IPEndPoint(addr[0],80);
Socket sock = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
sock.Connect(ep);
if(sock.Connected)
Console.WriteLine("OK");
Encoding ASCII = Encoding.ASCII;
string Get = "GET / HTTP/1.1\r\nHost: " + "www. google.com" +
"\r\nConnection: Close\r\n\r\n";
Byte[] ByteGet = ASCII.GetBytes(Get);
Byte[] RecvBytes = new Byte[256];
sock.Send(ByteGet, ByteGet.Length, 0);
Int32 bytes = sock.Receive(RecvBytes, RecvBytes.Length, 0);
Console.WriteLine(bytes);
String strRetPage = null;
strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
while (bytes > 0)
{
bytes = sock.Receive(RecvBytes, RecvBytes.Length, 0);
strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
Console.WriteLine(strRetPage );
}
sock.ShutDown(SocketShutdown.Both);
sock.Close();
}
}

A Chat Client/Server Program for C#

Here's some code for a chat server, and an accompanying client program.
The client:

using System.IO;
using System.Net;
using System;
using System.Threading;
using N = System.Net;
using System.Collections;
using System.Windows.Forms;
using System.ComponentModel;
using System.Runtime.InteropServices;

class TalkUser {

static Form talk;
static N.Sockets.TcpClient TC;

[DllImport("kernel32.dll")]
private static extern void ExitProcess(int a);

public static void Main() {
talk = new Form();
talk.Text = "TalkUser - The OFFICIAL TalkServ Client";
talk.Closing += new CancelEventHandler(talk_Closing);
talk.Controls.Add(new TextBox());
talk.Controls[0].Dock = DockStyle.Fill;
talk.Controls.Add(new TextBox());
talk.Controls[1].Dock = DockStyle.Bottom;
((TextBox)talk.Controls[0]).Multiline = true;
((TextBox)talk.Controls[1]).Multiline = true;
talk.WindowState = FormWindowState.Maximized;
talk.Show();
((TextBox)talk.Controls[1]).KeyUp += new KeyEventHandler(key_up);
TC = new N.Sockets.TcpClient();
TC.Connect("IP OF A SERVER HERE",4296);
Thread t = new Thread(new ThreadStart(run));
t.Start();
while(true) {
Application.DoEvents();
}
}

private static void talk_Closing(object s, CancelEventArgs e) {
e.Cancel = false;
Application.Exit();
ExitProcess(0);
}

private static void key_up(object s,KeyEventArgs e) {
TextBox TB = (TextBox)s;
if(TB.Lines.Length>1) {
StreamWriter SW = new StreamWriter(TC.GetStream());
SW.WriteLine(TB.Text);
SW.Flush();
TB.Text = "";
TB.Lines = null;
}
}

private static void run() {
StreamReader SR = new StreamReader(TC.GetStream());
while(true) {
Application.DoEvents();
TextBox TB = (TextBox)talk.Controls[0];
TB.AppendText(SR.ReadLine()+"\r\n");
TB.SelectionStart = TB.Text.Length;
}
}
}
And the server:
using System.IO;
using System.Net;
using System;
using System.Threading;
using N = System.Net;
using System.Collections;

class TalkServ {

System.Net.Sockets.TcpListener server;
public static Hashtable handles;
public static Hashtable handleByConnect;

public static void Main() {
TalkServ TS = new TalkServ();
}

public TalkServ() {
handles = new Hashtable(100);
handleByConnect = new Hashtable(100);
server = new System.Net.Sockets.TcpListener(4296);
while(true) {
server.Start();
if(server.Pending()) {
N.Sockets.TcpClient connection = server.AcceptTcpClient();
Console.WriteLine("Connection made");
BackForth BF = new BackForth(connection);
}
}
}

public static void SendToAll(string name,string msg) {
StreamWriter SW;
ArrayList ToRemove = new ArrayList(0);
N.Sockets.TcpClient[] tc = new N.Sockets.TcpClient[TalkServ.handles.Count];
TalkServ.handles.Values.CopyTo(tc,0);
for(int i=0;i<tc.Length;i++) {
try {
if(msg.Trim()==""||tc[i]==null)
continue;
SW = new StreamWriter(tc[i].GetStream());
SW.WriteLine(name + ": " + msg);
SW.Flush();
SW = null;
} catch(Exception e44) { e44 = e44;
string g = (string) TalkServ.handleByConnect[tc[i]];
TalkServ.SendSysMsg("** " + g + " ** HAS LEFT US.");
TalkServ.handles.Remove(g);
TalkServ.handleByConnect.Remove(tc[i]);
}
}
}

public static void SendSysMsg(string msg) {
StreamWriter SW;
ArrayList ToRemove = new ArrayList(0);
N.Sockets.TcpClient[] tc = new N.Sockets.TcpClient[TalkServ.handles.Count];
TalkServ.handles.Values.CopyTo(tc,0);
for(int i=0;i<tc.Length;i++) {
try {
if(msg.Trim()==""||tc[i]==null)
continue;
SW = new StreamWriter(tc[i].GetStream());
SW.WriteLine(msg);
SW.Flush();
SW = null;
} catch(Exception e44) { e44 = e44;
TalkServ.handles.Remove(TalkServ.handleByConnect[tc[i]]);
TalkServ.handleByConnect.Remove(tc[i]);
}
}
}
}//end of class TalkServ

class BackForth {
N.Sockets.TcpClient client;
System.IO.StreamReader SR;
System.IO.StreamWriter SW;
string handle;

public BackForth(System.Net.Sockets.TcpClient c) {
client = c;
Thread t = new Thread(new ThreadStart(init));
t.Start();
}

private string GetHandle() {
SW.WriteLine("What is your handle? ");
SW.Flush();
return SR.ReadLine();
}

private void run() {
try {
string l = "";
while(true) {
l = SR.ReadLine();
TalkServ.SendToAll(handle,l);
}
} catch(Exception e44) { Console.WriteLine(e44); }
}

private void init() {
SR = new System.IO.StreamReader(client.GetStream());
SW = new System.IO.StreamWriter(client.GetStream());
SW.WriteLine("WELCOME TO TalkServ! Be Nice!");
//SW.WriteLine("What is your handle? ");
//SW.Flush();
handle = GetHandle();
while(TalkServ.handles.Contains(handle)) {
SW.WriteLine("ERR - Handle already exists!");
handle = GetHandle();
}
TalkServ.handles.Add(handle,client);
TalkServ.handleByConnect.Add(client,handle);
TalkServ.SendSysMsg("** " + handle + " ** HAS JOINED US.");
SW.WriteLine("Now Talking.....\r\n-------------------------------");
SW.Flush();
Thread t = new Thread(new ThreadStart(run));
t.Start();
}
}

Java Native Access (JNA)

What is JNA?

JNA provides Java programs easy access to native shared libraries (DLLs on Windows) without writing anything but Java code—no JNI or native code is required. This functionality is comparable to Windows' Platform/Invoke and Python's ctypes. Access is dynamic at runtime without code generation.
JNA allows you to call directly into native functions using natural Java method invocation. The Java call looks just like it does in native code. Most calls require no special handling or configuration; no boilerplate or generated code is required.
The JNA library uses a small native library stub to dynamically invoke native code. The developer uses a Java interface to describe functions and structures in the target native library. This makes it quite easy to take advantage of native platform features without incurring the high overhead of configuring and building JNI code for multiple platforms.
While some attention is paid to performance, correctness and ease of use take priority.
JNA includes a platform library with many native functions already mapped as well as a set of utility interfaces that simplify native access.

Features

  • Automatic mapping from Java to native functions, with simple mappings for all primitive data types
  • Runs on most platforms which support Java
  • Automatic conversion between C and Java strings, with customizable encoding/decoding
  • Structure and Union arguments/return values, by reference and by value
  • Function Pointers, (callbacks from native code to Java) as arguments and/or members of a struct
  • Auto-generated Java proxies for native function pointers
  • By-reference (pointer-to-type) arguments
  • Java array and NIO Buffer arguments (primitive types and pointers) as pointer-to-buffer
  • Nested structures and arrays
  • Wide (wchar_t-based) strings
  • Native long support (32- or 64-bit as appropriate)
  • Demo applications
  • Supported on 1.4 or later JVMs (earlier VMs may work with stubbed NIO support)
  • Customizable marshalling/unmarshalling (argument and return value conversions)
  • Customizable mapping from Java method to native function name, and customizable invocation to simulate C preprocessor function macros
  • Support for automatic Windows ASCII/UNICODE function mappings
  • Varargs support
  • Type-safety for native pointers
  • VM crash protection (optional)
  • Optimized direct mapping for high-performance applications. 

How To Get Started Using JNA

Java Native Access (JNA) has a single component, jna.jar; the supporting native library (jnidispatch) is included in the jar file. JNA is capable of extracting and loading the native library on its own, so you don't need additional configuration. JNA falls back to extraction if the native library is not already installed on the local system somewhere accessible to System.loadLibrary (see information on library loading). The native library is also available in platform-specific jar files for use with Java Web Start.
  1. Download jna.jar from the download page.
  2. Compile and run this short example, which maps the printf function from the standard C library and calls it. Be sure to include jna.jar in the classpath:
    
    package com.sun.jna.examples;
    
    import com.sun.jna.Library;
    import com.sun.jna.Native;
    import com.sun.jna.Platform;
    
    /** Simple example of JNA interface mapping and usage. */
    public class HelloWorld {
    
        // This is the standard, stable way of mapping, which supports extensive
        // customization and mapping of Java to native types.
        public interface CLibrary extends Library {
            CLibrary INSTANCE = (CLibrary)
                Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"),
                                   CLibrary.class);
        
            void printf(String format, Object... args);
        }
    
        public static void main(String[] args) {
            CLibrary.INSTANCE.printf("Hello, World\n");
            for (int i=0;i < args.length;i++) {
                CLibrary.INSTANCE.printf("Argument %d: %s\n", i, args[i]);
            }
        }
    }
    
  3. Identify a native target library that you want to use. This can be any shared library with exported functions. Many examples of mappings for common system libraries may be found in the platform package.
  4. Make your target library available to your Java program. There are two ways to do this:
    • The preferred method is to set the jna.library.path system property to the path to your target library. This property is similar to java.library.path but only applies to libraries loaded by JNA.
    • Change the appropriate library access environment variable before launching the VM. This is PATH on Windows, LD_LIBRARY_PATH on Linux, and DYLD_LIBRARY_PATH on OSX.
  5. Declare a Java interface to hold the native library methods by extending the Library interface. Following is an example of mapping for the Windows kernel32 library.
    
    package com.sun.jna.examples.win32;
    
    import com.sun.jna.*;
    
    // kernel32.dll uses the __stdcall calling convention (check the function
    // declaration for "WINAPI" or "PASCAL"), so extend StdCallLibrary
    // Most C libraries will just extend com.sun.jna.Library,
    public interface Kernel32 extends StdCallLibrary { 
        // Method declarations, constant and structure definitions go here
    }
  6. Within this interface, define an instance of the native library using the Native.loadLibrary(Class) method, providing the native library interface you defined in step (5).
    
        Kernel32 INSTANCE = (Kernel32)
            Native.loadLibrary("kernel32", Kernel32.class);
        // Optional: wraps every call to the native library in a
        // synchronized block, limiting native calls to one at a time
        Kernel32 SYNC_INSTANCE = (Kernel32)
            Native.synchronizedLibrary(INSTANCE);
    

    The INSTANCE variable is for convenient reuse of a single instance of the library. Alternatively, you can load the library into a local variable so that it will be available for garbage collection when it goes out of scope. A Map of options may be provided as the third argument to loadLibrary to customize the library behavior; some of these options are explained in more detail below. The SYNC_INSTANCE is also optional; use it if you need to ensure that your native library has only one call to it at a time.
  7. Declare methods that mirror the functions in the target library by defining Java methods with the same name and argument types as the native function (refer to the basic mappings below or the detailed table of type mappings). You may also need to declare native structures to pass to your native functions. To do this, create a class within the interface definition that extends Structure and add public fields (which may include arrays or nested structures).
    
    public static class SYSTEMTIME extends Structure {
        public short wYear;
        public short wMonth;
        public short wDayOfWeek;
        public short wDay;
        public short wHour;
        public short wMinute;
        public short wSecond;
        public short wMilliseconds;
    }
    
    void GetSystemTime(SYSTEMTIME result);
        
  8. You can now invoke methods on the library instance just like any other Java class. For a more extensive example, see the WindowUtils and ShapedWindowDemo classes.
    
    Kernel32 lib = Kernel32.INSTANCE;
    SYSTEMTIME time = new SYSTEMTIME();
    lib.GetSystemTime(time);
    System.out.println("Today's integer value is " + time.wDay);
    
  9. Alternatively, you may declare a class to hold your native methods, declare any number of methods with the "native" qualifier, and invoke Native.register(String) in the class static initializer with your library's name. See JNA direct mapping for an example.
If the C header files for your library are available, you can auto-generate a library mapping by using Olivier Chafik's excellent JNAerator utility. This is especially useful if your library uses long or complicated structures where translating by hand can be error-prone. See the JavaDoc overview for more detailed information about JNA usage.

Default Type Mappings

Java primitive types (and their object equivalents) map directly to the native C type of the same size.
Native Type Size Java Type Common Windows Types
char 8-bit integer byte BYTE, TCHAR
short 16-bit integer short WORD
wchar_t 16/32-bit character char TCHAR
int 32-bit integer int DWORD
int boolean value boolean BOOL
long 32/64-bit integer NativeLong LONG
long long 64-bit integer long __int64
float 32-bit FP float
double 64-bit FP double
char* C string String LPTCSTR
void* pointer Pointer LPVOID, HANDLE, LPXXX
Unsigned types use the same mappings as signed types. C enums are usually interchangeable with "int". A more comprehensive list of mappings may be found here

Using Pointers and Arrays

Primitive array arguments (including structs) are represented by their corresponding Java types. For example:

// Original C declarations
void fill_buffer(int *buf, int len);
void fill_buffer(int buf[], int len); // same thing with array syntax

// Equivalent JNA mapping
void fill_buffer(int[] buf, int len);
NOTE: if the parameter is to be used by the native function outside the scope of the function call, you must use Memory or an NIO Buffer. The memory provided by a Java primitive array will only be valid for use by the native code for the duration of the function call.
Arrays of C strings (the char* argv[] to the C main, for example), may be represented by String[] in Java code. JNA will pass an equivalent array with a NULL final element.

Using Structures/Unions

When a function requires a pointer to a struct, a Java Structure should be used. If the struct is passed or returned by value, you need only make minor modifications to the parameter or return type class declaration. Typically you define a public static class derived from Structure within your library interface definition. This allows the structure to share any options (like custom type mapping) defined for the library interface.
If a function requires an array of struct (allocated contiguously in memory), a Java Structure[] may be used. When passing in an array of Structure, it is not necessary to initialize the array elements (the function call will allocate, zero memory, and assign the elements for you). If you do need to initialize the array, you should use the Structure.toArray method to obtain an array of Structure elements contiguous in memory, which you can then initialize as needed.
Unions are generally interchangeable with Structures, but require that you indicate which union field is active with the setType method before it can be properly passed to a function call.

Using By-reference Arguments

When a function accepts a pointer-to-type argument you can use one of the ByReference types to capture the returned value, or subclass your own. For example:

// Original C declaration
void allocate_buffer(char **bufp, int* lenp);

// Equivalent JNA mapping
void allocate_buffer(PointerByReference bufp, IntByReference lenp);

// Usage
PointerByReference pref = new PointerByReference();
IntByReference iref = new IntByReference();
lib.allocate_buffer(pref, iref);
Pointer p = pref.getValue();
byte[] buffer = p.getByteArray(0, iref.getValue());
    
Alternatively, you could use a Java array with a single element of the desired type, but the ByReference convention better conveys the intent of the code. The Pointer class provides a number of accessor methods in addition to getByteArray() which effectively function as a typecast onto the memory.
Type-safe pointers may be declared by deriving from the PointerType class.

Customized Mapping from Java to Native (Types and Function Names)

The TypeMapper class and related interfaces provide for converting any Java type used as an argument, return value, or structure member to be converted to or from a native type. The example w32 API interfaces use a type mapper to convert Java boolean into the w32 BOOL type. A TypeMapper instance is passed as the value for the TYPE_MAPPER key in the options map passed to Native.loadLibrary. Alternatively, user-defined types may implement the NativeMapped interface, which determines conversion to and from native types on a class-by-class basis.
You may also customize the mapping of Java method names to the corresponding native function name. The StdCallFunctionMapper is one implementation which automatically generates stdcall-decorated function names from a Java interface method signature. The mapper should be passed as the value for the OPTION_FUNCTION_MAPPER key in the options map passed to the Native.loadLibrary call.
Refer to this table in the overview for a complete list of built-in type mappings.

Callbacks/Closures (Function Pointers)

Callback declarations consist of a simple interface that extends the Callback interface and implements a callback method (or defines a single method of arbitrary name). Callbacks are implemented by wrapping a Java object method in a little bit of C glue code. The simplest usage resembles using anonymous inner classes to register event listeners. Following is an example of callback usage:

// Original C declarations
typedef void (*sig_t)(int);
sig_t signal(sig_t);

// Equivalent JNA mappings
public interface CLibrary extends Library {
    int SIGUSR1 = 30;
    interface sig_t extends Callback {
        void invoke(int signal);        
    }
    sig_t signal(int sig, sig_t fn);
    int raise(int sig);
}
...
CLibrary lib = (CLibrary)Native.loadLibrary("c", CLibrary.class);
// WARNING: you must keep a reference to the callback object
// until you deregister the callback; if the callback object
// is garbage-collected, the native callback invocation will
// probably crash.
CLibrary.sig_t fn = new CLibrary.sig_t() {
    public void invoke(int sig) {
        System.out.println("signal " + sig + " was raised");
    }
};
CLibrary.sig_t old_handler = lib.signal(CLibrary.SIGUSR1, fn);
lib.raise(CLibrary.SIGUSR1);
...
Here is a more involved example, using the w32 APIs to enumerate all native windows:

// Original C declarations
typedef int (__stdcall *WNDENUMPROC)(void*,void*);
int __stdcall EnumWindows(WNDENUMPROC,void*);

// Equivalent JNA mappings
public interface User32 extends StdCallLibrary {
    interface WNDENUMPROC extends StdCallCallback {
        /** Return whether to continue enumeration. */
        boolean callback(Pointer hWnd, Pointer arg);
    }
    boolean EnumWindows(WNDENUMPROC lpEnumFunc, Pointer arg);
}
...
User32 user32 = User32.INSTANCE;

user32.EnumWindows(new WNDENUMPROC() {
    int count;
    public boolean callback(Pointer hWnd, Pointer userData) {
        System.out.println("Found window " + hWnd + ", total " + ++count);
        return true;
    }
}, null);
If your callback needs to live beyond the method invocation where it is used, make sure you keep a reference to it or the native code will call back to an empty stub after the callback object is garbage collected. Proxy wrappers are automatically generated for function pointers found within structs initialized by native code. This facilitates calling those functions from Java.

Invocation from Dynamically-Typed Languages

Languages such as Jython or JRuby may find it more convenient to access the NativeLibrary and Function classes directly rather than establishing a dedicated interface. Here's a brief example of using JNA from JRuby:

require 'java'

module Libc
  @@lib = com.sun.jna.NativeLibrary.getInstance("c")
  @@ptr_funcs = [ 'fopen', 'malloc', 'calloc' ]
  def self.method_missing(meth, *args)
    if @@ptr_funcs.include?(meth.to_s)
      @@lib.getFunction(meth.to_s).invokePointer(args.to_java)
    else
      @@lib.getFunction(meth.to_s).invokeInt(args.to_java)
    end
  end
  O_RDONLY = 0
  O_WRONLY = 1
  O_RDWR = 2
end

Libc.puts("puts from libc")
Libc.printf("Hello %s, from printf\n", "World")

file = Libc.open("/dev/stdout", 1, Libc::O_WRONLY)
n = Libc.write(file, "Test\n", 5)
puts "Wrote #{n} bytes via Libc"

path = "/dev/stdout"
fp = Libc.fopen(path, "w+")
Libc.fprintf(fp, "fprintf to %s via stdio\n", path)
Libc.fflush(fp)
Libc.fclose(fp)

Platform Library

JNA includes platform.jar that has cross-platform mappings and mappings for a number of commonly used platform functions, including a large number of Win32 mappings as well as a set of utility classes that simplify native access. The code is tested and the utility interfaces ensure that native memory management is taken care of correctly.
Before you map your own functions, check the platform package documentation for an already mapped one.
Platform-specific structures are mapped by header. For example, ShlObj.h structures can be found in com.sun.jna.platform.win32.ShlObj. Platform functions are mapped by library. For example, Advapi32.dll functions can be found in com.sun.jna.platform.win32.Advapi32. Simplified interfaces (wrappers) for Advapi32.dll functions can be found in com.sun.jna.platform.win32.Advapi32Util.
Cross-platform functions and structures are implemented in com.sun.jna.platform. These currently include the following.
  • FileMonitor: a cross-platform file system watcher
  • FileUtils: a cross-platform set of file-related functions, such as move to the recycle bin
  • KeyboardUtils: a cross-platform set of keyboard functions, such as finding out whether a key is pressed
  • WindowUtils: a cross-platform set of window functions, providing non-rectangular shaped and transparent windows

C# code for opening and closing CD,DVD ROM

using System;
using System.IO;
using System.Runtime.InteropServices;

class Test
{
    const int OPEN_EXISTING = 3;
    const uint GENERIC_READ = 0x80000000;
    const uint GENERIC_WRITE = 0x40000000;
    const uint IOCTL_STORAGE_EJECT_MEDIA = 2967560;

    [DllImport("kernel32")]
    private static extern IntPtr CreateFile
        (string filename, uint desiredAccess,
         uint shareMode, IntPtr securityAttributes,
         int creationDisposition, int flagsAndAttributes,
         IntPtr templateFile);

    [DllImport("kernel32")]
    private static extern int DeviceIoControl
        (IntPtr deviceHandle, uint ioControlCode,
         IntPtr inBuffer, int inBufferSize,
         IntPtr outBuffer, int outBufferSize,
         ref int bytesReturned, IntPtr overlapped);

    [DllImport("kernel32")]
    private static extern int CloseHandle(IntPtr handle);

    static void EjectMedia(char driveLetter)
    {
        string path = "\\\\.\\" + driveLetter + ":";
        IntPtr handle = CreateFile(path, GENERIC_READ | GENERIC_WRITE, 0,
                                   IntPtr.Zero, OPEN_EXISTING, 0,
                                   IntPtr.Zero);
        if ((long)handle == -1)
        {
            throw new IOException("Unable to open drive " + driveLetter);
        }
        int dummy = 0;
        DeviceIoControl(handle, IOCTL_STORAGE_EJECT_MEDIA, IntPtr.Zero, 0,
                        IntPtr.Zero, 0, ref dummy, IntPtr.Zero);
        CloseHandle(handle);
    }

    static void Main()
    {
        EjectMedia('g');
    }
}

Friday 30 September 2011

28 HTML5 Features, Tips, and Techniques you Must Know

1. New Doctype

Still using that pesky, impossible-to-memorize XHTML doctype?
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
  2.     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
If so, why? Switch to the new HTML5 doctype. You’ll live longer — as Douglas Quaid might say.
  1. <!DOCTYPE html>  
In fact, did you know that it truthfully isn’t even really necessary for HTML5? However, it’s used for current, and older browsers that require a specified doctype. Browsers that do not understand this doctype will simply render the contained markup in standards mode. So, without worry, feel free to throw caution to the wind, and embrace the new HTML5 doctype.

2. The Figure Element

Consider the following mark-up for an image:
  1. <img src="path/to/image" alt="About image" />  
  2. <p>Image of Mars. </p>  
There unfortunately isn’t any easy or semantic way to associate the caption, wrapped in a paragraph tag, with the image element itself. HTML5 rectifies this, with the introduction of the <figure> element. When combined with the <figcaption> element, we can now semantically associate captions with their image counterparts.
  1. <figure>  
  2.     <img src="path/to/image" alt="About image" />  
  3.     <figcaption>  
  4.         <p>This is an image of something interesting. </p>  
  5.     </figcaption>  
  6. </figure>  

3. <small> Redefined

Not long ago, I utilized the <small> element to create subheadings that are closely related to the logo. It’s a useful presentational element; however, now, that would be an incorrect usage. The small element has been redefined, more appropriately, to refer to small print. Imagine a copyright statement in the footer of your site; according to the new HTML5 definition of this element; the <small> would be the correct wrapper for this information.
The small element now refers to “small print.”

4. No More Types for Scripts and Links

You possibly still add the type attribute to your link and script tags.
  1. <link rel="stylesheet" href="path/to/stylesheet.css" type="text/css" />  
  2. <script type="text/javascript" src="path/to/script.js"></script>  
This is no longer necessary. It’s implied that both of these tags refer to stylesheets and scripts, respectively. As such, we can remove the type attribute all together.
  1. <link rel="stylesheet" href="path/to/stylesheet.css" />  
  2. <script src="path/to/script.js"></script>  

5. To Quote or Not to Quote.

…That is the question. Remember, HTML5 is not XHTML. You don’t have to wrap your attributes in quotation marks if you don’t want to you. You don’t have to close your elements. With that said, there’s nothing wrong with doing so, if it makes you feel more comfortable. I find that this is true for myself.
  1. <p class=myClass id=someId> Start the reactor.  
Make up your own mind on this one. If you prefer a more structured document, by all means, stick with the quotes.

6. Make your Content Editable

Content Editable
The new browsers have a nifty new attribute that can be applied to elements, called contenteditable. As the name implies, this allows the user to edit any of the text contained within the element, including its children. There are a variety of uses for something like this, including an app as simple as a to-do list, which also takes advantage of local storage.
  1. <!DOCTYPE html>  
  2.   
  3. <html lang="en">  
  4. <head>  
  5.     <meta charset="utf-8">  
  6.     <title>untitled</title>  
  7. </head>  
  8. <body>  
  9.     <h2> To-Do List </h2>  
  10.      <ul contenteditable="true">  
  11.         <li> Break mechanical cab driver. </li>  
  12.         <li> Drive to abandoned factory  
  13.         <li> Watch video of self </li>  
  14.      </ul>  
  15. </body>  
  16. </html>  
Or, as we learned in the previous tip, we could write it as:
  1. <ul contenteditable=true>  

7. Email Inputs

If we apply a type of “email” to form inputs, we can instruct the browser to only allow strings that conform to a valid email address structure. That’s right; built-in form validation will soon be here! We can’t 100% rely on this just yet, for obvious reasons. In older browsers that do not understand this “email” type, they’ll simply fall back to a regular textbox.
  1. <!DOCTYPE html>  
  2.   
  3. <html lang="en">  
  4. <head>  
  5.     <meta charset="utf-8">  
  6.     <title>untitled</title>  
  7. </head>  
  8. <body>  
  9.     <form action="" method="get">  
  10.         <label for="email">Email:</label>  
  11.         <input id="email" name="email" type="email" />  
  12.   
  13.         <button type="submit"> Submit Form </button>  
  14.     </form>  
  15. </body>  
  16. </html>  
Email Validation
At this time, we cannot depend on browser validation. A server/client side solution must still be implemented.
It should also be noted that all the current browsers are a bit wonky when it comes to what elements and attributes they do and don’t support. For example, Opera seems to support email validation, just as long as the name attribute is specified. However, it does not support the placeholder attribute, which we’ll learn about in the next tip. Bottom line, don’t depend on this form of validation just yet…but you can still use it!

8. Placeholders

Before, we had to utilize a bit of JavaScript to create placeholders for textboxes. Sure, you can initially set the value attribute how you see fit, but, as soon as the user deletes that text and clicks away, the input will be left blank again. The placeholder attribute remedies this.
  1. <input name="email" type="email" placeholder="doug@givethesepeopleair.com" />  
Again, support is shady at best across browsers, however, this will continue to improve with every new release. Besides, if the browser, like Firefox and Opera, don’t currently support the placeholder attribute, no harm done.
Validation

9. Local Storage

Thanks to local storage (not officially HTML5, but grouped in for convenience’s sake), we can make advanced browsers “remember” what we type, even after the browser is closed or is refreshed.


“localStorage sets fields on the domain. Even when you close the browser, reopen it, and go back to the site, it remembers all fields in localStorage.”

While obviously not supported across all browsers, we can expect this method to work, most notably, in Internet Explorer 8, Safari 4, and Firefox 3.5. Note that, to compensate for older browsers that won’t recognize local storage, you should first test to determine whether window.localStorage exists.
Support matrix
via http://www.findmebyip.com/litmus/

10. The Semantic Header and Footer

Gone are the days of:
  1. <div id="header">  
  2.     ...  
  3. </div>  
  4.   
  5. <div id="footer">  
  6.     ...  
  7. </div>  
Divs, by nature, have no semantic structure — even after an id is applied. Now, with HTML5, we have access to the <header> and <footer> elements. The mark-up above can now be replaced with:
  1. <header>  
  2.     ...  
  3. </header>  
  4.   
  5. <footer>  
  6.     ...  
  7. </footer>  
It’s fully appropriate to have multiple headers and footers in your projects.
Try not to confuse these elements with the “header” and “footer” of your website. They simply refer to their container. As such, it makes sense to place, for example, meta information at the bottom of a blog post within the footer element. The same holds true for the header.

11. More HTML5 Form Features

Learn about more helpful HTML5 form features in this quick video tip.


12. Internet Explorer and HTML5

Unfortunately, that dang Internet Explorer requires a bit of wrangling in order to understand the new HTML5 elements.
All elements, by default, have a display of inline.
In order to ensure that the new HTML5 elements render correctly as block level elements, it’s necessary at this time to style them as such.
  1. header, footer, article, section, nav, menu, hgroup {  
  2.    displayblock;  
  3. }  
Unfortunately, Internet Explorer will still ignore these stylings, because it has no clue what, as an example, the header element even is. Luckily, there is an easy fix:
  1. document.createElement("article");  
  2. document.createElement("footer");  
  3. document.createElement("header");  
  4. document.createElement("hgroup");  
  5. document.createElement("nav");  
  6. document.createElement("menu");  
Strangely enough, this code seems to trigger Internet Explorer. To simply this process for each new application, Remy Sharp created a script, commonly referred to as the HTML5 shiv. This script also fixes some printing issues as well.
  1. <!--[if IE]>  
  2. <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>  
  3. <![endif]-->  

13. hgroup

Imagine that, in my site’s header, I had the name of my site, immediately followed by a subheading. While we can use an <h1> and <h2> tag, respectively, to create the mark-up, there still wasn’t, as of HTML4, an easy way to semantically illustrate the relationship between the two. Additionally, the use of an h2 tag presents more problems, in terms of hierarchy, when it comes to displaying other headings on the page. By using the hgroup element, we can group these headings together, without affecting the flow of the document’s outline.
  1. <header>  
  2.     <hgroup>  
  3.         <h1> Recall Fan Page </h1>  
  4.         <h2> Only for people who want the memory of a lifetime. </h2>  
  5.     </hgroup>  
  6. </header>  

14. Required Attribute

Forms allow for a new required attribute, which specifies, naturally, whether a particular input is required. Dependent upon your coding preference, you can declare this attribute in one of two ways:
  1. <input type="text" name="someInput" required>  
Or, with a more structured approach.
  1. <input type="text" name="someInput" required="required">  
Either method will do. With this code, and within browsers that support this attribute, a form cannot be submitted if that “someInput” input is blank. Here’s a quick example; we’ll also add the placeholder attribute as well, as there’s no reason not to.
  1. <form method="post" action="">  
  2.     <label for="someInput"> Your Name: </label>  
  3.     <input type="text" id="someInput" name="someInput" placeholder="Douglas Quaid" required>  
  4.     <button type="submit">Go</button>  
  5. </form>  
Required and Placeholder Attributes
If the input is left blank, and the form is submitted, the textbox will be highlighted.

15. Autofocus Attribute

Again, HTML5 removes the need for JavaScript solutions. If a particular input should be “selected,” or focused, by default, we can now utilize the autofocus attribute.
  1. <input type="text" name="someInput" placeholder="Douglas Quaid" required autofocus>  
Interestingly enough, while I personally tend to prefer a more XHTML approach (using quotation marks, etc.), writing "autofocus=autofocus" feels odd. As such, we’ll stick with the single keyword approach.

16. Audio Support

No longer do we have to rely upon third party plugins in order to render audio. HTML5 now offers the <audio> element. Well, at least, ultimately, we won’t have to worry about these plugins. For the time being, only the most recent of browsers offer support for HTML5 audio. At this time, it’s still a good practice to offer some form of backward compatibility.
  1. <audio autoplay="autoplay" controls="controls">  
  2.     <source src="file.ogg" />  
  3.     <source src="file.mp3" />  
  4.     <a href="file.mp3">Download this file.</a>  
  5. </audio>  
Mozilla and Webkit don’t fully get along just yet, when it comes to the audio format. Firefox will want to see an .ogg file, while Webkit browsers will work just fine with the common .mp3 extension. This means that, at least for now, you should create two versions of the audio.
When Safari loads the page, it won’t recognize that .ogg format, and will skip it and move on to the mp3 version, accordingly. Please note that IE, per usual, doesn’t support this, and Opera 10 and lower can only work with .wav files.

17. Video Support

Much like the <audio> element, we also, of course, have HTML5 video as well in the new browsers! In fact, just recently, YouTube announced a new HTML5 video embed for their videos, for browsers which support it. Unfortunately, again, because the HTML5 spec doesn’t specify a specific codec for video, it’s left to the browsers to decide. While Safari, and Internet Explorer 9 can be expected to support video in the H.264 format (which Flash players can play), Firefox and Opera are sticking with the open source Theora and Vorbis formats. As such, when displaying HTML5 video, you must offer both formats.
  1. <video controls preload>  
  2.     <source src="cohagenPhoneCall.ogv" type="video/ogg; codecs='vorbis, theora'" />  
  3.     <source src="cohagenPhoneCall.mp4" type="video/mp4; 'codecs='avc1.42E01E, mp4a.40.2'" />  
  4.     <p> Your browser is old. <a href="cohagenPhoneCall.mp4">Download this video instead.</a> </p>  
  5. </video>  
Chrome can correctly display video that is encoded in both the “ogg” and “mp4″ formats.
There are a few things worth noting here.
  1. We aren’t technically required to set the type attribute; however, if we don’t, the browser has to figure out the type itself. Save some bandwidth, and declare it yourself.
  2. Not all browsers understand HTML5 video. Below the source elements, we can either offer a download link, or embed a Flash version of the video instead. It’s up to you.
  3. The controls and preload attributes will be discussed in the next two tips.

18. Preload Videos

The preload attribute does exactly what you’d guess. Though, with that said, you should first decide whether or not you want the browser to preload the video. Is it necessary? Perhaps, if the visitor accesses a page, which is specifically made to display a video, you should definitely preload the video, and save the visitor a bit of waiting time. Videos can be preloaded by setting preload="preload", or by simply adding preload. I prefer the latter solution; it’s a bit less redundant.
  1. <video preload>  

19. Display Controls

If you’re working along with each of these tips and techniques, you might have noticed that, with the code above, the video above appears to be only an image, without any controls. To render these play controls, we must specify the controls attribute within the video element.
  1. <video preload controls>  
Options
Please note that each browser renders its player differently from one another.

20. Regular Expressions

How often have you found yourself writing some quickie regular expression to verify a particular textbox. Thanks to the new pattern attribute, we can insert a regular expression directly into our markup.
  1. <form action="" method="post">  
  2.     <label for="username">Create a Username: </label>  
  3.     <input type="text"  
  4.        name="username"  
  5.        id="username"  
  6.        placeholder="4 <> 10"  
  7.        pattern="[A-Za-z]{4,10}"  
  8.        autofocus  
  9.        required>  
  10.     <button type="submit">Go </button>  
  11. </form>  
If you’re moderately familiar with regular expressions, you’ll be aware that this pattern: [A-Za-z]{4,10} accepts only upper and lowercase letters. This string must also have a minimum of four characters, and a maximum of ten.
Notice that we’re beginning to combine all of these new awesome attributes!
If regular expressions are foreign to you, refer here.

21. Detect Support for Attributes

What good are these attributes if we have no way of determining whether the browser recognizes them? Well, good point; but there are several ways to figure this out. We’ll discuss two. The first option is to utilize the excellent Modernizr library. Alternatively, we can create and dissect these elements to determine what the browsers are capable of. For instance, in our previous example, if we want to determine if the browser can implement the pattern attribute, we could add a bit of JavaScript to our page:
  1. alert( 'pattern' in document.createElement('input') ) // boolean;  
In fact, this is a popular method of determining browser compatibility. The jQuery library utilizes this trick. Above, we’re creating a new input element, and determining whether the pattern attribute is recognized within. If it is, the browser supports this functionality. Otherwise, it of course does not.
  1. <script>  
  2. if (!'pattern' in document.createElement('input') ) {  
  3.     // do client/server side validation  
  4. }  
  5. </script>  
Keep in mind that this relies on JavaScript!

22. Mark Element

Think of the <mark> element as a highlighter. A string wrapped within this tag should be relevant to the current actions of the user. For example, if I searched for “Open your Mind” on some blog, I could then utilize some JavaScript to wrap each occurrence of this string within <mark> tags.
  1. <h3> Search Results </h3>  
  2. <p> They were interrupted, just after Quato said, <mark>"Open your Mind"</mark></p>  

23. When to Use a <div>

Some of us initially questioned when we should use plain-ole divs. Now that we have access to headers, articles, sections, and footers, is there ever a time to use a…div? Absolutely.
Divs should be utilized when there’s no better element for the job.
For example, if you find that you need to wrap a block of code within a wrapper element specifically for the purpose of positioning the content, a <div> makes perfect sense. However, if you’re instead wrapping a new blog post, or, perhaps, a list of links in your footer, consider using the <article> and <nav> elements, respectively. They’re more semantic.

24. What to Immediately Begin Using

With all this talk about HTML5 not being complete until 2022, many people disregard it entirely – which is a big mistake. In fact, there are a handful of HTML5 features that we can use in all our projects right now! Simpler, cleaner code is always a good thing. In today’s video quick tip, I’ll show you a handful of options.


25. What is Not HTML5

People can be forgiven for assuming that awesome JavaScript-less transitions are grouped into the all-encompassing HTML5. Hey — even Apple has inadvertently promoted this idea. For non-developers, who cares; it’s an easy way to refer to modern web standards. However, for us, though it may just be semantics, it’s important to understand exactly what is not HTML5.
  1. SVG: Not HTML5. It’s at least five years old.
  2. CSS3: Not HTML5. It’s…CSS.
  3. Geolocation: Not HTML5.
  4. Client Storage: Not HTML5. It was at one point, but was removed from the spec, due to the fact that many worried that it, as a whole, was becoming too complicated. It now has its own specification.
  5. Web Sockets: Not HTML5. Again, was exported to its own specification.
Regardless of how much distinction you require, all of these technologies can be grouped into the modern web stack. In fact, many of these branched specifications are still managed by the same people.

26. The Data Attribute

We now officially have support for custom attributes within all HTML elements. While, before, we could still get away with things like:
  1. <h1 id=someId customAttribute=value> Thank you, Tony. </h1>  
…the validators would kick up a fuss! But now, as long as we preface our custom attribute with “data,” we can officially use this method. If you’ve ever found yourself attaching important data to something like a class attribute, probably for JavaScript usage, this will come as a big help!

HTML Snippet

  1. <div id="myDiv" data-custom-attr="My Value"> Bla Bla </div>  

Retrieve Value of the Custom Attribute

  1. var theDiv = document.getElementById('myDiv');  
  2. var attr = theDiv.getAttribute('data-custom-attr');  
  3. alert(attr); // My Val  
It can also even be used in your CSS, like for this silly and lame CSS text changing example.
  1. <!DOCTYPE html>  
  2.   
  3. <html lang="en">  
  4. <head>  
  5.    <meta charset="utf-8">  
  6.    <title>Sort of Lame CSS Text Changing</title>  
  7. <style>  
  8.   
  9. h1 { position: relative; }  
  10. h1:hover { color: transparent; }  
  11.   
  12. h1:hover:after {  
  13.     content: attr(data-hover-response);  
  14.     color: black;  
  15.     position: absolute;  
  16.     left: 0;  
  17.   
  18. }  
  19. </style>  
  20. </head>  
  21. <body>  
  22.   
  23. <h1 data-hover-response="I Said Don't Touch Me!"> Don't Touch Me  </h1>  
  24.   
  25. </body>  
  26. </html>  

27. The Output Element

As you probably have guessed, the output element is used to display some sort of calculation. For example, if you’d like to display the coordinates of a mouse position, or the sum of a series of numbers, this data should be inserted into the output element.
As a simple example, let’s insert the sum of two numbers into an empty output with JavaScript, when a submit button is pressed.
  1. <form action="" method="get">  
  2.     <p>  
  3.         10 + 5 = <output name="sum"></output>  
  4.     </p>  
  5.     <button type="submit"> Calculate </button>  
  6. </form>  
  7.   
  8. <script>  
  9. (function() {  
  10.     var f = document.forms[0];  
  11.   
  12.     if ( typeof f['sum'] !== 'undefined' ) {  
  13.         f.addEventListener('submit', function(e) {  
  14.             f['sum'].value = 15;  
  15.             e.preventDefault();  
  16.         }, false);  
  17.     }  
  18.     else { alert('Your browser is not ready yet.'); }  
  19. })();  
  20. </script>  
Try it out for yourself.
Please note that support for the output element is still a bit wonky. At the time of this writing, I was only able to get Opera to play nice. This is reflected in the code above. If the browser does not recognize the element, the browser will simply alert a notice informing you of as much. Otherwise, it finds the output with a name of “sum,” and sets its value to 15, accordingly, after the form has been submitted.
Output element
This element can also receive a for attribute, which reflects the name of the element that the output relates to, similar to the way that a label works.

28. Create Sliders with the Range Input

HTML5 introduces the new range type of input.
  1. <input type="range">  
Most notably, it can receive min, max, step, and value attributes, among others. Though only Opera seems to support this type of input right now fully, it’ll be fantastic when we can actually use this!
For a quick demonstration, let’s build a gauge that will allow users to decide how awesome “Total Recall” is. We won’t build a real-world polling solution, but we’ll review how it could be done quite easily.

Step 1: Mark-up

First, we create our mark-up.
  1. <form method="post">  
  2.     <h1> Total Recall Awesomness Gauge </h1>  
  3.     <input type="range" name="range" min="0" max="10" step="1" value="">  
  4.     <output name="result">  </output>  
  5. </form>  
Unstyled range input
Notice that, in addition to setting min and max values, we can always specify what the step for each transition will be. If the step is set to 1, there will then be 10 values to choose. We also take advantage of the new output element that we learned about in the previous tip.

Step 2: CSS

Next, we’ll style it just a bit. We’ll also utilize :before and :after to inform the user what our specified min and max values are. These trick, via “Introducing HTML5.”
  1. body {  
  2.     font-family'Myriad-Pro''myriad'helveticaarialsans-serif;  
  3.     text-aligncenter;  
  4. }  
  5. input { font-size14pxfont-weightbold;  }  
  6.   
  7. input[type=range]:before { contentattr(min); padding-right5px; }  
  8. input[type=range]:after { contentattr(max); padding-left5px;}  
  9.   
  10. output {  
  11.     displayblock;  
  12.     font-size: 5.5em;  
  13.     font-weightbold;  
  14. }  
Above, we create content before and after the range input, and make their values equal to the min and max values, respectively.
Styled Range

Step 3: The JavaScript

Lastly, we:
  • Determine if the current browser knows what the range input is. If not, we alert the user that the demo won’t work.
  • Update the output element dynamically, as the user moves the slider.
  • Listen for when the user mouses off the slider, grab the value, and save it to local storage.
  • Then, the next time the user refreshes the page, the range and output will automatically be set to what they last selected.
  1. (function() {  
  2.     var f = document.forms[0],  
  3.         range = f['range'],  
  4.         result = f['result'],  
  5.         cachedRangeValue = localStorage.rangeValue ? localStorage.rangeValue : 5;   
  6.   
  7.     // Determine if browser is one of the cool kids that  
  8.     // recognizes the range input.  
  9.     var o = document.createElement('input');  
  10.     o.type = 'range';  
  11.     if ( o.type === 'text' ) alert('Sorry. Your browser is not cool enough yet. Try the latest Opera.');  
  12.   
  13.     // Set initial values of the input and ouput elements to  
  14.     // either what's stored locally, or the number 5.  
  15.     range.value = cachedRangeValue;  
  16.     result.value = cachedRangeValue;  
  17.   
  18.     // When the user makes a selection, update local storage.  
  19.     range.addEventListener("mouseup"function() {  
  20.         alert("The selected value was " + range.value + ". I am using local storage to remember the value. Refresh and check on a modern browser.");  
  21.         localStorage ? (localStorage.rangeValue = range.value) : alert("Save data to database or something instead.");  
  22.     }, false);  
  23.   
  24.     // Display chosen value when sliding.  
  25.     range.addEventListener("change"function() {  
  26.         result.value = range.value;  
  27.     }, false);  
  28.   
  29. })();  
Styled Range with JS
Ready for the real world? Probably not yet; but it’s still fun to play with and prep for!
Download the source code, and try it out for yourself. But use Opera.