Page Options
You are here : Blog
...and the Geek shall inherit the Earth Blog... Minimize
Dec 3

Written by: Lance Larsen
12/3/2008 11:14 AM 

CardSwipe I do a lot of development for mobile devices. 

Specifically, I needed to integrate a mag-stripe reader that fits into the CF slot of a PocketPC into a SmartDevice C# compact framework application that I am in the process of creating. 

The overall goal is to allow a credit card ( but could be any card with a mag-strip ) to be swiped directly on the mobile device and have that data integrated into the application.

Took advantage of the SerialPort class in .NET, and spun off an example application illustrating that to share with anyone else needing similar architecture.

Download: The "CardSwipe" example code ( Visual Studio 2008 )

Using a HP 2790 Pocket PC with a TokenWorks DigiSwipe CF mag strip card reader.

Ok - so highlighting the most interesting code...

Here we see how easy it is to create and initialize a SerialPort object in C#.

   1:  ///----------------------------------------------------------------------
   2:  /// <summary>
   3:  /// Initializes the swipe device.
   4:  /// </summary>
   5:  ///----------------------------------------------------------------------
   6:  private void InitializaeSwipeDevice()
   7:  {
   8:      try
   9:      {
  10:          //----------------------------------------------------------------------
  11:          // Create a new SerialPort object
  12:          //----------------------------------------------------------------------
  13:          _serialPort =
  14:              new SerialPort
  15:              {
  16:                  //----------------------------------------------------------------------
  17:                  // Set the SerialPort settings for the Card Swipe device
  18:                  //----------------------------------------------------------------------
  19:                  PortName = "COM6",
  20:                  BaudRate = 9600,
  21:                  Parity = Parity.None,
  22:                  StopBits = StopBits.One,
  23:                  Handshake = Handshake.None,
  24:                  DataBits = 8,
  25:                  ReadTimeout = 2000,
  26:                  WriteTimeout = 2000
  27:              };
  28:      }
  29:      catch (Exception exceptionGeneral)
  30:      {
  31:          CatchError(exceptionGeneral);
  32:      }
  33:  }

 

We follow that up with opening the SerialPort object, thus connecting to the device, and attaching our event delegates so we can see when data is captured from the connected port -- of course trapping any errors in the process.

   1:  ///----------------------------------------------------------------------
   2:  /// <summary>
   3:  /// Connects the swipe device.
   4:  /// </summary>
   5:  ///----------------------------------------------------------------------
   6:  private void ConnectSwipeDevice()
   7:  {
   8:      try
   9:      {
  10:          //----------------------------------------------------------------------
  11:          // Check that we do not already have a connection to the Port
  12:          //----------------------------------------------------------------------
  13:          if (!_serialPort.IsOpen)
  14:          {
  15:              //----------------------------------------------------------------------
  16:              // Open the port
  17:              //----------------------------------------------------------------------
  18:              _serialPort.Open();
  19:   
  20:              //----------------------------------------------------------------------
  21:              // Attach the events that need to be monitored
  22:              //----------------------------------------------------------------------
  23:              this._serialPort.DataReceived += _serialPort_DataReceived;
  24:              this._serialPort.ErrorReceived += _serialPort_ErrorReceived;
  25:          }
  26:      }
  27:      catch (Exception exceptionGeneral)
  28:      {
  29:          CatchError(exceptionGeneral);
  30:      }
  31:  }

 

Ok - for the compact framework ( for mobile development on PocketPCs ) - we don't have the ability to pass values to a delegate - so while functional but slightly less elegant, we store that value in a member level variable and Invoke a EventHandler to get that value into our UI textbox, as seen in the next two methods.

Note, we are using ReadExisting() method to get what's in the buffer - I started by using .ReadLine() - but would timeout when there was no NewLine character.

Also note, the DataReceived event is called multiple times as the data is being transferred into the buffer from the DigiSwipe device - but we only care about what is the final full value, so the last call to the UpdateSwipeTextboxEvent() method will overwrite previous incremental values. 

For mag-strips - in my testing, the full value always fits in the buffer ( Track 1, 2 and 3 ), but depending on your application - you may want to do more extensive testing / capturing of the incremental values.

   1:  ///----------------------------------------------------------------------
   2:  /// <summary>
   3:  /// Handles the DataReceived event of the _serialPort control.
   4:  /// </summary>
   5:  /// <param name="sender">The source of the event.</param>
   6:  /// <param name="e">The <see cref="System.IO.Ports.SerialDataReceivedEventArgs"/> instance containing the event data.</param>
   7:  ///----------------------------------------------------------------------
   8:  void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
   9:  {
  10:      try
  11:      {
  12:          //----------------------------------------------------------------------
  13:          // Read in what is currently in the buffer and append to member variable
  14:          //----------------------------------------------------------------------
  15:          _sBufferValue += _serialPort.ReadExisting();
  16:   
  17:          //----------------------------------------------------------------------
  18:          // For compact framework we need to call the event handler, which then 
  19:          //  reads the value out of the member variable.
  20:          //----------------------------------------------------------------------
  21:          textboxSwipe.Invoke(new EventHandler(UpdateSwipeTextboxEvent));
  22:      }
  23:      catch (Exception exceptionGeneral)
  24:      {
  25:          CatchError(exceptionGeneral);
  26:      }
  27:  }
  28:   
  29:  ///----------------------------------------------------------------------
  30:  /// <summary>
  31:  /// Updates the swipe textbox - needs to be wrapped into an Event as we
  32:  ///   need to call this from within another delegate - little different
  33:  ///   in Compact framework than in other window forms development
  34:  /// </summary>
  35:  /// <param name="sender">The sender.</param>
  36:  /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
  37:  ///----------------------------------------------------------------------
  38:  private void UpdateSwipeTextboxEvent(object sender, EventArgs e)
  39:  {
  40:      textboxSwipe.Text = _sBufferValue;
  41:  }

 

We finish up by of course cleaning up after our selves - clearing the buffer and closing the SerialPort object.

   1:  ///----------------------------------------------------------------------
   2:  /// <summary>
   3:  /// Disconnects the swipe device.
   4:  /// </summary>
   5:  ///----------------------------------------------------------------------
   6:  private void DisconnectSwipeDevice()
   7:  {
   8:      try
   9:      {
  10:          //----------------------------------------------------------------------
  11:          // Clears the swipe values.
  12:          //----------------------------------------------------------------------
  13:          ClearSwipeValues();
  14:   
  15:          //----------------------------------------------------------------------
  16:          // Check that we have a connection to the Port
  17:          //----------------------------------------------------------------------
  18:          if (_serialPort.IsOpen)
  19:          {
  20:              //----------------------------------------------------------------------
  21:              // Clean up the buffer and close the port
  22:              //----------------------------------------------------------------------
  23:              _serialPort.DiscardInBuffer();
  24:              _serialPort.DiscardOutBuffer();
  25:              _serialPort.Close();
  26:          }
  27:      }
  28:      catch (Exception exceptionGeneral)
  29:      {
  30:          CatchError(exceptionGeneral);
  31:      }
  32:  }

 

Not necessarily obvious before seeing the code on how to do this, but I hope you'll find that the above is pretty clean and elegant once you've looked at it further.

As always, I welcome comments and improvements to the code - please send any improvements you make and I'll incorporate them into the CardSwipe example.

Regards...

...Lance

Tags:

Your name:
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
Enter the code shown above in the box below
Add Comment   Cancel 
Categories Minimize
Search Blog Minimize
Publish Dates Minimize

Copyright 2008 by Lance Larsen ( A.I. Labs )
Privacy StatementTerms Of Use