EMB06_2D00_HOL-POS-for-.NET-Scanner-Lab

advertisement

EMB06-HOL: Using Microsoft Point of Service for .NET

EMB06-HOL: Develop POS Applications

Using Microsoft Point of Service for .NET

Page 1 of 21

Abstract

Microsoft Point of Service (POS) for .NET provides simple and consistent interfaces for controlling and managing POS peripherals and is integrated with Windows Embedded for Point of Service (WEPOS).

Microsoft Point of Service for .NET addresses the needs of Independent Software Vendors (ISV) who develop software that interfaces with POS peripherals and of Independent Hardware Vendors (IHV) who want to provide powerful capabilities to ISVs with minimal investment. Regardless of if you are an ISV or

IHV, Microsoft Point of Service for .NET can help lower the cost of your product development while providing the most advanced capabilities. Microsoft does the heavy lifting for you so you can focus on what you do best! This session demonstrates how to create applications and service objects leveraging

POS for NET.

Objectives

These are the overall learning objectives of this lab:

Create an application that references Microsoft POS for .NET.

Use POS for .NET in an application to determine available POS peripherals

Use POS for .NET in an application to interface with a POS peripheral

Use POS for .NET to respond to Plug-n-Play events from POS peripherals

Write a POS for .NET Service Object

NOTE: The exercise within the lab that cover the Plug-n-Play capabilities and the writing of a .NET Service

Object require a physical device to complete the exercise. If you would like to complete these portions of the lab, please make sure you are at one of the stations with an available barcode scanner. The other exercises can be completed at any station using a simulated scanner included with Microsoft Point of

Service for .NET.

Scenarios

An ISV needs her application to interface with a barcode or RFID scanner in order to keep track of inventory.

An ISV needs his application to interface with multiple POS periperhals, including RFID, MSR,

Line Display, Biometric, PINPad, Receipt Printer, Cash drawer, etc.

An ISV develops a .NET application and would like a modern API for interfacing with POS periperhals while still supporting legacy equipment.

EMB06-HOL: Using Microsoft Point of Service for .NET Page 2 of 21

An IHV would like to develop a .NET Service Object for his product while keeping development cost low.

Prerequisites

This lab assumes familiarity with the following tools and technology:

Microsoft Visual Studio

Microsoft C#

Familiar with creating basic UI forms from within Visual Studio

The Microsoft .NET framework

Duration

This lab is broken up into multiple exercises each building upon that work completed in previous exercises. While you are encouraged to complete all of the exercises, it is not necessary to gain the fundamental understanding of how to use POS for .NET within an application. Completion of the first two exercises should take approximately 40 minutes and can be done at any station. Completion of all exercise in the lab should take approximately 60 minutes and requires that you perform the lab at one of the stations setup with a physical barcode scanner.

NOTE: If you wish to perform all of the exercises in this lab, please use a station with a physical scanner available.

Technology Overview

Microsoft POS for .NET provides .NET applications with simple and consistent interfaces for communicating with well over thirty Point of Service (POS) peripheral devices. The list of devices includes barcode scanners, magnetic stripe readers (MSR), Line Displays, PIN Pads, RFID readers,

Biometric readers, receipt printers, cash drawers, and many others. POS for .NET is Microsoft’s implementation of the industry’s Unified Point of Service (UPOS) standard. POS for .NET makes it easy for both Independent Software Vendors and Independent Hardware Vendors to support a broad range of peripherals using Microsoft .NET. In addition, Microsoft POS for .NET provides many advantages to the ISV and end customer above and beyond Unified POS.

For More Information

Microsoft Point of Service for .NET is available as a free download from Microsoft at: http://www.microsoft.com/downloads/details.aspx?FamilyID=eaae202a-0fcc-406a-8fde-

35713d7841ca&displaylang=en

EMB06-HOL: Using Microsoft Point of Service for .NET Page 3 of 21

EMB06-HOL: Using Microsoft Point of Service for .NET Page 4 of 21

Exercise 1

POS Project Creation and UI Layout

In this exercise you will create a new POS application that will contain the required project references for applications using POS for .NET. In addition this exercise will create the basic UI layout of the POS application which will be used in all subsequent exercises in this lab.

Overview

Create a new project in Visual Studio

Add required assembly references

Layout the basic UI for the POS application

Instructions

When you are done with this exercise, you should have a view that looks something like the following:

Figure 1 – Form UI Layout

1.

Open Microsoft Visual C# 2008 Express Edition (or Visual Studio 2008 if available) .

2.

Create a new project file: a.

Select File->New->Project b.

Select “Windows Forms Application” project under “Visual C# - Windows” c.

Name the project “ScannerSampleLab1” and click “OK”

EMB06-HOL: Using Microsoft Point of Service for .NET Page 5 of 21

3.

The Microsoft.PointOfService assembly defines programming interface contracts between POS applications and service objects used to interface and control the many devices supported by

POS for .NET. Add a reference to this assembly to the project: a.

Right-click on “References” in the solution explorer, and click “Add Reference…” b.

In the dialog box that pops up, select the “Browse” tab c.

Select the reference “Microsoft.PointOfService.dll” file by navigating to the folder

“%ProgramFiles%\Microsoft Point Of Service\SDK” where it is contained d.

Click “OK” to add the reference.

4.

Using the property window, change the following properties for the main form as indicated: a.

Name: ScannerLab1 b.

StartPosition: CenterScreen c.

Text: Scanner Lab 1 d.

Feel free to adjust the size of the form as desired any time during the exercise

5.

While in the form designer view, use the toolbox common controls to add labels to the form with the following text values (see figure 1 for the general layout of the form): a.

Scan Data Label b.

Scan Data Type c.

Event History d.

Scanners

6.

Add a Text Box for the “Scan Data Label” label and set the properties as follows: a.

Name: txtScanDataLabel b.

ReadOnly: True. c.

Adjust the size of the textbox as desired.

7.

Add a Text Box for the “Scan Data Type” label and set the properties as follows: a.

Name: txtScanDataType b.

ReadOnly: True. c.

Adjust the size of the textbox as desired.

8.

Add a TextBox for the “Event History” label and set the properties as follows: a.

Name: txtEventHistory b.

ReadOnly: True. c.

Multiline: True d.

ScrollBars: Vertical e.

Adjust the size of the textbox as desired.

9.

Add a ListBox for the “Scanners” label and set the properties as follows: a.

Name: lstDevices b.

Adjust the size and position as desired.

10.

Add a Binding source (available under Toolbox->Data) to the form and set the properties as follow: a.

Name: scannerBindingSource

11.

Add a button to the form with the following properties: a.

Name: btnActivateDevice b.

Text: Activate

EMB06-HOL: Using Microsoft Point of Service for .NET Page 6 of 21 c.

Adjust the size of the button as desired.

12.

Create a “Load” event handler for the main form. Don’t worry about the code to go in this method for now, that will be done later on.

13.

Create a “Click” event handler for the “Activate” button. Again, don’t worry about the code for this method as it will be added later on.

Verification

Build and run the project to verify that all of the steps were completed satisfactorily and that the UI

looks similar to Figure 1 – Form UI Layout:

1.

From Visual Studio Select Debug->Start Debugging or Press the ‘F5’ key to start the debugger

2.

View the UI layout

3.

Press the Close (X) button when done.

EMB06-HOL: Using Microsoft Point of Service for .NET Page 7 of 21

Exercise 2

Developing a POS Application

This exercise will start to add POS functionality to the application created in the previous exercise. In this exercise you will learn how easy it is to use POS for .NET in your applications, thus allowing you to easily interface with POS peripherals, such as a barcode scanner. You will be introduced to the ‘POSExplorer’ class which will allow you to explore the system for available

POS peripherals. You will enhance the POS application to discover all available scanners and to respond to events from a barcode scanner (or a simulated barcode scanner). Finally, you will enhance the POS application to read and display data from the barcode scanner.

Overview

Add required using statements

Introduction to ‘POSExplorer’

Use ‘POSExplorer’ to discover all available barcode scanners

Use ‘POSExplorer’ to interface with one of the available barcode scanner

Instructions

1.

Open the form1.cs file to view the code-behind the designer view. This can be done by rightclicking on the form and selecting “View Code.”

2.

Add a few using statements to make life a bit easier: using Microsoft.PointOfService; using System.Collections;

Note: Microsoft.PointOfService is the main assembly reference for POS for .NET.

3.

POS for .NET provides the ‘POSExplorer’ class. This class can be used to perform queries on the system of available POS device peripherals, to instantiate service objects which act as device drivers for the peripherals, and to receive notification of Plug-n-Play (PnP) events for POS devices. The ‘Scanner’ class represents a service object for barcode scanner peripherals. The instance of the ‘Scanner’ is device specific and is provided by the ‘POSExplorer’. Add member fields to the form for the explorer, the active scanner, and a running list of available scanners: private PosExplorer explorer; private ArrayList scannerList; private Scanner activeScanner;

4.

Before hooking up the events, a few utility methods are in order. The first utility method will be used to log activities and display them in the UI as they occur. The ‘txtEventHistory’ control will be used to maintain and display this log. So the first method will add the new event to the top of the log while maintaining history of past events. Add an ‘UpdateEventHistory’ method to maintain this log: private void UpdateEventHistory( string newEvent)

{

EMB06-HOL: Using Microsoft Point of Service for .NET

} txtEventHistory.Text = newEvent +

System.

Environment .NewLine + txtEventHistory.Text;

Page 8 of 21

5.

The next utility method will be used to deactivate the active scanner (if any). Because calls to the service objects exposed by various devices may result in a ‘PosControlException’, these will be handled by simply logging the exception if it is raised. After the active scanner has been closed code should be added to set the ‘activeScanner’ variable to null to indicate that there are is no longer an active scanner: private void DeactivateScanner()

{ if

{

(activeScanner != null )

// We have an active scanner, lets log that we are

// about to close it.

UpdateEventHistory( "Deactivate Current Scanner" ); try

{

}

// Close the active scanner activeScanner.Close(); catch ( PosControlException )

{

}

}

// Log any error that happens

UpdateEventHistory( "Close Failed" ); finally

{ // Don't forget to set activeScanner to null to

// indicate that we no longer have an active

// scanner configured. activeScanner = null ;

}

}

6.

‘DeviceInfo’ class is used by POS for .NET to identify and represent information about an available device. This class can be provided to the ‘PosExplorer’ in order to instantiate a service object for the device identified by the ‘DeviceInfo’ class. A utility method is needed to activate a scanner identified by ‘DeviceInfo’. This method will first verify that the ‘DeviceInfo’ provided identifies a device other than the one that is already in use. It will then deactivate the current scanner, create a new instance member for the active scanner, open the scanner, claim the scanner for exclusive use by the application, enable the device, subscribe to events from the device, and enable data events for the device. If any exception occurs this will be logged and the active scanner will be set to none. All of this can be done as follows: private void ActivateScanner( DeviceInfo selectedScanner)

{

// Verifify that the selectedScanner is not null

// and that it is not the same scanner already selected if (selectedScanner != null &&

!selectedScanner.IsDeviceInfoOf(activeScanner))

EMB06-HOL: Using Microsoft Point of Service for .NET

}

{

}

// Configure the new scanner

DeactivateScanner();

Page 9 of 21

// Activate the new scanner

UpdateEventHistory( string .Format( "Activate Scanner: {0}" , selectedScanner.ServiceObjectName)); try

{ activeScanner =

( Scanner )explorer.CreateInstance(selectedScanner); activeScanner.Open(); activeScanner.Claim(1000); activeScanner.DeviceEnabled = true ; activeScanner.DataEvent +=

new DataEventHandler (activeScanner_DataEvent); activeScanner.ErrorEvent += new

DeviceErrorEventHandler ( activeScanner_ErrorEvent); activeScanner.DecodeData =

} catch ( PosControlException ) true ; activeScanner.DataEventEnabled = true ;

{ // Log error and set the active scanner to none

UpdateEventHistory( string .Format( "Activation Failed: {0}" ,

} selectedScanner.ServiceObjectName)); activeScanner = null ;

7.

It is now time to create an instance of a ‘POSExplorer’. The explorer will be used to find the list of available devices and instantiate service objects (SO) for the devices as needed. It can also be used to provide PnP events as POS devices that are added and removed from the system.

Events from devices may be generated in a thread asynchronously outside of the UI. However, you want all of the events to be processed within the UI thread. Luckily POS explore makes this easy, simply identify the form in the constructor and the ‘POSExplorer’ will ensure that all events are marshaled into the UI thread. Add the code to create the instance inside the Form’s load event as follows: explorer = new PosExplorer ( this );

8.

Within the Forms load event, use the explorer to create a list of ‘DeviceInfo’ for all available POS scanners. This list will be saved in an ArrayList and bound to the data source for the ‘lstDevices’ control via the binding source that was created earlier. Finally, the ‘lstDevices’ will set the

DisplayMember to indicate that only the service object name should be displayed in the UI: scannerList = new ArrayList (explorer.GetDevices( "Scanner" )); scannerBindingSource.DataSource = scannerList;

EMB06-HOL: Using Microsoft Point of Service for .NET Page 10 of 21 lstDevices.DataSource = scannerBindingSource; lstDevices.DisplayMember = "ServiceObjectName" ;

9.

Add code to the bottom of the forms load event to activate the first available scanner (if any) identified by the ‘lstDevices’ control. Remember that the ‘lsDevices’ is bound to a list of

‘DeviceInfo’ objects contained in the scannerList. The code is as follows: if (lstDevices.SelectedItem != null )

{

ActivateScanner(( DeviceInfo )lstDevices.SelectedItem);

}

10.

Modify the button click code so that it will activate the selected scanner using the same code in the previous step: if (lstDevices.SelectedItem != null )

{

ActivateScanner(( DeviceInfo )lstDevices.SelectedItem);

}

11.

Upon receiving a scan event from the barcode scanner, the following actions are desired: log the data event, update the label and data type information with the data provided by the scanner, re-enable the data event for any subsequent scans, and log any exceptions that may have occurred. In the event handler, one is faced with a choice of using the sender object to identify the scanner, or directly using the active scanner. In order to support multiple scanners in the same event handler, the later choice would be the desired approach. For simplicity, however, go ahead and use the ‘activeScanner’ directly: void activeScanner_DataEvent( object sender, DataEventArgs e)

{

UpdateEventHistory( "Data Event" );

ASCIIEncoding encoder = new ASCIIEncoding (); try

{

{

// Display the ASCII encoded label text txtScanDataLabel.Text = encoder.GetString(activeScanner.ScanDataLabel);

// Display the encoding type txtScanDataType.Text = activeScanner.ScanDataType.ToString();

// re-enable the data event for subsequent scans activeScanner.DataEventEnabled =

} catch ( PosControlException )

// Log any errors

UpdateEventHistory( true ;

"DataEvent Operation Failed" );

EMB06-HOL: Using Microsoft Point of Service for .NET

}

}

Page 11 of 21

12.

In the event that a an error event is received from the scanner, simply log the occurrence and re-enable the scanner for future events: void activeScanner_ErrorEvent( object sender, DeviceErrorEventArgs e)

{

UpdateEventHistory( "Error Event" );

} try

{

}

// re-enable the data event for subsequent scans activeScanner.DataEventEnabled = true ; catch ( PosControlException )

{ // Log any errors

UpdateEventHistory( "ErrorEvent Operation Failed" );

}

Verification

Now it is time to verify the application. POS for .NET includes a set of “simulated” devices including a

“Microsoft Scanner Simulated” that can be used to simulate a physical scanner. This will be used here to verify the application. Later on, you will have the opportunity to develop your own scanner service object that will interface with a physical scanner (normally, only IHV would need to write a managed service object, but they are simple enough even with relatively little hardware experience as POS for

.NET does much of the heavy lifting of implementing in accordance with the Unified POS standard).

1.

Compile and run the Scanner Lab 1 application.

2.

The “Microsoft Scanner Simulator” should be selected by default, if not, select this scanner and press the “Activate” button.

3.

A window is displayed titled, “Microsoft Scanner Simulator” that is used to simulate a physical scanner. Go ahead and try sending different scan events to your application while entering different barcode values.

EMB06-HOL: Using Microsoft Point of Service for .NET Page 12 of 21

Exercise 3

Developing a .NET Service Object

This exercise demonstrates how to create a .NET Service Object. Microsoft POS for .NET makes it easy for anybody who would like to develop a .NET Service Object. Developers of .NET

Service Objects may choose to use of the basic classes for their service objects. Microsoft provides a basic class for all UnifiedPOS device categories (e.g., scanner, printer, line display, etc). As of the v1.12 release there are thirty-six (36) basic classes provided. In order to simplify

.NET Service Object development even further, Microsoft also provides base classes for many device categories that implement all of the standard UnifiedPOS functionality, leaving only the device specific portions to be completed by the developer. As of v1.12, there are base classes available for the following device categories:

Cash Drawer

Check Scanner

Line Display

Magnetic Strip Reader (MSR)

PIN Pad

POS Keyboard

POS Printer

Barcode Scanner

RFID Scanner

In this exercise you will create a .NET Service Object for a barcode scanner using the base class within POS for .NET.

Overview

Create a new project for the service object

Add the required references

Add the required attributes so that the ‘POSExplorer’ can recognize your .NET Service Object

Implement your class derived from the ‘Scanner’ base class.

Additional Requirements

NOTE: This exercise requires the use of a physical barcode scanner. Please make sure that you are at a station with a physical scanner available before attempting to proceed.

Instructions

1.

This lab exercise depends on the application created in the earlier steps. Create a new project

‘DemoScanner’ in the same solution as the application: a.

Select the solution b.

Right-click the solution and select “Add” and “New Project…” c.

For the project, select the “Class Library” under the “Visual C# - Windows” project type. d.

Name the project “DemoScanner” and click “OK”

2.

Add a reference to the Microsoft.PointOfService assembly: a.

Right-click on “References” in the solution explorer, and click “Add Reference…”

EMB06-HOL: Using Microsoft Point of Service for .NET Page 13 of 21 b.

In the dialog box that pops up, select the “Browse” tab c.

Select the reference “Microsoft.PointOfService.dll” file by navigating to the folder

“%ProgramFiles%\Microsoft Point Of Service\SDK” where it is contained. d.

Click “OK” to add the reference.

3.

The Microsoft.PointOfService.ControlBase assembly contains the basic class implementation for all supported device types. In addition it provides base classes for some of the more common devices as well as utility code for .NET Service Object. Add a reference to the

Microsoft.PointOfService.ControlBase assembly to the project: a.

Right-click on “References” in the solution explorer, and click “Add Reference…” b.

In the dialog box that pops up, select the “Browse” tab c.

Select the reference “Microsoft.PointOfService.ControlBase.dll” file by navigating to the folder “%ProgramFiles%\Microsoft Point Of Service\SDK” where it is contained. d.

Click “OK” to add the reference.

4.

The ‘POSExplorer’ requires that Service Object assemblies contain the PosAssembly global attribute in order to recognize assemblies that contain service objects. Add this attribute to the

AssemblyInfo file: a.

Open the AssemblyInfo.cs file under properties b.

Add a using statement at the top of the file for “Microsoft.PointOfService” c.

Add an assembly level attribute for PosAssembly use “My Company Name” as the manufacturerName. It should look something like this:

[ assembly : PosAssembly ( "My Company Name" )]

5.

Because the service object will require some USB operations, a class is needed to handle basic

USB I/O. Luckily, the SDK includes a sample class ‘HidReader’ that does just what is needed.

Add the ‘HidReader’ class to the project: a.

Right-click on the “DemoScanner” project and select “Add” followed by “Existing Item…” b.

The file to be added, “HidReader.cs” is under the “Example Service Objects” folder at the following location: %ProgramFiles%\Microsoft Point Of Service\SDK\

Samples\Example Service Objects\Source” Select the file and then press “Add” (NOTE:

Do not choose “Add as Link” as you want a local copy of the file).

6.

Use the solution explorer to rename the projects default class from “Class1.cs” to

“MyScanner.cs”

7.

In the “MyScanner.cs” source file, add using statements for the various namespaces that provide required functionality. This includes the Point Of Service namespace, the Base Service

Object namespace that defines a base class for scanners, and the Example Service Object namespace that defines the HidReader class that will be used for USB I/O operations. At the top of the MyScanner file, add using statements for all of the following: a.

Microsoft.PointOfService b.

Microsoft.PointOfService.BaseServiceObjects c.

Microsoft.PontOfService.ExampleServiceOjects

8.

Make “MyScanner” a public derived class of “ScannerBase”. This base class provides almost all scanner UPOS functionality – all you need to do is add a little bit of device specific code.

EMB06-HOL: Using Microsoft Point of Service for .NET Page 14 of 21

9.

Right-click on the ScannerBase class and select “Implement Abstract Class” to have Visual Studio provide the template code for the methods (CheckHealth, CheckHealthText, and DirectIO) that require an override.

10.

The ‘POSExplorer’ needs a way to identify the class that implements a scanner and to provide a user friendly name for the service object. This can be accomplished by adding the

“ServiceObject” attribute to the class. Add this attribute to the ‘MyScanner’ class with the following properties: a.

Type = “Scanner” b.

Name = “DemoScanner” c.

Description = “Add some description here” d.

uposVersionMajor = 1 e.

uposVersionMinor = 12

11.

The scanner that is going to be supported is of type USB HID. For USB HID devices each manufacture has a unique vendor ID (VID) and product ID (PID) that identifies the peripheral.

Add the POS for .NET attribute “HardwareId” to your scanner class in order to allow the device to automatically be detected and associated with the service object. If you are at a station with a Symbol LS2208 scanner, you should use the following value:

[ HardwareId ( @"HID\VID_05E0&PID_1300" )] // Symbol LS2208

Otherwise, locate the HID string printed on your local scanner and add the HardwareId attribute to the “MyScanner” class.

NOTE: If you cannot locate the HID printed on your scanner, then you can use the Device

Manager MMC to determine this information: a.

Make sure you plug-in the scanner b.

Under Vista, select Start->Run->devmgmt.msc to launch the device manager. c.

Expand the “Human Interface Devices” tree d.

Double-click to open the “HID-compliant device” e.

Select the “Details” tab f.

Select “Hardware Ids” property. This will display all HID devices connected to the system.

12.

At this point, you should have code that looks something like this (NOTE: that the HardwareId

may have a different value depending on the scanner you are using): using System; using System.Collections.Generic; using System.Text; using Microsoft.PointOfService; using Microsoft.PointOfService.BaseServiceObjects; using Microsoft.PointOfService.ExampleServiceObjects; namespace DemoScanner

{

[ ServiceObject ( "Scanner" , "DemoScanner" ,

EMB06-HOL: Using Microsoft Point of Service for .NET Page 15 of 21

{

"Add some description here" , 1, 12)]

// Device Specific HID VID/PID:

[ HardwareId ( @"HID\VID_05E0&PID_1300" )] // Symbol LS2208 public class MyScanner : ScannerBase public override string CheckHealth( HealthCheckLevel level)

{

} throw new NotImplementedException (); public override string CheckHealthText

{ get { throw new NotImplementedException (); }

}

}

} public override DirectIOData DirectIO( int command, int data, object obj)

{

} throw new NotImplementedException ();

13.

Add an member variable to the ‘MyScanner’ class for a ‘HidReader’: private HidReader reader;

14.

Define two device specific constants that indicate where within the packet received by the scanner the data length and start data may be found: private const int DataLengthIndex = 1; private const int DataStartIndex = 5;

15.

The next step will be to override the “Open” method to create an instance of reader. This instance will use the base class to identify the device name and path. In addition, a callback method “OnScan” will be provided so that the class will get notified of all packets received from the scanner: public override void Open()

{ base .Open();

} if (reader == null )

{ reader = new HidReader (DeviceName, DevicePath, OnScan);

}

16.

Create the OnScan method identified above to handle the packets as they are received. If the data is not null and the length is the minimum size required, the base class will be asked to to continue processing via a call to “GoodScan”; otherwise, a call to “FailedScan” to tell the base class that the scan was invalid:

EMB06-HOL: Using Microsoft Point of Service for .NET void OnScan( byte [] data)

{ if

{

(data != null && data.Length >= DataStartIndex)

GoodScan(data);

} else

{

}

FailedScan();

}

Page 16 of 21

17.

Override the DeviceEnabled property, and when the property’s value is being changed, use the reader to Open or Close the device. For the getter, just return the base values:

} public override bool DeviceEnabled

{ get

{ return base .DeviceEnabled;

} set

{

} if ( value != base .DeviceEnabled)

{

}

// Value is being changed

// change the value in the base class base .DeviceEnabled = value ; if ( value )

{ // The device is enabled - start reading reader.OpenDevice();

} else

{

}

// The device is disabled - stop reading reader.CloseDevice();

18.

The scanner data comes in a packet that must be decoded by the service object in order to extrapolate the label data from other metadata. In order to decode the scanner label from the data, override the DecodeScanDataLabel method. Assuming that the scanner specifics the data length in the byte array at the position “DataLengthIndex” and that the data bytes start at

“DataStartIndex” then the following method would extract the label data and return the results: protected override byte [] DecodeScanDataLabel( byte [] scanData)

{

// Device dependent logic for decoding scanned data label

// Production code would include additional validations int scanDataLength = scanData[DataLengthIndex]; byte [] decodeData = new byte [scanDataLength];

EMB06-HOL: Using Microsoft Point of Service for .NET

} for ( int i = 0; i < scanDataLength; i++)

{ decodeData[i] = scanData[DataStartIndex + i];

} return decodeData;

Page 17 of 21

19.

One could also override the DecodeScanDataType method in order to identify different barcode symbologies. Since devices are so divergent on how this is done, this step will be skipped. The default handling provided by the base class is sufficient.

20.

Finally, the implementation of CheckHealth(), DirectIO(), and CheckHealthText will be left for another day.

Verification

This portion of the lab will show how to register a service object (SO) for discovery by POS for .NET and will then verify that the SO is working properly.

1.

Plug in the Scanner at your station if it is not already connected to the computers USB port.

2.

Compile your service object and fix any issues that you encounter

3.

In order for a managed service object to be discovered, it must be contained within the search path of POS for .NET. One may either copy the service object to an existing search path, or one can modify the search path to include a new location. Normally, this is something that would be done by the service objects installer. For now, just go ahead and create a new sting key to specify the location where the DemoScanner DLL is being dropped by visual studio: a.

From the start menu, select Run and type regedit. Click continue if presented with a security dialog. b.

Open the registry key

HKEY_LOCAL_MACHINE\SOFTWARE\POSfor.NET\ControlAssemblies a.

Add/set the string value “DemoScanner” to the bin\debug folder location for your project.

4.

Now using the POS application created previously, you should be able to see your scanner in the list, and select the scanner. Go ahead and run the POS application. The application should respond to scan events when the scanner is active. Try scanning some barcodes.

5.

If your service object does not show up on the list, check the following: a.

The Service Object assembly contains an assembly level attribute ‘PosAssembly’ b.

The MyScanner class is public and contains the following attributes: i.

Service Object ii.

HardwareId c.

The hardware ID string exactly matches that used by your scanner d.

The registry key “ControlAssemblies” contains a string entry identifying the location of your assembly

EMB06-HOL: Using Microsoft Point of Service for .NET Page 18 of 21

Exercise 4

Enhance POS Applications with Plug-n-Play

This exercise will add Plug-n-Play capabilities to the POS application created previously. In this exercise you will learn how to use the ‘POSExplorer’ to subscribe to Plug-n-Play events from

POS peripherals. You will enhance the application to automatically respond to these events, by removing the scanner from the available list, or by automatically selecting the scanner as it is plugged in.

Overview

Use ‘POSExplorer’ to add event handler for device added

Use ‘POSExplorer’ to add event handler for device removed

Add code to determine matching scanners

Use the service object previously developed to verify PnP events

Additional Requirements

NOTE: This exercise requires the use of a physical barcode scanner. Please make sure that you are at a station with a physical scanner available before attempting to proceed.

Instructions

1.

In the main form of the POS application, create a utility function in the application to help search an ArrayList for items with identical ‘DeviceInfo’ details. The routine should return the index of the found item, or -1 if no match is found: private int FindMatchingDeviceInfo(

ArrayList deviceList,

DeviceInfo target)

{ for ( int index = 0; index < deviceList.Count; index++)

{

DeviceInfo if

tmp = ( DeviceInfo )deviceList[index];

(tmp.ToString().Equals(target.ToString(),

StringComparison .OrdinalIgnoreCase))

{

}

} return -1; return index;

}

13.

In order for the application to respond to Plug-n-Play (PnP) events for POS devices all that is required is to subscribe to the Device Added and Removed Events exposed by the explorer.

These events will be called automatically by POS for .NET as devices are added or removed.

Modify the form loads method to include subscription to these events the binding code and before the Activation code: explorer.DeviceAddedEvent += new DeviceChangedEventHandler (explorer_DeviceAddedEvent);

EMB06-HOL: Using Microsoft Point of Service for .NET Page 19 of 21 explorer.DeviceRemovedEvent += new DeviceChangedEventHandler (explorer_DeviceRemovedEvent);

2.

In the device Add event, call the UpdateEventHistory() method to indicate that the event was called. If the device type identified by the event is a “Scanner” then add the scanner to the list, reset the bindings to update the UI, update the listDevices control to select the device, and then activate the scanner: void explorer_DeviceAddedEvent( object sender, DeviceChangedEventArgs e)

{

UpdateEventHistory( string .Format( "Device Added {0} : {1}" , e.Device.Type.ToString(), e.Device.ServiceObjectName)); if (e.Device.Type == "Scanner" )

{ scannerList.Add(e.Device); scannerBindingSource.ResetBindings( lstDevices.SelectedIndex = FindMatchingDeviceInfo( scannerList, e.Device); false );

}

ActivateScanner(e.Device);

}

3.

In the Device Remove event handler, we want to determine if the scanner is the active scanner, and if so, to deactivate it, then remove the scanner from the running list of scanners and refresh the UI by resetting the bindings. Finally, if the removed scanner was the active scanner, clear the selected item in the ‘lstDevices’ control: void explorer_DeviceRemovedEvent( object sender,

DeviceChangedEventArgs e)

{

UpdateEventHistory( if

{ string

(e.Device.Type == bool if

{

}

.Format(

"Scanner" )

clearSelectedItem =

"Device Removed {0} : {1}" false ;

(e.Device.IsDeviceInfoOf(activeScanner))

// The active scanner has been removed

DeactivateScanner(); clearSelectedItem = true ; int matchIndex =

FindMatchingDeviceInfo(scannerList, e.Device); if (matchIndex >= 0)

{ scannerList.RemoveAt(matchIndex); scannerBindingSource.ResetBindings( false );

}

, e.Device.Type.ToString(), e.Device.ServiceObjectName)); if (clearSelectedItem)

EMB06-HOL: Using Microsoft Point of Service for .NET Page 20 of 21

}

}

{

} lstDevices.ClearSelected();

Verification

Verify that the application responds to plug-n-play events as the scanner is unplugged and plugged into the system.

1.

Plug in the Scanner at your station if it is not already connected to the computers USB port.

2.

Run the application using the debugger

3.

Make the DemoScanner Active by selecting it and pressing the “Activate” button

4.

Scan some barcodes

5.

Unplug the scanner and verify that the Event History indicates that it is unplugged

6.

Select the “Microsoft Scanner Simulator” and press “Activate”

7.

Verify that events are received from the simulated scanner

8.

Plug-in the scanner and verify that the: a.

simulated scanner is dismissed b.

event history indicates that there is a new active scanner c.

Application receives barcode scan events as you use the scanner to scan barcodes

Congratulations

You have completed all exercises of the lab. Please visit the Microsoft Windows Embedded both to learn more about Microsoft POS for .NET and Windows Embedded for POS.

EMB06-HOL: Using Microsoft Point of Service for .NET Page 21 of 21

Appendix A

Lab Build Guide

The following high level setup steps can be used to reproduce this labs build environment.

Configure a development machine with Microsoft POS for .NET:

1.

Install Microsoft Windows Vista and all updates (WePOS or Microsoft Windows XP may also be used)

2.

Install Visual Studio 2008 or Microsoft Visual C# 2008 Express Edition a.

An express version may be used, and is available for download at: http://www.microsoft.com/express/vcsharp/

3.

Install Microsoft Point of Service for .NET: a.

A free download is available at: http://www.microsoft.com/downloads/details.aspx?FamilyID=eaae202a-0fcc-406a-

8fde-35713d7841ca&displaylang=en b.

Run the installer and choose the “Complete” option in order to including the SDK. c.

Verify that the string value “Simulators” is defined in the registry key: i.

HKEY_LOCAL_MACHINE\SOFTWARE\POSfor.NET\ControlAssemblies ii.

With the value: C:\Program Files\Microsoft Point Of

Service\SDK\Samples\Simulator Service Objects\ d.

Verify that the string value “ExampleSOs” is defined in the registry key: i.

HKEY_LOCAL_MACHINE\SOFTWARE\POSfor.NET\ControlAssemblies ii.

With the value: C:\Program Files\Microsoft Point Of iii.

Service\SDK\Samples\Example Service Objects\

4.

Allow user to be connected to machine as admin so that they can change the registry keys as required.

Download