2011年12月28日 星期三

[HTML5] A sample for drag and drop.




<html>
 <body>
  <form>
<ul id="list1" ondragstart="onDragStart(event)"
ondragenter="onDragEnter(event)"
ondragover="onDragOver(event)"
ondrop="onDrop(event)">
<li id="apple1" draggable="true">CCCCC</li>
<li id="orange1" draggable="true">OOOOO</li>
<li id="grape1" draggable="true">ooooo</li>
</ul>
<ul id="list2" ondragstart="onDragStart(event)"
ondragenter="onDragEnter(event)"
ondragover="onDragOver(event)"
ondrop="onDrop(event)">
<li id="apple2" draggable="true">APPLE</li>
<li id="orange2" draggable="true">ORANGE</li>
<li id="grape2" draggable="true">GRAPE</li>
</ul>
</form>

  <script type="text/javascript">
function onDragStart(event)
{
if (event.target.tagName.toLowerCase() == "li")
{
event.dataTransfer.setData('Text', event.target.id);
}
else
{
event.preventDefault();
}
}

function onDrop(event)
{
var iid = event.dataTransfer.getData('Text');
var li = document.getElementById(iid);

if (li && li.parentNode != event.currentTarget)
{
li.parentNode.removeChild(li);
event.currentTarget.appendChild(li);
}
event.stopPropagation();
}

function onDragOver(event)
{
event.preventDefault();
}

function onDragEnter(event)
{
var types = event.dataTransfer.types;
for (var i=0; i<types.length; i++)
{
if (types[i] == 'Text')
{
event.preventDefault();
return;
}
}
}
  </script>
 </body>
</html>




















Reference: http://www.books.com.tw/exep/prod/booksfile.php?item=0010480450

2011年12月27日 星期二

[HTML5] A simple clock.

This is a shabby clock.



<html>
 <body>
  <canvas id="canvas1" width="300" height="200"></canvas>
  <script type="text/javascript">

  setInterval(drawClock, 1000);

function drawClock()
{
// get canvas and datetime
var canvas = document.getElementById("canvas1");
  var cx = canvas.getContext("2d");
  var currentDate = new Date();
  var hours = currentDate.getHours();
  var mins = currentDate.getMinutes();
  var secs = currentDate.getSeconds();
 
  cx.clearRect(0, 0, canvas.width, canvas.height);
 
  cx.fillStyle = "red";
  cx.fillRect(0, 0, 2 * hours * 60 / 24, 20);
  cx.fillText("Hour: " + hours, 130, 20);
 
  cx.fillStyle = "blue";
  cx.fillRect(0, 20, 2 * mins, 20);
  cx.fillText("Minute: " + mins, 130, 40);
 
  cx.fillStyle = "green";
  cx.fillRect(0, 40, 2 * secs, 20);
  cx.fillText("Second: " + secs, 130, 60);
}
  </script>
 </body>
</html>




This is its output.

2011年12月26日 星期一

[HTML5] Hello Canvas!

This is a simple example to draw on a HTML5 canvas with javascript.


<html>
<body>
<canvas id="canvas1" width="300" height="200"></canvas>
<script type="text/javascript">
// get canvas
var canvas = document.getElementById("canvas1");
var context = canvas.getContext("2d");

// fill rectagle
context.fillRect(0,0,150,100);

// fill text
context.fillText("Hello, Canvas!", 155, 110);

// draw a line
context.beginPath();
context.moveTo(0, 100);
context.lineTo(300, 100);
context.moveTo(150, 0);
context.lineTo(150, 200);
context.rect(0, 0, 300, 200);
context.stroke();
context.closePath();
</script>
</body>
</html>


The result such like below,


Reference: http://www.books.com.tw/exep/prod/booksfile.php?item=0010480450

2011年12月16日 星期五

[SQLite] Truncate table

In SQL server or mysql, you can delete all data from a table and set auto-increment identity to zero by the command below:

TRUNCATE TABLE [TableName];

In SQLite, there is no command for truncate tables, you should remove data and set identity by yourself.

DELETE FROM  [TableName]; 
UPDATE sqlite_sequence SET seq=0 WHERE name=' TableName'; 

2011年12月14日 星期三

[.Net] New Line in TextBox

In ASP.net, you should use \n for getting your mouse cursor to new line.
But in WindowsApplication, you should use \r\n to get new line.

\n is new line character for Linux system occupy 1 byte.
\r\n is new line character for Windows system occupy 2 bytes.

2011年12月13日 星期二

[.Net] Create SQLite database and datatable with .net framework

This is sample code for creating a new database file and table in SQLite.

            string m_dataSource = "test1.s3db";
            SQLiteConnection.CreateFile(m_dataSource);
            DbProviderFactory factory = SQLiteFactory.Instance;
            using (DbConnection conn = factory.CreateConnection())
            {
                // Create DB
                conn.ConnectionString = "Data Source=" + m_dataSource;
                conn.Open();
                // Create Table
                string sql = "create table [aa] ([id] INTEGER PRIMARY KEY, [s] TEXT COLLATE NOCASE)";
                DbCommand cmd = conn.CreateCommand();
                cmd.Connection = conn;
                cmd.CommandText = sql;
                cmd.ExecuteNonQuery();
            }



Reference:
http://hirocat.pixnet.net/blog/post/40514692-%E5%A6%82%E4%BD%95%E9%AB%98%E6%95%88%E4%BD%BF%E7%94%A8sqlite-.net-(c%23)


2011年10月4日 星期二

[.Net] The type 'Microsoft.CompactFramework.Design.UnsafeUserControl' has no property named 'XXX'

I create a user control and it use another user control.
It met some problem when I view it's design and the saw the message,
The type 'Microsoft.CompactFramework.Design.UnsafeUserControl' has no property named 'XXX'

I follow the step as below to work around it,
1. In the Solution Explorer of VS2005, right click on the class file and 
select "View Class Diagram" (This will open the Class Diagram file). 

2. Select the class and open the Properties window. 

3. In the "Custom Attributes" field, click the browse button. A dialog 
will be displayed and enter the following: DesktopCompatible(true) 





Reference:
http://forum.soft32.com/pda/VS2005-Design-UnsafeUserControl-Error-ftopict60562.html

2011年10月3日 星期一

[.Net] Reading scrambled words in txt file

There is a txt file with Chinese words and I read it string by StreadReader.
I set encoding to default, but words still scrambled.


Solution:

I open the txt file and set encoding as Unicode then work well.

2011年8月30日 星期二

[Android] How to read and parse xml files in android application.

I have a xml file named books.xml that is stored in my pad.

<?xml version="1.0" encoding="UTF-8"?>
<library-metadata title="My library">
  <book-metadata name="One Day" author="Nicholls, David">
    <publish-info publisher="Random House Inc" date="05-24-2011" ISBN="9780307946713"/>
  </book-metadata>
  <book-metadata name="Transformers: Exodus" author="Irvine, Alex">
    <publish-info publisher="Random House" date="06-28-2011" ISBN="9780345522528"/>
  </book-metadata>
</book-metadata>

I want to read the xml content and save it to my custom class.
The code as below.


        final String path = Environment.getExternalStorageDirectory().getPath() + "/books.xml";
        FileInputStream fstream = null;
        try
        {
            // read file.
            fstream = new FileInputStream(path);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(fstream);
            Element root = document.getDocumentElement();


            NodeList bookList = root.getElementsByTagName("book-metadata");
            for (int i = 0; i < bookList.getLength(); i++)
            {
                Element bookElement = (Element) bookList.item(i);


                NodeList publishList = bookElement.getElementsByTagName("publish-info");
                for (int j = 0; j < publishList.getLength(); j++)
                {
                    classBooks myBook = new classBooks();
                    Element publishElement = (Element) publishList.item(j);


                    // get xml value and set it into class object.
                    myBook.setName(Integer.parseInt(bookElement.getAttribute("name")));
                    myBook.setAuthor(bookElement.getAttribute("author"));
                    myBook.setPublisher(publishElement.getAttribute("publisher"));
                    myBook.setPublishDate(publishElement.getAttribute("date"));
                    myBook.setISBN(publishElement.getAttribute("ISBN"));


                    m_bookList.add(myBook);  // m_bookList is a member collection variable.
                }
            }
        }
        catch (Exception exception)
        {
            exception.printStackTrace();
        }
        finally
        {
            if (null != fstream)
            {
                fstream.close();
            }
        }

2011年8月2日 星期二

[.Net] Can't find PInvoke DLL 'sqlceme35.dll

You need to install Compact on the device if you met the problem.


1. Copy the file sqlce.ppc.wce5.armv4i.CAB in the path 
C:\Program Files\Microsoft SQL Server Compact Edition\v3.5\Devices\wce500\armv4i into device or emulator


2. execute it on device.




Reference:
http://social.msdn.microsoft.com/Forums/en-US/sqlce/thread/8faa4e72-2dfe-44d4-b8b1-8fd64df01e7d/






[.Net] Emulate a storage card using folder sharing

We hope to simulate a storage card insert into Microsoft Device Emulator.
We have to create a folder shared to the emulator, it appears as a storage card.
You can also stop folder sharing when you no longer want to work with an emulated storage card.


To activate folder sharing

  1. On the Device Emulator File menu, click Configure.
  2. Select the General tab.
  3. In the Shared folder box, type the path and folder name for the directory you want to use as an emulated storage card. (also can click the Browse button, navigate to the directory that you want to use.)
  4. Click OK.


Reference:
http://msdn.microsoft.com/en-us/library/aa188184(v=vs.90).aspx

2011年7月27日 星期三

[Android] Read string from external files

There is a txt file named text.txt and it's content as below.
hello string.

I put the file into sdcard of my Pad under folder named /myfile.
I want get the content of the file in my android program.

At first of all, making sure your sdcard is ready.

       File fileSDCard = null;
       if(Environment.getExternalStorageState().equals(Environment.MEDIA_REMOVED))
       {
          return;
       }
       else
       {
           fileSDCard = Environment.getExternalStorageDirectory();
       }

next, open the file and read it.
       FileInputStream fstream = null;
       String readString = "";  
       try 
       {
           fstream = new FileInputStream(fileSDCard.getParent() + "/" + fileSDCard.getName() + "/myfile/test.txt");
           StringBuffer buffer = new StringBuffer();
           int readChar; 
           while ((readChar = fstream.read()) != -1) 
           { 
               buffer.append((char) readChar); 
           } 
           fstream.close(); 
           readString = buffer.toString(); 
       } 
       catch (Exception e) 
       {
           e.printStackTrace();
       }

It's done, so easy, isn't it?

2011年6月17日 星期五

[Android] Generating multitouch MotionEvents for testing

For testing the behaviour of the GestureDetector, i want to send MotionEvents to check action result.


Above android 2.3 we can use the method 'obtain' to get multitouch event.

public static MotionEvent obtain (long downTime, long eventTime, int action, int pointers, int[] pointerIds, PointerCoords[] pointerCoords, int metaState, float xPrecision, float yPrecision, int deviceId, int edgeFlags, int source, int flags)
            //action is an int variable indicate what event type to send. (DOWN, UP, POINIT_DOWN....)
            //point is an PointF array to indecate all coordinates touch on screen.
            int[] pointCoordsID = new int[point.length];
            PointerCoords[] pointCoords = new PointerCoords[point.length];
            for (int i = 0; i < point.length; i++) 
            {
                pointerIds[i] = i;
                pointerCoords[i] = new PointerCoords();
                pointerCoords[i].x = point[i].x;
                pointerCoords[i].y = point[i].y;
            }            
            long downTime = SystemClock.uptimeMillis();
            long eventTime = SystemClock.uptimeMillis();

            MotionEvent event = MotionEvent.obtain(downTime, eventTime, action, point.lenth, pointCoordsID, pointCoords, 0, 1, 1, 0, 0, 0, 0);



#########################################################


If your device or sdk is android 2.2 or lower, you have to create MotionEvent from Parcel as below to perform it.


            //action is an int variable indicate what event type to send. (DOWN, UP, POINIT_DOWN....)
            //point is an PointF array to indecate all coordinates touch on screen.

            Parcel inParcel = Parcel.obtain();

            long downTime = SystemClock.uptimeMillis();
            long eventTime = SystemClock.uptimeMillis();
            inParcel.writeLong(downTime); //DownTime
            inParcel.writeLong(eventTime); //EventTime
            inParcel.writeInt(action);         //Action
            inParcel.writeInt(0);         //MetaState
            inParcel.writeFloat(point[0].x); //RawX
            inParcel.writeFloat(point[0].y); //RawY
            final int NP = m_point.length; //NumPointers
            inParcel.writeInt(NP);
            final int NS = m_point.length; //NumSamples
            inParcel.writeInt(NS);
            final int NI = NP*NS;
            if (NI > 0) 
            {
                int i;               
                //set point index
                for (i=0; i<NP; i++) 
                {
                inParcel.writeInt(i);
                }
                // set location, pressure, size for each sampleData
                int NUM_SAMPLE_DATA = 4;
                final int ND = NI*NUM_SAMPLE_DATA;
                float[] history = new float[ND];;
                for (i = 0; i < m_point.length; i++) 
                {
                history[i*NUM_SAMPLE_DATA] = point[i].x;
                history[i*NUM_SAMPLE_DATA + 1] = point[i].y;
                history[i*NUM_SAMPLE_DATA + 2] = 0;
                history[i*NUM_SAMPLE_DATA + 3] = 0;
                }
                for (i=0; i<ND; i++) 
                {
                inParcel.writeFloat(history[i]);
                }
                // set event time for each sampleData
                for (i=0; i<NS; i++) 
                {
                inParcel.writeLong(eventTime);
                }
            }
            inParcel.writeFloat(1); //PrecisionX
            inParcel.writeFloat(1); //PrecisionY
            inParcel.writeInt(0); //DeviceID
            inParcel.writeInt(0); //EdgeFlags
            
            inParcel.setDataPosition(0);
            
            MotionEvent event = MotionEvent.CREATOR.createFromParcel(inParcel);


###########################################


Reference:
http://stackoverflow.com/questions/3637044/generating-multitouch-motionevents-for-testing

2011年6月16日 星期四

[Android] Error: java.lang.NoClassDefFoundError

I got an error message: java.lang.NoClassDefFoundError

I tried to google antidote all day...

Here is a way to work it out but it doesn't match my case.
http://www.tech-recipes.com/rx/826/java-exception-in-thread-main-javalangnoclassdeffounderror/


Eventually, I found my SDK is android 3.0 but my device is android 2.2... (so stupid...)


Check SDK or device version is necessary.  :~|



2011年6月10日 星期五

[Android] Junit: get private variable, invoke private function

When we writing a JUnit test case, we sometimes need to get private member variable to verify the testing result or invoke private function to simulate software process.
We can use the object named PrivateAccessor to get private member like below.

To get private variable:
Integer.parseInt(PrivateAccessor.getPrivateField(Object, "Index").toString());

To invoke private function:
// The arguments to be passed to method
Object[] params = new Object[1]; 
params[0] = 0;
PrivateAccessor.invokePrivateMethod(Object, "functionName", params); 


Reference:
http://junit-addons.sourceforge.net/junitx/util/PrivateAccessor.html