Saturday, August 27, 2011

Android - Use websites in your app (WebView Tutorial)

Summary
This is an Android tutorial on a really simple way to get started using the WebView.

Description
You can use a WebView to display a website the same way you would when you open a browser on your Android device.  You can use a WebView to display a saved or self-made html document, view a website, or display strings in html format.
Although it is beyond this really simple tutorial, you can bind javascript to Android code.  You can find more information on this at http://developer.android.com/guide/webapps/webview.html.

Before we begin
I'm using Eclipse (Indigo x64) with the ADT plugin on Windows 7 x64.  My target API is Android 1.6 so that the application is backwards compatible with all others beyond 1.6.


Steps

  1. Create a new Android project
  2. Add a WebView to your activity layout
  3. Add the permission to the manifest file
  4. Add the code to your Activity

1.  Create a new Android project
Go to File > New > Android Project.  For the project name, I choose "WebViewDemo".  In the build target, select Android 1.6 for compatibility.  For the package name, I choose "com.projects.WebViewDemo".
Select Finish and you should have a project that looks like Figure 1.1.

Figure 1.1

2.  Add a WebView to your activity layout
In the Project Explorer, find your project, and navigate to "res\layout\main.xml".  Open "main.xml" and you eclipse will show "main.xml" in the Graphical Layout Editor (Figure 2.1).  Just under the Graphical Layout Editor, select the tab "main.xml" (This tab is circled in Figure 2.1).  

Figure 2.1

Now that we can see the XML document.  Lets add the following code as show in Figure 2.2.

<android.webkit.WebView 
android:id="@+id/wvwMain" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent">
</android.webkit.WebView>

Figure 2.2

3. Add the permission to the manifest file
Your WebView will need to access the internet and your application will need to ask for permission to do this.  
In the Project Explorer, find your project, and open "AndroidManifest.xml".  Eclipse will open the "AndroidManifest.xml" (Figure 3.1).  Just under this editor, select the tab "AndroidManifest.xml" (This tab is circled in Figure 3.1).  

Figure 3.1

Now that we can see the XML document.  Lets add the following code as show in Figure 3.2.

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Figure 3.2

4.  Add the code to your activity
In the Project Explorer, find your project, and navigate to "res\com.projects.WebViewDemo\WebViewDemoActivity.java".  If you used a different project name or package name than the ones I used,  you will find the .java file under the names you used.  Open the ".java" file, mine is "WebViewDemoActivity.java" (Figure 4.1).  

Figure 4.1

Lets add the following code to the activity as in Figue 4.2:

Starting at the import section add:
import android.webkit.WebView;

After the Activity starts (and before the "@Override" line) add:
WebView browser;

In the OnCreate method of the Activity add:

        // find the WebView by name in the main.xml of step 2
        browser=(WebView)findViewById(R.id.wvwMain);
        
        // Enable javascript
        browser.getSettings().setJavaScriptEnabled(true);  
        
        // load a webpage
        browser.loadUrl("http://news.google.com/");

Figure 4.2

That's it!
Run your program and see the results! 


Final Notes:
You'll notice that the browser you created has no status bar or navigation URL portion at the top.  This was the goal.  For example, I make an ASP.NET website and want my android application to view only certain pages as well as control the navigation.  Another example, I could make an html document, store it locally, load it with the WebView, and bind the javascript to your Android code.  

Comments/Questions?
I'm always wanting to improve the quality of the content here.  If you have questions, want to see a better explanation, a better picture, let me know.  Thanks - Sean

Friday, August 26, 2011

Fill PDF forms in C# with iTextSharp

Summary:
This tutorial is about using the iTextSharp library using C# in Visual Studio 2010


Description:
We will take user input from a Windows Forms project and place the input into the appropriate fields of an existing PDF document.


I fill out a lot of forms at work.  These forms never change.  Every week, I'm always using the same form and entering data in the same fields (on paper).  It seems like a perfect opportunity to make the process easier by doing it electronically.  


Before we start:
This tutorial assumes that you have an editable PDF with text fields named: "NAME", "ADDRESS", "CITY", and "STATE".  If I could post the template PDF to use as an example I would.  This is the only thing I can't provide with this tutorial.  If you can make a pdf file (somehow), and add the above listed textfields.  The rest of the tutorial should be easy.  If you want to substitute your own template PDF with editable text fields, rock on.  Pay special attention to matching the name (and case) of the PDF text field with the "fields.SetFields("pdf text field", string) parts.  


Steps:


  1. Download the iTextSharp library
  2. Extract the iTextSharp library
  3. Start new C# Windows Forms project
  4. Add reference to the iTextSharp library
  5. Add the needed controls (textboxes, buttons, labels) to our form
  6. Add a folder for the template PDF and place the PDF file in the folder
  7. Add the code to the project
  8. Done!! Check for the output file


1. Download iTextSharp
Download the iTextSharp library at http://sourceforge.net/projects/itextsharp/






2. Extract the iTextSharp library
Extract the library to a new folder that you can find again.  I extracted mine to my Visual Studio directory.  For example, "\Visual Studio 2010\external libraries\iText lib"


3. Create a new C# Windows Forms project
Start Visual Studio 2010.  Select "New Project".  Next, under C#, select "Windows Forms Application".  Name the solution something like "FormFillerPDF" and select "OK".


4.  Add a reference to the iTextSharp library
In your Solution Explorer, right click on "Reference".  Left-click on "Add Reference..." (Figure 4.1)
(Alternatively, you can also select "Project" then "Add Reference..." from the menu.)  Now you'll need to find the folder where you extracted the iTextSharp library in step 2. In that location, find "itextsharp.dll" and select "OK".  (Figure 4.2) 




Figure 4.1




Figure 4.2


5.  Add the needed controls to our form
Add five labels, four textbox, and two button controls to the form. (Figure 5.1)
Arange the controls the same way as they are arranged in Figure 5.1
Name the textboxes (from top to bottom): txtName, txtAddress, txtCity, txtState
Name the buttons (from left to right): btnReset, btnSubmit
Name the labels (from top to bottom): Name, Address, City, State 
Place the last label below everything else, name it "lblResult", and change the text to "Result: "


Figure 5.1


6,  Add a folder for the template PDF and place the PDF file in the folder
In the Solution Explorer, right-click on your project name (FormFillerPDF), and select "Add" then "New Folder".  Name the folder "PDF", place your template PDF in the folder.  Name your PDF file "BasePDF".


7.  Add the code to the project



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


using System.IO; // This is for file access
using iTextSharp.text.pdf; // This is for iText


namespace FormFillerPDF
{
    public partial class frmFiller : Form
    {
        public frmFiller()
        {
            InitializeComponent();
        }


        private void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {


                // get the file paths


                // Template file path
                string formFile = "PDF\\BasePDF.pdf";
                
                // Output file path
                string newFile = "PDF\\Filled-out Form.pdf";                


                // read the template file
                PdfReader reader = new PdfReader(formFile);


                // instantiate PDFStamper object
                // The Output file will be created from template file and edited by the PDFStamper
                PdfStamper stamper = new PdfStamper(reader, new FileStream(
                            newFile, FileMode.Create));


                // Object to deal with the Output file's textfields
                AcroFields fields = stamper.AcroFields;


                // set form fields("Field Name in PDF", "String to be placed in this PDF text field");
                fields.SetField("NAME", txtName.Text);
                fields.SetField("ADDRESS", txtAddress.Text);
                fields.SetField("CITY", txtCity.Text);
                //fields.SetField("STATE", txtState.Text);


                // form flattening rids the form of editable text fields so
                // the final output can't be edited
                stamper.FormFlattening = true;


                // closing the stamper
                stamper.Close();                


                // If the code above works, we should see the following
                lblResult.Text = "Result: Success";


                // After everything is done, we are setting the textbox text properties to ""
                btnReset_Click(sender, e);


            }


            catch (Exception ex)
            {
                // Make my exception's visible (if any)
                lblResult.Text = ex.ToString();
            }            
        }


        private void btnReset_Click(object sender, EventArgs e)
        {
            txtName.Text = "";
            txtAddress.Text = "";
            txtCity.Text = "";
            txtState.Text = "";
        }
    }
}





8.  Done!!! Check for the output file.  Look for the file "Filled-out Form.pdf".  It will be located in your project directory\bin\debug




Comments/Questions?
I'm always wanting to improve the quality of the content here.  If you have questions, want to see a better explanation, a better picture, let me know.  Thanks - Sean








Wednesday, August 24, 2011

The RC Car Hack - Appendix A - Reference Code



The RC Car Hack - Appendix A
Code used


Summary

This is the working code used for the project.


Tutorial Contents

     This tutorial is broken into many parts/posts as there is plenty of content to show.

  1. Introduction
  2. Description of items/stuff used
  3. Getting inside your RC Car
  4. More soon...
  5. Code used (Reference)

Code in C#:

When starting a new winforms project, the following would be used in the main form. 


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;

namespace CIS169_SerialDemo
{
    public partial class frmSerial : Form
    {
        // Create a new instance of the clsSerial class
        clsSerial mySerial = new clsSerial();

        public frmSerial()
        {
            InitializeComponent();
        }

        // When a key is pressed, respond
        private void frmSerial_KeyDown(object sender, KeyEventArgs e)
        {
            string str = e.KeyData.ToString();

            if (!string.IsNullOrEmpty(str))
            {
                // The key is sent to the clsSerial (mySerial) class
                mySerial.writeSerial(str);
            }

            else
            { 
                
            }
        }
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Display the about form.
            // Create a new instance of the frmAbout form class
            frmAbout myAbout = new frmAbout();
            // Show the new aboutForm object.
            myAbout.ShowDialog();           
        }

        private void frmSerial_FormClosing(object sender, FormClosingEventArgs e)
        {
            mySerial.closeSerial();
        }
    }
}

As you might notice, the only significant part of that code is "mySerial" (at the beginning).  "mySerial" is created from the "clsSerial" class.  The following code is for the clsSerial class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;

namespace CIS169_SerialDemo
{   
    class clsSerial
    {
        // Making the serialport
        SerialPort mySerialPort = new SerialPort();
    
        // Constructor adds the needed details for the serial connection
        // and then open's the serial.
        public clsSerial()
        {
            setupSerial();
            openSerial();
        }

        private void setupSerial()
        {
                      // COM9 was where my bluetooth was located
                      // Your "PortName" may be different as your
                      // bluetooth may be located somewhere else
            mySerialPort.PortName = "COM9";
            mySerialPort.BaudRate = 9600;
            mySerialPort.Parity = Parity.None;
            mySerialPort.StopBits = StopBits.One;        
        }

        // Open the serialport, if its not available
        // then try again.
        private void openSerial()
        {
            try
            {
                if (!mySerialPort.IsOpen)
                {
                    mySerialPort.Open();
                }
            }
            catch (Exception e)
            {
                // Try again code would be posted but
                // I need to be able to test without the serial connection
                // openSerial();
            }
        }

        // Close the serialport 
        public void closeSerial()
        {
            if (mySerialPort.IsOpen)
            {
                mySerialPort.Close();
            }
        }

        // Used to write to the serial port and get the response
        public void writeSerial(string str)
        {
            openSerial();
            string cmd = str;
            // Checking for any value
            if (!string.IsNullOrEmpty(cmd))
            {
                mySerialPort.Write(cmd);
                // To ensure the conversation is going well, we listen for bot to speak
                          // After sending the command, the code on the Arduino will respond via
                          // the "Serial.println" portions to acknowledge the receipt of the message
                          // that we just sent.  The next lines listen for this.
                mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
            }
        }


        

        // This is used to debug my commands sent
        /* 
         * After a command is sent from this machine, the other machine will
         * receive the command, respond back through serial, and act.
         * The console.write presents me with a way to check the 
         * command/response situations.
        */
        private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                SerialPort sp = (SerialPort)sender;
                string indata = sp.ReadLine();
                Console.Write(indata);
            }
            catch (Exception myexception)
            { 
                // For demo purposes... do nothing (not the coolest thing to do)
            }
        }
    }  
}
Code for Arduino:
     This is the sketch used for the Arduino.  (A sketch is the entire file containing the code for your Arduino)


/*
DMACC
CIS169
Sean

Main ref's:
arduino.cc
http://www.ladyada.net/make/mshield/index.html
http://www.sparkfun.com
MSDN
*/

// for the library (using/import)
#include <AFMotor.h>

// For the motors from the library
AF_DCMotor leftMotor(2, MOTOR12_64KHZ);
AF_DCMotor rightMotor(1, MOTOR12_64KHZ);

// variables
char val;         // variable to receive data from the serial port
int ledpin = 2;  // LED connected to pin 2 (on-board LED)
int counter = 0; // Used to toggle the LED


void setup()
{

  pinMode(ledpin = 13, OUTPUT);  // pin 13 (on-board LED) as OUTPUT

  Serial.begin(115200);       // start serial communication at 115200bps

 // set motor speed (range is 0 - 255)
  leftMotor.setSpeed(200);
  rightMotor.setSpeed(200);
}

void loop() {
  if( Serial.available() )       // if data is available to read
  {;}
    val = Serial.read();         // read it and store it in 'val'


 // All code follows the same format....
 // Respond, set the speed, action.


 // Turn in place to the left
  if( val == '0' )            
  {
    // Respond
    Serial.println("CMD: SPIN LEFT");
    // Set the speed
    leftMotor.setSpeed(255);
    rightMotor.setSpeed(255);
    // Action
    leftMotor.run(BACKWARD);
    rightMotor.run(FORWARD);
  }

  // if '1' was received led 13 is switched to it's opposite state
  if( val == '1' )  
  {
   toggle();
  }

    //stop
  if( val == '2')
  {
    Serial.println("CMD: STOP");
    leftMotor.setSpeed(255);
    rightMotor.setSpeed(255);
 
    leftMotor.run(RELEASE);
    rightMotor.run(RELEASE);
  }

    // forward
  if( val == '3')
  {
    Serial.println("CMD: FORWARD");
    leftMotor.setSpeed(255);
    rightMotor.setSpeed(255);
 
    leftMotor.run(FORWARD);
    rightMotor.run(FORWARD);
  }
   // backward
  if( val == '4')
  {
    Serial.println("CMD: BACKWARD");
    leftMotor.setSpeed(255);
    rightMotor.setSpeed(255);
 
    leftMotor.run(BACKWARD);
    rightMotor.run(BACKWARD);
  }

  // forward to the left
  if( val == '5')
  {
    Serial.println("CMD: FORWARD LEFT");
    leftMotor.setSpeed(30);
    rightMotor.setSpeed(255);
 
    leftMotor.run(FORWARD);
    rightMotor.run(FORWARD);
  }

  // forward to the right
  if( val == '6')
  {
    Serial.println("CMD: FORWARD RIGHT");
    leftMotor.setSpeed(255);
    rightMotor.setSpeed(30);
 
    leftMotor.run(FORWARD);
    rightMotor.run(FORWARD);
  }

  // backward to the left, port side
  if( val == '7')
  {
    Serial.println("CMD: BACKWARD LEFT");
    leftMotor.setSpeed(30);
    rightMotor.setSpeed(255);
 
    leftMotor.run(BACKWARD);
    rightMotor.run(BACKWARD);
  }

  // backward to the right, starboard side
  if( val == '8')
  {
    Serial.println("CMD: BACKWARD RIGHT");
    leftMotor.setSpeed(255);
    rightMotor.setSpeed(30);
 
    leftMotor.run(BACKWARD);
    rightMotor.run(BACKWARD);
  }

  // turn in-spot to the right
  if( val == '9')
  {
    Serial.println("CMD: SPIN RIGHT");
    leftMotor.setSpeed(255);
    rightMotor.setSpeed(255);
 
    leftMotor.run(FORWARD);
    rightMotor.run(BACKWARD);
  }


}

// turn the LED on or off with one value
void toggle()
{
  if (counter == 0)
  {
    digitalWrite(ledpin = 13, HIGH);
    Serial.println("CMD: LIGHT ON");
    counter++;
  }
  else
  {
    digitalWrite(ledpin = 13, LOW);
    Serial.println("CMD: LIGHT OFF");
    counter--;
  }

}



Comments/Questions?
I'm always wanting to improve the quality of the content here.  If you have questions, want to see a better explanation, a better picture, let me know.  Thanks - Sean



Thursday, August 18, 2011

The RC Car Hack - Part 1 - Introduction


The RC Car Hack
Summary
This is a tutorial following my implementation of the RC Car Hack.


Project  Goal
The goal of this tutorial is to give a little guidance to others who are interested in the RC Car Hack.  What is the RC Car Hack?  First off, I didn’t name it but I try to better define it for you (based on my experience).  


The process of modifying the hardware, software, and/or the physical design of an existing remote control (RC) car for your own purposes is known as “The RC Car Hack”. 


     I'm sure there are a lot of different definitions but that's my definition.  It could have been called the RC Carbot, a Bluetooth Bot, Arduino robot, etc but I guess those names never stuck for something like this.  In reality, RC Car Hack is the only name I found it under when searching which is probably how you found this. 


Tutorial Contents
     This tutorial is broken into many parts/posts as there is plenty of content to show.

  1. Introduction -> (You are here.)
  2. Description of items/stuff used
  3. Getting inside your RC Car
  4. More soon...
  5. Code used (Reference)


Before you start...  
This tutorial involves using basic C#, Bluetooth, and Arduino. If you know some java or C# and have uploaded a sketch to an Arduino before, this should be fairly straightforward.  Use or take any code listed in this tutorial.  I hope you learn as much as I did and do something fun with it. 





Comments/Questions?
I'm always wanting to improve the quality of the content here.  If you have questions, want to see a better explanation, a better picture, let me know.  Thanks - Sean



The RC Car Hack - Part 3 - Getting Inside your RC Car


The RC Car Hack - Part 3
Getting Inside Your RC Car


Summary

Identify the important parts of your RC Car and get rid of the rest.


Tutorial Contents

     This tutorial is broken into many parts/posts as there is plenty of content to show.

  1. Introduction
  2. Description of items/stuff used
  3. Getting inside your RC Car
  4. More soon...
  5. Code used (Reference)

Get inside your RC car


Gut it out – The first thing I did was open my car up.  I found the board that everything is attached to and cut it out.  (There are transistors you can salvage from the old board and use to control the motors but it’s complicated.  To save you time from my experience, I wouldn’t recommend it unless you have experience with circuits.)

Typical case– I don’t know what your RC car looks like but most RC cars are the same.  In many RC cars, the front two wheels are controlled by a servo and the back two are controlled by a motor.  In the above stated case, the front wheels control the direction of the car and the back two wheels will push or pull the car.


This case – The car used in this project does not have a servo.  It has two motors.  One motor for wheels on the left side and one motor for the wheels on the right side.    If your car is the typical case, you will need 
to look at how to control a servo, it’s not hard just google it.





Comments/Questions?
I'm always wanting to improve the quality of the content here.  If you have questions, want to see a better explanation, a better picture, let me know.  Thanks - Sean

The RC Car Hack - Part 2 - Stuff Used

The RC Car Hack - Part 2
Description of Items Used


Summary

This following is a description of all the items used in this RC Car Hack tutorial.


Tutorial Contents

     This tutorial is broken into many parts/posts as there is plenty of content to show.

  1. Introduction
  2. Description of items/stuff used
  3. Getting inside your RC Car
  4. More soon...
  5. Code used (Reference)
Stuff used

RC car
Description – There are plenty of RC Cars to be found.  The one for this project was found at Goodwill for $1.99.  For this project, we are only using toy RC cars like the ones found at Wal-mart for 20 – 40 dollars.  Unless you really want to, I do not recommend spending any money on the RC car.  Ask family or go find a garage sale.  Finding RC cars slightly damaged and/or without the remote control make them worth less (to others) but definitely not worthless (to us).

Description – This project uses the Arduino Duemilanove to control the RC car.  An Arduino is very inexpensive, versatile, and fun.  It can be reused for any project in your imagination.  If you have never used an Arduino before, it is very easy to learn and great community support.  The Arduino portion of this project relied on the Arduino community.

Description – The motor shield will make motor control very easy for us.  It goes above the arduino and is connection by stackable pins.  Although there are other ways to control motors, I would highly recommend just using this motor shield.  This motor shield is inexpensive.  It will let us control motor direction (forward/reverse), speed, and we can easily add separate power.

Description – I found this bluetooth modem to be great.  This bluetooth modem connects to the arduino and will let the arduino speak and listen to others.  As a general overview, the bluetooth modem (attached to the arduino) will connect to the bluetooth on my computer.

Description – This is what you will need to compile and upload the code that will go to the arduino.  It’s free.

Description – If you don’t have Visual Studio 2008 or 2010, go get it.  You can get the express edition of C#.  

Description – Bluetooth for your computer.  If you don’t already have one, they can be found for about $20 at many places.


Comments/Questions?
I'm always wanting to improve the quality of the content here.  If you have questions, want to see a better explanation, a better picture, let me know.  Thanks - Sean