الفريق العربي للبرمجةأرشيف المنتديات · 2000 – 2023
نسخة أرشيفية للقراءة فقط — التسجيل والمشاركة مغلقان، والمحتوى محفوظ كما كان.

اريد عمل برنامج حضور وانصراف بلبصمة وجبت جهاز مايكروسوفت للبصمة

بدأه hamada252_eg في 13 أغسطس 2008 · 15 رد · 7,679 مشاهدة · في Microsoft Visual C#.NET
مشاركة: واتساب X فيسبوك تيليجرام
#1 صاحب الموضوع

السلام عليكم ورحمة الله وبركاتة

اريد عمل برنامج حضور وانصراف بلبصمة وجبت جهاز مايكروسوفت للبصمة

ارجو المساعدة

#2

هل ممكن أن ترفق معلومات أكثر عن الجهاز حتى أستطيع أن أبحث عنه

Sr. Software Development Engineer
Hulu, LLC
My Blogs

#3

السلام عليكم ورحمة الله وبركاتة

اشكرك يا اخى على اهتمامك

كل المعلومات عن الجهاز موجودة فى هذا الرابط

http://www.microsoft.com/hardware/mouseand...nt/default.mspx

#4

السلام عليكم ،

هل سؤالك بخصوص المشروع نفسه

ام كيف يتم التعامل مع جهاز البصمة؟

هناك كتاب به فصل يتكلم عن مشروع بأستخدام هذا الجهاز،

سأحاول رفع الكتاب.

لدي سؤال : من أين جلبت هذا الجهاز؟ او بالأصح ،، أين تعيش؟

Incorporating Fingerprint
Recognition into Your
.NET Application
Biometric recognition is one of the most reliable ways to confirm the identity of an individual.
And by now, most people should be familiar with the Microsoft Fingerprint Reader (http://
www.microsoft.com/hardware/mouseandkeyboard/productdetails.aspx?pid=036; see also
Figure 3-1).
Figure 3-1. The Microsoft Fingerprint Reader
Using the Microsoft Fingerprint Reader, you can now log in to your computer by placing
your finger on the reader. You can also use the application provided by the Fingerprint Reader
to save your user IDs and passwords for websites that require them for authentication. You
can then use your fingerprint as a key to retrieve the user IDs and passwords for logging into
these sites securely. The Microsoft Fingerprint Reader removes the hassle of remembering
different passwords for different sites.
123
C H A P T E R 3
■ ■ ■
However, that’s all you can do with the Fingerprint Reader. Microsoft does not provide a
SDK to allow developers to incorporate the Fingerprint Reader into their applications. For
this, you have to rely on third-party solution providers. Fortunately, one such provider exists:
Griaule (http://griaule.com/).
Griaule provides the GrFinger Fingerprint SDK (http://griaule.com/page/en-us/
grfinger_sdk), a fingerprint recognition SDK that supports existing fingerprint readers; it
works with Microsoft Fingerprint Reader, Digital Persona U.are.U 4000, SecuGen Hamster
FDU02, Geomok (Testech) Bio-I, and Crossmatch USB Fingerprint Reader.
In this chapter, I will show you how you can use the GrFinger Fingerprint SDK to integrate
the Microsoft Fingerprint Reader into your .NET 2.0 Windows applications. In particular, you
will build a visitor identification system whereby users visiting your office can register at the
reception desk (see Figure 3-2). Once a user is registered, the next time the user visits the
office, he can simply scan his fingerprint, and the system will register his visit. Schools can
also adapt this application for attendance-taking purposes, such as in big lecture theaters
where attendance must be taken rapidly and efficiently.
Figure 3-2. The visitor identification system application you will build in this chapter
Using the GrFinger SDK
Two editions of the GrFinger Fingerprint SDK exist: light and full (http://www.griaule.com/
page/en-us/grfinger_sdk). Consult Griaule’s website for full pricing information for each edition.
For this chapter’s examples, I have used the full edition of the GrFinger SDK 4.2. You can
apply for a free 90-day trial license to test the SDK (http://www.griaule.com/page/en-us/
downloads).
124 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
Creating the Application
Once you have the GrFinger SDK installed, you are ready to create the application. Using
Visual Studio 2005, create a new Windows application (select either Visual Basic or C#), and
name it Fingerprintreader.
First, you need to add the GrFingerXCtrl control (an ActiveX control representing the
GrFinger component) to your Toolbox. Right-click the Toolbox, and select Add/Remove Items.
On the COM Components tab, check the GrFingerXCtrl Class item (see Figure 3-3), and click OK.
Figure 3-3. Adding the GrFingerXCtrl control to the Toolbox
The GrFingerXCtrl control will now appear in the Toolbox (see Figure 3-4).
Figure 3-4. The GrFingerXCtrl control in the Toolbox
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 125
In the default Form1, populate it with the following controls (see Figure 3-5):
• PictureBox
• AxGrFingerXCtrl
• Label
• TextBox
• Button
• GroupBox
• Timer
Figure 3-5. Populating the default Form1 with all the controls
ListBox Control (ListBox1)
Button Control (btnRegister)
TextBox Control (txtEmail)
TextBox Control (txtContactNumber)
TextBox Control (txtCompany)
TextBox Control (txtName)
TextBox Control (txtSSN)
Label Control (lblMessage)
PictureBox Control
(PictureBox1) GroupBox Control
Timer Control
(Timer1)
Label Controls
AxGrFingerXCtrl Control
(AxGrFingerXVCrl1)
126 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
ACTIVEX CONTROL BUG IN VISUAL STUDIO 2005
Because of a bug in Visual Studio 2005, you may encounter an error message when you try to drag and drop
the AxGrFingerXCtrl control from the Toolbox onto the Windows form. The typical error message is “Failed to
import the ActiveX control. Please ensure it is properly registered.” This error usually arises when you try to
add third-party ActiveX controls to your Windows application.
To solve this error, after the error message, go to the obj\Debug folder in the application, and delete
the file named Interop.GrFingerXLib.dll. Once you’ve deleted the file, perform the drag and drop one
more time. This time, you should be able to add the ActiveX control successfully.
Set the image of the PictureBox control by clicking the ellipsis (…) icon in the Image property
of the PictureBox control in the Properties window. Click the Import button to load an
image named fingerprintreader (see Figure 3-6). Click OK.
■Tip Download the sample code from the Source Code/Download section of the Apress website
(http://www.apress.com).
Figure 3-6. Selecting a picture resource
Also, set the Interval property of the Timer control to 5000. This will cause the Timer
control to fire an event every five seconds.
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 127
Coding the Application
The GrFinger Fingerprint SDK comes with a sample application written in different languages:
Visual Basic 6, Java, C++, Visual Basic .NET (for Visual Studio .NET 2003), Visual Basic 2005 (for
Visual Studio 2005), and so on. For the Visual Basic 2005 and C# 2005 versions of this sample,
Griaule has provided two useful libraries: DBClass.vb/DBClass.cs and Util.vb/Util.cs.
The DBClass.vb (or DBClass.cs) library contains routines to add/retrieve user’s information
to/from a database. The Util.vb (or Util.cs) library contains all the necessary routines to
use the GrFingerXCtrl control and other supporting Win32 APIs. For this reason (rather than
reinventing the wheel), you will use these libraries in this application.
Hence, add the DBClass.vb (or DBClass.cs) and Util.vb (or Util.cs) files to the project
(see Figure 3-7; right-click Solution Explorer, and then select Add ➤ Existing Item). You can
add the two files from the default installation directory: C:\Program Files\Griaule\GrFinger
4.2\samples\Visual Basic.NET 2005\GrFingerX (or C:\Program Files\Griaule\GrFinger
4.2\samples\C# 2005\GrFingerX).
Figure 3-7. Adding the two useful libraries provided by Griaule
Listing 3-1 and Listing 3-2 (later in the chapter) show the full source of Util.vb (and
Util.cs) and DBClass.vb (and DBClass.cs). You will also modify the sample application
provided by Griaule to suit the purpose of this application.
To keep the code in the DBClass.vb (or DBClass.cs) library intact, you will use the sample
Access database provided by Griaule. The original Access database is named
GrFingerSample.mdb (you can find this in the default directory, C:\Program
Files\Griaule\GrFinger 4.2\samples\), and it contains one single table called enroll. The
original enroll table contains only two fields: ID and template (for storing the fingerprint
image). For this application, you will add five more fields to the enroll table. They are SSN,
Name, Company, ContactNumber, and Email (see Figure 3-8).
128 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
Figure 3-8. Adding new fields to the enroll table
Save the changes to the database, and add it to the project (right-click Solution Explorer,
and select Add ➤ Existing Items). Figure 3-9 shows the GrFingerSample.mdb database added to
the project.
Figure 3-9. Adding the GrFingerSample.mdb database to the project
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 129
Wiring Up All the Controls
Let’s now switch to the code-behind of Form1 and write the code to wire up all the controls.
First, import the GrFingerXLib namespace.
Visual Basic 2005
Imports GrFingerXLib
C# 2005
using GrFingerXLib;
Declare the following constants and member variables.
Visual Basic 2005
Public Class Form1
'---name of the database---
Const DBFile = "GrFingerSample.mdb"
Const Logfile = "C:\Log.csv"
Const ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; " & _
"Data Source="
'---for an instance of the Util.vb class---
Private myUtil As Util
'---for storing user’s ID---
Private _UserID As Integer
'---database connection---
Private connection As System.Data.OleDb.OleDbConnection
C# 2005
//---name of the database---
const string DBFile = "GrFingerSample.mdb";
const string Logfile = "C:\\Log.csv";
const string ConnectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=";
//---for an instance of the Util.vb class---
Util myUtil;
//---for storing user's ID---
int _UserID;
//---database connection---
System.Data.OleDb.OleDbConnection connection;
In the Form1_Load event, code the following.
130 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
Visual Basic 2005
Private Sub Form1_Load( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
Dim err As Integer
'---initialize Util class---
myUtil = New Util(ListBox1, PictureBox1, AxGrFingerXCtrl1)
'---Initialize GrFingerX Library---
err = myUtil.InitializeGrFinger()
'---Print result in log---
If err < 0 Then
myUtil.WriteError(err)
Exit Sub
Else
myUtil.WriteLog( _
"**GrFingerX Initialized Successfully**")
End If
'---create a log file---
If Not System.IO.File.Exists(Logfile) Then
System.IO.File.Create(Logfile)
End If
End Sub
C# 2005
private void Form1_Load(object sender, EventArgs e)
{
int err;
//---initialize util class---
myUtil = new Util(ListBox1, PictureBox1, null, null,
null, null, null, null);
//---wire up all the event handlers for the reader---
axGrFingerXCtrl1.SensorPlug += new
AxGrFingerXLib.
_IGrFingerXCtrlEvents_SensorPlugEventHandler(
axGrFingerXCtrl1_SensorPlug);
axGrFingerXCtrl1.SensorUnplug += new
AxGrFingerXLib.
_IGrFingerXCtrlEvents_SensorUnplugEventHandler(
axGrFingerXCtrl1_SensorUnplug);
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 131
axGrFingerXCtrl1.FingerDown += new
AxGrFingerXLib.
_IGrFingerXCtrlEvents_FingerDownEventHandler(
axGrFingerXCtrl1_FingerDown);
axGrFingerXCtrl1.FingerUp += new
AxGrFingerXLib.
_IGrFingerXCtrlEvents_FingerUpEventHandler(
axGrFingerXCtrl1_FingerUp);
axGrFingerXCtrl1.ImageAcquired += new
AxGrFingerXLib.
_IGrFingerXCtrlEvents_ImageAcquiredEventHandler(
axGrFingerXCtrl1_ImageAcquired);
//---Initialize GrFingerX Library---
err = myUtil.InitializeGrFinger(axGrFingerXCtrl1);
//---Print result in log---
if ((err < 0))
{
myUtil.WriteError((GRConstants)err);
return;
}
else
{
myUtil.WriteLog(
"**GrFingerX Initialized Successfully**");
}
//---create a log file---
if (!System.IO.File.Exists(Logfile))
{
System.IO.File.Create(Logfile);
}
}
Here, you create an instance of the Util class. The constructor of the Visual Basic version
of the Util class takes three arguments: the ListBox control to display the status of the
GrFingerXCtrl control, a PictureBox control to display the captured fingerprint image, and
finally the GrFingerXCtrl control. The C# version of the Util class takes eight arguments, but
only the first two are relevant in this case: the ListBox control to display the status of the
GrFingerXCtrl control and the PictureBox control to display the captured fingerprint image.
The rest of the arguments are related to the sample example shipped with the Fingerprint
SDK, and hence you will just ignore them here by sending a null value.
■Note For the C# code, you need to wire up the event handlers for the axGrFingerXCtrl1 control.
132 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
You then initialize the GrFingerX library and create a log file (if it is not already present).
This log file is a comma-separated values (CSV) file that contains the user’s ID and login time.
Next, service all the necessary events of the GrFingerXCtrl control.
Visual Basic 2005
' --------------------------------------------------------------------------------
' GrFingerX events
' --------------------------------------------------------------------------------
'---A fingerprint reader was plugged on system---
Private Sub AxGrFingerXCtrl1_SensorPlug( _
ByVal sender As System.Object, _
ByVal e As _
AxGrFingerXLib._IGrFingerXCtrlEvents_SensorPlugEvent) _
Handles AxGrFingerXCtrl1.SensorPlug
myUtil.WriteLog("Sensor: " & e.idSensor & ". Event: Plugged.")
AxGrFingerXCtrl1.CapStartCapture(e.idSensor)
End Sub
'---A fingerprint reader was unplugged from system---
Private Sub AxGrFingerXCtrl1_SensorUnplug( _
ByVal sender As System.Object, _
ByVal e As _
AxGrFingerXLib._IGrFingerXCtrlEvents_SensorUnplugEvent) _
Handles AxGrFingerXCtrl1.SensorUnplug
myUtil.WriteLog("Sensor: " & e.idSensor & _
". Event: Unplugged.")
AxGrFingerXCtrl1.CapStopCapture(e.idSensor)
End Sub
'---A finger was placed on reader---
Private Sub AxGrFingerXCtrl1_FingerDown( _
ByVal sender As System.Object, _
ByVal e As _
AxGrFingerXLib._IGrFingerXCtrlEvents_FingerDownEvent) _
Handles AxGrFingerXCtrl1.FingerDown
myUtil.WriteLog("Sensor: " & e.idSensor & _
". Event: Finger Placed.")
End Sub
'---A finger was removed from reader---
Private Sub AxGrFingerXCtrl1_FingerUp( _
ByVal sender As System.Object, _
ByVal e As AxGrFingerXLib._IGrFingerXCtrlEvents_FingerUpEvent) _
Handles AxGrFingerXCtrl1.FingerUp
myUtil.WriteLog("Sensor: " & e.idSensor & _
". Event: Finger removed.")
End Sub
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 133
C# 2005
//------------------------------------------------------------
// GrFingerX events
//------------------------------------------------------------
//---A fingerprint reader was plugged on system---
private void axGrFingerXCtrl1_SensorPlug(object sender,
AxGrFingerXLib._IGrFingerXCtrlEvents_SensorPlugEvent e)
{
myUtil.WriteLog(("Sensor: "
+ (e.idSensor + ". Event: Plugged.")));
axGrFingerXCtrl1.CapStartCapture(e.idSensor);
}
//---A fingerprint reader was unplugged from system---
private void axGrFingerXCtrl1_SensorUnplug(object sender,
AxGrFingerXLib._IGrFingerXCtrlEvents_SensorUnplugEvent e)
{
myUtil.WriteLog(("Sensor: "
+ (e.idSensor + ". Event: Unplugged.")));
axGrFingerXCtrl1.CapStopCapture(e.idSensor);
}
//---A finger was placed on reader---
private void axGrFingerXCtrl1_FingerDown(object sender,
AxGrFingerXLib._IGrFingerXCtrlEvents_FingerDownEvent e)
{
myUtil.WriteLog(("Sensor: "
+ (e.idSensor + ". Event: Finger Placed.")));
}
//---A finger was removed from reader---
private void axGrFingerXCtrl1_FingerUp(object sender,
AxGrFingerXLib._IGrFingerXCtrlEvents_FingerUpEvent e)
{
myUtil.WriteLog(("Sensor: "
+ (e.idSensor + ". Event: Finger removed.")));
}
These events are raised when the following happens:
• A fingerprint reader is plugged or unplugged from the computer.
• A finger is placed or removed from the fingerprint reader.
Also, you need to service the ImageAcquired event of the GrFingerXCtrl control. This event
is fired whenever a fingerprint image is acquired. Once the image is acquired, you call the
ExtractTemplate() function (explained after this) and then the IdentifyFingerprint()
subroutine to identify the user’s fingerprint.
134 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
Visual Basic 2005
'---An image was acquired from reader---
Private Sub AxGrFingerXCtrl1_ImageAcquired( _
ByVal sender As System.Object, _
ByVal e As _
AxGrFingerXLib._IGrFingerXCtrlEvents_ImageAcquiredEvent) _
Handles AxGrFingerXCtrl1.ImageAcquired
'---Copying acquired image---
myUtil.raw.height = e.height
myUtil.raw.width = e.width
myUtil.raw.res = e.res
myUtil.raw.img = e.rawImage
'---Signaling that an Image Event occurred.---
myUtil.WriteLog("Sensor: " & e.idSensor & _
". Event: Image captured.")
'---display fingerprint image---
myUtil.PrintBiometricDisplay(False, _
GRConstants.GR_DEFAULT_CONTEXT)
'---extract the template from the fingerprint scanned---
ExtractTemplate()
'---identify who the user is---
_UserID = IdentifyFingerprint()
If _UserID > 0 Then
'---user found---
Beep()
btnRegister.Enabled = False
'---display user's information---
GetUserInfo()
'---writes to log file---
WriteToLog(_UserID)
Else
'---user not found---
ClearDisplay()
btnRegister.Enabled = True
Beep()
lblMessage.Text = "User not found! Please register " & _
"your information below"
End If
End Sub
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 135
C# 2005
//---An image was acquired from reader---
private void axGrFingerXCtrl1_ImageAcquired(object sender,
AxGrFingerXLib._IGrFingerXCtrlEvents_ImageAcquiredEvent e)
{
//---Copying acquired image---
myUtil._raw.height = e.height;
myUtil._raw.width = e.width;
myUtil._raw.Res = e.res;
myUtil._raw.img = e.rawImage;
//---Signaling that an Image Event occurred.---
myUtil.WriteLog(("Sensor: "
+ (e.idSensor + ". Event: Image captured.")));
//---display fingerprint image---
myUtil.PrintBiometricDisplay(false, _
GRConstants.GR_DEFAULT_CONTEXT);
//---extract the template from the fingerprint scanned---
ExtractTemplate();
//---identify who the user is---
_UserID = IdentifyFingerprint();
if ((_UserID > 0))
{
//---user found---
btnRegister.Enabled = false;
GetUserInfo();
//---writes to log file---
WriteToLog(_UserID.ToString());
}
else
{
//---user not found---
ClearDisplay();
btnRegister.Enabled = true;
lblMessage.Text = "User not found! Please " & _
"register your information below";
}
}
Once the user’s identity is found, you will display the user’s particulars by calling
the GetUserInfo() subroutine. You will also write an entry to the log file by calling the
WriteToLog() subroutine.
136 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
Once a fingerprint image is captured, you need to extract some characteristic points from
the image, called minutiae. One regular fingerprint has some 50 minutiae. To identify a user,
you need about 13 of them. When all the minutiae are extracted, they are put together into a
structure called a template, which is the joining of all the extracted minutiae in a fingerprint.
According to Griaule, the identification is made by a triangulation process and geometrical
relation between the minutiae only, not the entire image. You accomplish this process by
using the ExtractTemplate() function.
Visual Basic 2005
'---Extract a template from a fingerprint image---
Private Function ExtractTemplate() As Integer
Dim ret As Integer
'---extract template---
ret = myUtil.ExtractTemplate()
'---write template quality to log---
If ret = GRConstants.GR_BAD_QUALITY Then
myUtil.WriteLog("Template extracted successfully. " & _
"Bad quality.")
ElseIf ret = GRConstants.GR_MEDIUM_QUALITY Then
myUtil.WriteLog("Template extracted successfully. " & _
"Medium quality.")
ElseIf ret = GRConstants.GR_HIGH_QUALITY Then
myUtil.WriteLog("Template extracted successfully. " & _
"High quality.")
End If
If ret >= 0 Then
'---if no error, display minutiae/segments/directions
' into the image---
myUtil.PrintBiometricDisplay(True, _
GRConstants.GR_NO_CONTEXT)
Else
'---write error to log---
myUtil.WriteError(ret)
End If
Return ret
End Function
C# 2005
//---Extract a template from a fingerprint image---
private int ExtractTemplate()
{
int ret;
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 137
//---extract template---
ret = myUtil.ExtractTemplate();
//---write template quality to log---
if ((GRConstants)ret == GRConstants.GR_BAD_QUALITY)
{
myUtil.WriteLog(
"Template extracted successfully. Bad quality.");
}
else if ((GRConstants)ret ==
GRConstants.GR_MEDIUM_QUALITY)
{
myUtil.WriteLog(
"Template extracted successfully. Medium quality.");
}
else if ((GRConstants)ret == GRConstants.GR_HIGH_QUALITY)
{
myUtil.WriteLog(
"Template extracted successfully. High quality.");
}
if ((ret >= 0))
{
//---if no error, display minutiae/segments/directions
// into the image---
myUtil.PrintBiometricDisplay(true,
GRConstants.GR_NO_CONTEXT);
}
else
{
//---write error to log---
myUtil.WriteError((GRConstants)ret);
}
return ret;
}
The IdentifyFingerprint() function locates the identity of the user by calling the
Identify() method located in the Util.vb (or Util.cs) class. It returns the ID of the identified
user.
Visual Basic 2005
'---Identify a fingerprint; returns the ID of the user---
Private Function IdentifyFingerprint() As Integer
Dim ret As Integer, score As Integer
score = 0
'---identify it---
ret = myUtil.Identify(score)
138 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
'---write result to log---
If ret > 0 Then
myUtil.WriteLog("Fingerprint identified. ID = " & ret & _
". Score = " & score & ".")
myUtil.PrintBiometricDisplay(True, _
GRConstants.GR_DEFAULT_CONTEXT)
ElseIf ret = 0 Then
myUtil.WriteLog("Fingerprint not Found.")
Else
myUtil.WriteError(ret)
End If
Return ret
End Function
C# 2005
//---Identify a fingerprint; returns the ID of the user---
private int IdentifyFingerprint()
{
int ret;
int score;
score = 0;
//---identify it---
ret = myUtil.Identify(ref score);
//---write result to log---
if ((ret > 0))
{
myUtil.WriteLog(("Fingerprint identified. ID = "
+ (ret + (". Score = " + (score + ".")))));
myUtil.PrintBiometricDisplay(true,
GRConstants.GR_DEFAULT_CONTEXT);
}
else if ((ret == 0))
{
myUtil.WriteLog("Fingerprint not Found.");
}
else
{
myUtil.WriteError((GRConstants)ret);
}
return ret;
}
The GetUserInfo() subroutine retrieves the user’s particulars using the value of the UserID
variable.
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 139
Visual Basic 2005
'---get user's information---
Public Sub GetUserInfo()
Dim filePath As String
Try
filePath = Application.StartupPath() & "\" & DBFile
connection = New OleDb.OleDbConnection(ConnectionString _
& filePath)
connection.Open()
Dim reader As OleDb.OleDbDataReader
Dim command As OleDb.OleDbCommand = New OleDb.OleDbCommand
command.Connection = connection
'---retrieve user's particulars---
command.CommandText = "SELECT * FROM Enroll WHERE ID=" & _
_UserID
reader = _
command.ExecuteReader(CommandBehavior.CloseConnection)
reader.Read()
'---display user's particulars---
lblMessage.Text = "Welcome, " & reader("name")
txtSSN.Text = reader("SSN")
txtName.Text = reader("Name")
txtCompany.Text = reader("Company")
txtContactNumber.Text = reader("ContactNumber")
txtEmail.Text = reader("Email")
'---reset the timer to another five seconds---
Timer1.Enabled = False
Timer1.Enabled = True
Catch ex As Exception
MsgBox(ex.ToString)
Finally
connection.Close()
End Try
End Sub
C# 2005
//---get user's information---
public void GetUserInfo()
{
string filePath;
try
{
140 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
filePath = (Application.StartupPath + ("\\" +
DBFile));
connection = new System.Data.OleDb.OleDbConnection((
ConnectionString + filePath));
connection.Open();
System.Data.OleDb.OleDbDataReader reader;
System.Data.OleDb.OleDbCommand command = new
System.Data.OleDb.OleDbCommand();
command.Connection = connection;
//---retrieve user's particulars---
command.CommandText = (
"SELECT * FROM Enroll WHERE ID=" + _UserID);
reader =
command.ExecuteReader(
CommandBehavior.CloseConnection);
reader.Read();
//---display user's particulars---
lblMessage.Text = ("Welcome, " + reader["name"]);
txtSSN.Text = reader["SSN"].ToString();
txtName.Text = reader["Name"].ToString();
txtCompany.Text = reader["Company"].ToString();
txtContactNumber.Text =
reader["ContactNumber"].ToString();
txtEmail.Text = reader["Email"].ToString();
//---reset the timer to another five seconds---
Timer1.Enabled = false;
Timer1.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error");
}
finally
{
connection.Close();
}
}
When a fingerprint is not recognized, the user can register the fingerprint by filling in his
particulars. This is accomplished by the Register button, which first adds the fingerprint to the
database (via the EnrollFingerprint() function) and then adds the particulars of the user
using the AddNewUser() subroutine.
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 141
Visual Basic 2005
'---Register button---
Private Sub btnRegister_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnRegister.Click
'---first add the fingerprint---
_UserID = EnrollFingerprint()
'---then add the particulars---
AddNewUser()
'---clears the display---
ClearDisplay()
'---writes to log file---
WriteToLog(_UserID)
End Sub
C# 2005
//---Register button---
private void btnRegister_Click(
object sender,
System.EventArgs e)
{
//---first add the fingerprint---
_UserID = EnrollFingerprint();
//---then add the particulars---
AddNewUser();
//---clears the display---
ClearDisplay();
//---writes to log file---
WriteToLog(_UserID.ToString());
}
The EnrollFingerprint() function enrolls a finger in the database using the Enroll()
method defined in the Util.vb (or Util.cs) class.
Visual Basic 2005
'---adds a fingerprint to the database; returns the ID of the
' user---
Private Function EnrollFingerprint() As Integer
Dim id As Integer
142 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
'---add fingerprint---
id = myUtil.Enroll()
'---write result to log---
If id >= 0 Then
myUtil.WriteLog("Fingerprint enrolled with id = " & id)
Else
myUtil.WriteLog("Error: Fingerprint not enrolled")
End If
Return id
End Function
C# 2005
//---adds a fingerprint to the database; returns the ID of
// the user---
private int EnrollFingerprint()
{
int id;
//---add fingerprint---
id = myUtil.Enroll();
//---write result to log---
if ((id >= 0))
{
myUtil.WriteLog(("Fingerprint enrolled with id = " +
id));
}
else
{
myUtil.WriteLog("Error: Fingerprint not enrolled");
}
return id;
}
The AddNewUser() subroutine saves the user’s particulars in the database.
Visual Basic 2005
'---Add a new user's information to the database---
Public Sub AddNewUser()
Dim filePath As String
Try
filePath = Application.StartupPath() & "\" & DBFile
connection = New OleDb.OleDbConnection(ConnectionString _
& filePath)
connection.Open()
Dim command As OleDb.OleDbCommand = New OleDb.OleDbCommand
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 143
command.Connection = connection
'---set the user's particulars in the table---
Dim sql As String = "UPDATE enroll SET SSN='" & _
txtSSN.Text & "', " & _
"Name='" & txtName.Text & "', " & _
"Company='" & txtCompany.Text & "', " & _
"ContactNumber='" & txtContactNumber.Text & "', " & _
"Email='" & txtEmail.Text & "' " & _
" WHERE ID=" & _UserID
command.CommandText = sql
command.ExecuteNonQuery()
MsgBox("User added successfully!")
Catch ex As Exception
MsgBox(ex.ToString)
Finally
connection.Close()
End Try
End Sub
C# 2005
//---Add a new user's information to the database---
public void AddNewUser()
{
string filePath;
try
{
filePath = (Application.StartupPath + ("\\" +
DBFile));
connection = new System.Data.OleDb.OleDbConnection((
ConnectionString + filePath));
connection.Open();
System.Data.OleDb.OleDbCommand command = new
System.Data.OleDb.OleDbCommand();
command.Connection = connection;
//---set the user's particulars in the table---
string sql = ("UPDATE enroll SET SSN=\'"
+ (txtSSN.Text + ("\', " + ("Name=\'"
+ (txtName.Text + ("\', " + ("Company=\'"
+ (txtCompany.Text + ("\', " +
("ContactNumber=\'"
+ (txtContactNumber.Text + ("\', " + ("Email=\'"
+ (txtEmail.Text + ("\' " + (" WHERE ID=" +
_UserID))))))))))))))));
command.CommandText = sql;
144 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
command.ExecuteNonQuery();
MessageBox.Show("User added successfully!", "Error");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error");
}
finally
{
connection.Close();
}
}
The ClearDisplay() subroutine clears the information displayed in the various TextBox
controls.
Visual Basic 2005
'---Clears the user's particulars---
Public Sub ClearDisplay()
lblMessage.Text = _
"Please place your index finger on the fingerprint reader"
PictureBox1.Image = My.Resources.fingerprintreader
txtSSN.Text = String.Empty
txtName.Text = String.Empty
txtCompany.Text = String.Empty
txtContactNumber.Text = String.Empty
txtEmail.Text = String.Empty
End Sub
C# 2005
//---Clears the user's particulars---
public void ClearDisplay()
{
lblMessage.Text =
"Please place your index finger on the fingerprint" +
" reader";
PictureBox1.Image = FingerPrintReader_CS.
Properties.Resources.fingerprintreader;
txtSSN.Text = String.Empty;
txtName.Text = String.Empty;
txtCompany.Text = String.Empty;
txtContactNumber.Text = String.Empty;
txtEmail.Text = String.Empty;
}
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 145
When the Timer1_Tick event is fired (every five seconds), call the ClearDisplay() subroutine
to clear the display.
Visual Basic 2005
'---the Timer control---
Private Sub Timer1_Tick( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Timer1.Tick
ClearDisplay()
Timer1.Enabled = False
End Sub
C# 2005
private void Timer1_Tick(object sender, EventArgs e)
{
ClearDisplay();
Timer1.Enabled = false;
}
The WriteToLog() subroutine writes to the log file an entry containing the user’s ID and
the current time.
Visual Basic 2005
Public Sub WriteToLog(ByVal ID As String)
'---write to a log file---
Dim sw As New System.IO.StreamWriter( _
Logfile, True, System.Text.Encoding.ASCII)
sw.WriteLine(id & "," & Now.ToString)
sw.Close()
End Sub
C# 2005
public void WriteToLog(string ID)
{
//---write to a log file---
System.IO.StreamWriter sw = new
System.IO.StreamWriter(
Logfile, true, System.Text.Encoding.ASCII);
sw.WriteLine((ID + ("," +
System.DateTime.Now.ToString())));
sw.Close();
}
146 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
Testing the Application
You are now ready to test the application. Press F5 in Visual Studio 2005, and you will see the
application shown in Figure 3-10.
Figure 3-10. Testing the application
Place your index finger on the reader, and you should be prompted to register with your
particulars. Once registered, your particulars will be cleared after five seconds. You can now
try placing the same finger to check whether you can be identified correctly. If so, you will see
your information displayed, as shown in Figure 3-11.
Figure 3-11. Displaying the information of an identified user
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 147
Note that sometimes your fingerprint may not be correctly identified. This is likely due to
the incorrect positioning of your finger. Try again, and it should be identified correctly.
Summary
In this chapter, you saw how to integrate a fingerprint reader into your .NET application.
Although the example shown in this chapter was simple, you can easily extend it to more complex
scenarios, such as video rental applications, payment services, and so on. If you have not
started evaluating biometric authentication for your projects, this is a good time to start!
Listing 3-1. Util.vb
Visual Basic 2005
'-------------------------------------------------------------------------------
'GrFinger Sample
'(c) 2005 Griaule Tecnologia Ltda.
'http://www.griaule.com
'-------------------------------------------------------------------------------
'
'This sample is provided with "GrFinger Fingerprint Recognition Library" and
'can't run without it. It's provided just as an example of using GrFinger
'Fingerprint Recognition Library and should not be used as basis for any
'commercial product.
'
'Griaule Tecnologia makes no representations concerning either the merchantability
'of this software or the suitability of this sample for any particular purpose.
'
'THIS SAMPLE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
'IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
'OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
'IN NO EVENT SHALL GRIAULE BE LIABLE FOR ANY DIRECT, INDIRECT,
'INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
'NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
'DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
'THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
'(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
'THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'
'You can download the free version of GrFinger directly from Griaule website.
'
'These notices must be retained in any copies of any part of this
'documentation and/or sample.
'
'-------------------------------------------------------------------------------
' --------------------------------------------------------------------------------
148 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
' Support and fingerprint management routines
' --------------------------------------------------------------------------------
Imports GrFingerXLib
Imports Microsoft.VisualBasic
' Raw image data type.
Public Structure RawImage
' Image data.
Public img As Object
' Image width.
Public width As Long
' Image height.
Public height As Long
' Image resolution.
Public res As Long
End Structure
Public Class Util
' Some constants to make our code cleaner
Public Const ERR_CANT_OPEN_BD As Integer = -999
Public Const ERR_INVALID_ID As Integer = -998
Public Const ERR_INVALID_TEMPLATE As Integer = -997
' Importing necessary HDC functions
Private Declare Function GetDC Lib "user32" (ByVal hwnd As Int32) As Int32
Private Declare Function ReleaseDC Lib "user32" _
(ByVal hwnd As Int32, ByVal hdc As Int32) As Int32
' The last acquired image.
Public raw As RawImage
' The template extracted from last acquired image.
Public template As New TTemplate
' Database class.
Public DB As DBClass
' Reference to main form log.
Private _lbLog As ListBox
' Reference to main form Image.
Private _pbPic As PictureBox
' GrFingerX component
Private _GrFingerX As AxGrFingerXLib.AxGrFingerXCtrl
' ----------------------------------------------------------------------------
' Support functions
' ----------------------------------------------------------------------------
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 149
' This class creates an Util class with some functions
' to help us to develop our GrFinger Application
Public Sub New(ByRef lbLog As ListBox, _
ByRef pbPic As PictureBox, _
ByRef GrFingerX As AxGrFingerXLib.AxGrFingerXCtrl)
_lbLog = lbLog
_pbPic = pbPic
_GrFingerX = GrFingerX
End Sub
' Write a message in box.
Public Sub WriteLog(ByVal message As String)
_lbLog.Items.Add(message)
_lbLog.SelectedIndex = _lbLog.Items.Count - 1
_lbLog.ClearSelected()
End Sub
' Write and describe an error.
Public Sub WriteError(ByVal errorCode As Integer)
Select Case errorCode
Case GRConstants.GR_ERROR_INITIALIZE_FAIL
WriteLog("Fail to Initialize GrFingerX. (Error:" & errorCode & ")")
Case GRConstants.GR_ERROR_NOT_INITIALIZED
WriteLog("The GrFingerX Library is not initialized. (Error:" & _
errorCode & ")")
Case GRConstants.GR_ERROR_FAIL_LICENSE_READ
WriteLog( _
"License not found. See manual for troubleshooting. (Error:" _
& errorCode & ")")
MessageBox.Show( _
"License not found. See manual for troubleshooting.")
Case GRConstants.GR_ERROR_NO_VALID_LICENSE
WriteLog( _
"The license is not valid. See manual for " & _
"troubleshooting. (Error:" & errorCode & ")")
MessageBox.Show( _
"The license is not valid. See manual for troubleshooting.")
Case GRConstants.GR_ERROR_NULL_ARGUMENT
WriteLog("The parameter have a null value. (Error:" & _
errorCode & ")")
Case GRConstants.GR_ERROR_FAIL
WriteLog("Fail to create a GDI object. (Error:" & errorCode & ")")
Case GRConstants.GR_ERROR_ALLOC
WriteLog("Fail to create a context. Cannot " & _
"allocate memory. (Error:" & errorCode & ")")
Case GRConstants.GR_ERROR_PARAMETERS
WriteLog("One or more parameters are out of " & _
150 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
"bound. (Error:" & errorCode & ")")
Case GRConstants.GR_ERROR_WRONG_USE
WriteLog("This function cannot be called at " & _
"this time. (Error:" & errorCode & ")")
Case GRConstants.GR_ERROR_EXTRACT
WriteLog("Template Extraction failed. (Error:" & errorCode & ")")
Case GRConstants.GR_ERROR_SIZE_OFF_RANGE
WriteLog("Image is too larger or too short. (Error:" & _
errorCode & ")")
Case GRConstants.GR_ERROR_RES_OFF_RANGE
WriteLog("Image have too low or too high resolution. (Error:" & _
errorCode & ")")
Case GRConstants.GR_ERROR_CONTEXT_NOT_CREATED
WriteLog("The Context could not be created. (Error:" & _
errorCode & ")")
Case GRConstants.GR_ERROR_INVALID_CONTEXT
WriteLog("The Context does not exist. (Error:" & errorCode & ")")
' Capture error codes
Case GRConstants.GR_ERROR_CONNECT_SENSOR
WriteLog("Error while connection to sensor. (Error:" & _
errorCode & ")")
Case GRConstants.GR_ERROR_CAPTURING
WriteLog("Error while capturing from sensor. (Error:" & _
errorCode & ")")
Case GRConstants.GR_ERROR_CANCEL_CAPTURING
WriteLog("Error while stop capturing from sensor. (Error:" & _
errorCode & ")")
Case GRConstants.GR_ERROR_INVALID_ID_SENSOR
WriteLog("The idSensor is invalid. (Error:" & errorCode & ")")
Case GRConstants.GR_ERROR_SENSOR_NOT_CAPTURING
WriteLog("The sensor is not capturing. (Error:" & errorCode & ")")
Case GRConstants.GR_ERROR_INVALID_EXT
WriteLog("The File have a unknown extension. (Error:" & _
errorCode & ")")
Case GRConstants.GR_ERROR_INVALID_FILENAME
WriteLog("The filename is invalid. (Error:" & errorCode & ")")
Case GRConstants.GR_ERROR_INVALID_FILETYPE
WriteLog("The file type is invalid. (Error:" & errorCode & ")")
Case GRConstants.GR_ERROR_SENSOR
WriteLog("The sensor raise an error. (Error:" & errorCode & ")")
' Our error codes
Case ERR_INVALID_TEMPLATE
WriteLog("Invalid Template. (Error:" & errorCode & ")")
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 151
Case ERR_INVALID_ID
WriteLog("Invalid ID. (Error:" & errorCode & ")")
Case ERR_CANT_OPEN_BD
WriteLog("Unable to connect to DataBase. (Error:" & errorCode & ")")
Case Else
WriteLog("Error:" & errorCode)
End Select
End Sub
' Check if we have a valid template
Private Function TemplateIsValid() As Boolean
' Check template size
Return template.Size > 0
End Function
' ----------------------------------------------------------------------------
' Main functions for fingerprint recognition management
' ----------------------------------------------------------------------------
' Initializes GrFinger ActiveX and all necessary utilities.
Public Function InitializeGrFinger() As Integer
Dim err As Integer
DB = New DBClass
' Open DataBase
If DB.OpenDB() = False Then Return ERR_CANT_OPEN_BD
' Create a new Template
template.Size = 0
' Create a new raw image
raw.img = Nothing
raw.width = 0
raw.height = 0
' Initializing library
err = _GrFingerX.Initialize()
If err < 0 Then Return err
Return _GrFingerX.CapInitialize()
End Function
' Finalizes and close the DB.
Public Sub FinalizeGrFinger()
' finalize library
_GrFingerX.Finalize()
_GrFingerX.CapFinalize()
' close DB
DB.closeDB()
DB = Nothing
End Sub
152 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
' Display fingerprint image on screen
Public Sub PrintBiometricDisplay( _
ByVal biometricDisplay As Boolean, ByVal context As Integer)
' handle to finger image
Dim handle As System.Drawing.Image = Nothing
' screen HDC
Dim hdc As Integer = GetDC(0)
If biometricDisplay Then
' get image with biometric info
_GrFingerX.BiometricDisplay( _
template.tpt, raw.img, raw.width, raw.height, _
raw.res, hdc, handle, context)
Else
' get raw image
_GrFingerX.CapRawImageToHandle( _
raw.img, raw.width, raw.height, hdc, handle)
End If
' draw image on picture box
If Not (handle Is Nothing) Then
_pbPic.Image = handle
_pbPic.Update()
End If
' release screen HDC
ReleaseDC(0, hdc)
End Sub
' Add a fingerprint template to database
Public Function Enroll() As Integer
' Checking if template is valid.
If TemplateIsValid() Then
' Adds template to database and gets ID.
Return DB.AddTemplate(template)
Else
Return -1
End If
End Function
' Extract a fingerprint template from current image
Function ExtractTemplate() As Integer
Dim ret As Integer
' set current buffer size for extract template
template.Size = template.tpt.Length
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 153
ret = _GrFingerX.Extract( _
raw.img, raw.width, raw.height, raw.res, template.tpt, template.Size, _
GRConstants.GR_DEFAULT_CONTEXT)
' if error, set template size to 0
' Result < 0 => extraction problem
If ret < 0 Then template.Size = 0
Return ret
End Function
' Identify current fingerprint on our database
Public Function Identify(ByRef score As Integer) As Integer
Dim ret As Integer
Dim i As Integer
' Checking if template is valid.
If Not TemplateIsValid() Then Return ERR_INVALID_TEMPLATE
' Starting identification process and supplying query template.
Dim tmpTpt As Array = Array.CreateInstance(GetType(Byte), template.Size)
Array.Copy(template.tpt, tmpTpt, template.Size)
ret = _GrFingerX.IdentifyPrepare(tmpTpt, GRConstants.GR_DEFAULT_CONTEXT)
' error?
If ret < 0 Then Return ret
' Getting enrolled templates from database.
Dim templates As TTemplates() = DB.getTemplates()
' Iterate over all templates in database
For i = 1 To templates.Length
' Comparing the current template.
If Not (templates(i - 1).template Is Nothing) Then
Dim tempTpt As Array = _
Array.CreateInstance(GetType(Byte), _
templates(i - 1).template.Size)
Array.Copy(templates(i - 1).template.tpt, tempTpt, _
templates(i - 1).template.Size)
ret = _GrFingerX.Identify(tempTpt, score, _
GRConstants.GR_DEFAULT_CONTEXT)
End If
' Checking if query template and reference template match.
If ret = GRConstants.GR_MATCH Then
Return templates(i - 1).ID
End If
If ret < 0 Then Return ret
Next
' end of database, return "no match" code
Return GRConstants.GR_NOT_MATCH
End Function
154 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
' Check current fingerprint against another one in our database
Public Function Verify(ByVal id As Integer, ByRef score As Integer) As Integer
Dim tptref As System.Array
' Checking if template is valid.
If Not (TemplateIsValid()) Then Return ERR_INVALID_TEMPLATE
' Getting template with the supplied ID from database.
tptref = DB.getTemplate(id)
' Checking if ID was found.
If tptref Is Nothing Then Return ERR_INVALID_ID
' Comparing templates.
Dim tempTpt As Array = Array.CreateInstance(GetType(Byte), template.Size)
Array.Copy(template.tpt, tempTpt, template.Size)
Return _GrFingerX.Verify(tempTpt, tptref, score, _
GRConstants.GR_DEFAULT_CONTEXT)
End Function
' Show GrFinger version and type
Public Sub MessageVersion()
Dim majorVersion As Integer = 0
Dim minorVersion As Integer = 0
Dim result As GRConstants
Dim vStr As String = ""
result = _GrFingerX.GetGrFingerVersion(majorVersion, minorVersion)
If result = GRConstants.GRFINGER_FULL Then vStr = "FULL"
If result = GRConstants.GRFINGER_LIGHT Then vStr = "LIGHT"
If result = GRConstants.GRFINGER_FREE Then vStr = "FREE"
MessageBox.Show("The GrFinger DLL version is " & majorVersion & _
"." & minorVersion & "." & vbCrLf & _
"The license type is '" & vStr & "'.", "GrFinger Version")
End Sub
End Class
C# 2005
/*
-------------------------------------------------------------------------------
GrFinger Sample
(c) 2005 Griaule Tecnologia Ltda.
http://www.griaule.com
-------------------------------------------------------------------------------
This sample is provided with "GrFinger Fingerprint Recognition Library" and
can't run without it. It's provided just as an example of using GrFinger
Fingerprint Recognition Library and should not be used as basis for any
commercial product.
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 155
Griaule Tecnologia makes no representations concerning either the merchantability
of this software or the suitability of this sample for any particular purpose.
THIS SAMPLE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL GRIAULE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You can download the free version of GrFinger directly from Griaule website.
These notices must be retained in any copies of any part of this
documentation and/or sample.
-------------------------------------------------------------------------------
*/
// -------------------------------------------------------------------------------
// Support and fingerprint management routines
// -------------------------------------------------------------------------------
using GrFingerXLib;
using System;
using System.Drawing;
using System.Data.OleDb;
using System.Windows.Forms;
using System.Runtime.InteropServices;
// Raw image data type.
public struct TRawImage
{
// Image data.
public object img;
// Image width.
public int width;
// Image height.
public int height;
// Image resolution.
public int Res;
};
public class Util
{
156 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
// Some constants to make our code cleaner
public const int ERR_CANT_OPEN_BD = -999;
public const int ERR_INVALID_ID = -998;
public const int ERR_INVALID_TEMPLATE = -997;
// ---------------------------------------------------------------------------
// Support functions
// ---------------------------------------------------------------------------
// This class creates an Util class with some functions
// to help us to develop our GrFinger Application
public Util(ListBox lbLog, PictureBox pbPic,
Button btEnroll, Button btnExtract, Button btIdentify, Button btVerify,
CheckBox cbAutoExtract, CheckBox cbAutoIdentify)
{
_lbLog = lbLog;
_pbPic = pbPic;
_btEnroll = btEnroll;
_btExtract = btnExtract;
_btIdentify = btIdentify;
_btVerify = btVerify;
_cbAutoExtract = cbAutoExtract;
_cbAutoIdentify = cbAutoIdentify;
_DB = null;
_tpt = null;
}
~Util()
{
}
// Write a message in log box.
public void WriteLog(String msg)
{
_lbLog.Items.Add(msg);
_lbLog.SelectedIndex = _lbLog.Items.Count - 1;
_lbLog.ClearSelected();
}
// Write and describe an error.
public void WriteError(GrFingerXLib.GRConstants errorCode)
{
switch ((int)errorCode)
{
case (int)GRConstants.GR_ERROR_INITIALIZE_FAIL:
WriteLog("Fail to Initialize GrFingerX. (Error:" + errorCode + ")");
return;
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 157
case (int)GRConstants.GR_ERROR_NOT_INITIALIZED:
WriteLog("The GrFingerX Library is not initialized. (Error:" +
errorCode + ")");
return;
case (int)GRConstants.GR_ERROR_FAIL_LICENSE_READ:
WriteLog("License not found. See manual for " +
"troubleshooting. (Error:" + errorCode + ")");
MessageBox.Show("License not found. See " +
"manual for troubleshooting.");
return;
case (int)GRConstants.GR_ERROR_NO_VALID_LICENSE:
WriteLog("The license is not valid. See manual for " +
"troubleshooting. (Error:" + errorCode + ")");
MessageBox.Show("The license is not valid. See " +
"manual for troubleshooting.");
return;
case (int)GRConstants.GR_ERROR_NULL_ARGUMENT:
WriteLog("The parameter have a null value. (Error:" +
errorCode + ")");
return;
case (int)GRConstants.GR_ERROR_FAIL:
WriteLog("Fail to create a GDI object. (Error:" + errorCode + ")");
return;
case (int)GRConstants.GR_ERROR_ALLOC:
WriteLog("Fail to create a context. Cannot allocate " +
"memory. (Error:" + errorCode + ")");
return;
case (int)GRConstants.GR_ERROR_PARAMETERS:
WriteLog("One or more parameters are out of bound. (Error:" +
errorCode + ")");
return;
case (int)GRConstants.GR_ERROR_WRONG_USE:
WriteLog("This function cannot be called at this time. (Error:" +
errorCode + ")");
return;
case (int)GRConstants.GR_ERROR_EXTRACT:
WriteLog("Template Extraction failed. (Error:" + errorCode + ")");
return;
case (int)GRConstants.GR_ERROR_SIZE_OFF_RANGE:
WriteLog("Image is too larger or too short. (Error:" +
errorCode + ")");
return;
case (int)GRConstants.GR_ERROR_RES_OFF_RANGE:
WriteLog("Image have too low or too high resolution. (Error:" +
errorCode + ")");
return;
case (int)GRConstants.GR_ERROR_CONTEXT_NOT_CREATED:
158 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
WriteLog("The Context could not be created. (Error:" +
errorCode + ")");
return;
case (int)GRConstants.GR_ERROR_INVALID_CONTEXT:
WriteLog("The Context does not exist. (Error:" + errorCode + ")");
return;
// Capture error codes
case (int)GRConstants.GR_ERROR_CONNECT_SENSOR:
WriteLog("Error while connection to sensor. (Error:" +
errorCode + ")");
return;
case (int)GRConstants.GR_ERROR_CAPTURING:
WriteLog("Error while capturing from sensor. (Error:" +
errorCode + ")");
return;
case (int)GRConstants.GR_ERROR_CANCEL_CAPTURING:
WriteLog("Error while stop capturing from sensor. (Error:" +
errorCode + ")");
return;
case (int)GRConstants.GR_ERROR_INVALID_ID_SENSOR:
WriteLog("The idSensor is invalid. (Error:" + errorCode + ")");
return;
case (int)GRConstants.GR_ERROR_SENSOR_NOT_CAPTURING:
WriteLog("The sensor is not capturing. (Error:" + errorCode + ")");
return;
case (int)GRConstants.GR_ERROR_INVALID_EXT:
WriteLog("The File have a unknown extension. (Error:" +
errorCode + ")");
return;
case (int)GRConstants.GR_ERROR_INVALID_FILENAME:
WriteLog("The filename is invalid. (Error:" + errorCode + ")");
return;
case (int)GRConstants.GR_ERROR_INVALID_FILETYPE:
WriteLog("The file type is invalid. (Error:" + errorCode + ")");
return;
case (int)GRConstants.GR_ERROR_SENSOR:
WriteLog("The sensor raise an error. (Error:" + errorCode + ")");
return;
// Our error codes
case ERR_INVALID_TEMPLATE:
WriteLog("Invalid Template. (Error:"+errorCode+")");
return;
case ERR_INVALID_ID:
WriteLog("Invalid ID. (Error:"+errorCode+")");
return;
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 159
case ERR_CANT_OPEN_BD:
WriteLog("Unable to connect to DataBase. (Error:"+errorCode+")");
return;
default:
WriteLog("Error:" + errorCode);
return;
}
}
// Check if we have a valid template
private bool TemplateIsValid() {
// Check the template size and data
return ((_tpt._size > 0) && (_tpt._tpt != null));
}
// ---------------------------------------------------------------------------
// Main functions for fingerprint recognition management
// ---------------------------------------------------------------------------
// Initializes GrFinger ActiveX and all necessary utilities.
public int InitializeGrFinger(AxGrFingerXLib.AxGrFingerXCtrl grfingerx)
{
GRConstants result;
_grfingerx = grfingerx;
//Check DataBase Class.
if (_DB == null)
_DB = new DBClass();
//Open DataBase
if(_DB.openDB()==false)
{
return ERR_CANT_OPEN_BD;
}
//Create a new Template
if (_tpt == null)
_tpt = new TTemplate();
//Create a new raw image
_raw = new TRawImage();
//Initialize library
result = (GRConstants)_grfingerx.Initialize();
if (result < 0) return (int)result;
return (int)_grfingerx.CapInitialize();
}
160 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
// Finalizes library and close DB.
public void FinalizeUtil() {
// finalize library
_grfingerx.Finalize();
_grfingerx.CapFinalize();
// close DB
_DB.closeDB();
_raw.img = null;
_tpt = null;
_DB = null;
}
// Display fingerprint image on screen
public void PrintBiometricDisplay(bool isBiometric,
GrFingerXLib.GRConstants contextId)
{
// handle to finger image
System.Drawing.Image handle = null;
// screen HDC
IntPtr hdc = GetDC(System.IntPtr.Zero);
if (isBiometric) {
// get image with biometric info
_grfingerx.BiometricDisplay(ref _tpt._tpt,
ref _raw.img,_raw.width,_raw.height,_raw.Res,hdc.ToInt32(),
ref handle,(int)contextId);
} else {
// get raw image
_grfingerx.CapRawImageToHandle(ref _raw.img,_raw.width,
_raw.height, hdc.ToInt32(), ref handle);
}
// draw image on picture box
if (handle != null)
{
_pbPic.Image = handle;
_pbPic.Update();
}
// release screen HDC
ReleaseDC(System.IntPtr.Zero,hdc);
}
// Add a fingerprint template to database
public int Enroll()
{
int id = 0;
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 161
// Checks if template is valid.
if (TemplateIsValid())
{
// Adds template to database and returns template ID.
_DB.addTemplate(_tpt, ref id);
return id;
}
else
{
return -1;
}
}
// Extract a fingerprint template from current image
public int ExtractTemplate()
{
int result;
// set current buffer size for the extract template
_tpt._size = (int)GRConstants.GR_MAX_SIZE_TEMPLATE;
result = (int)_grfingerx.Extract(
ref _raw.img, _raw.width, _raw.height, _raw.Res,
ref _tpt._tpt,ref _tpt._size,
(int)GRConstants.GR_DEFAULT_CONTEXT);
// if error, set template size to 0
if (result < 0)
{
// Result < 0 => extraction problem
_tpt._size = 0;
}
return result;
}
// Identify current fingerprint on our database
public int Identify(ref int score) {
GRConstants result;
int id;
OleDbDataReader rs;
TTemplate tptRef;
// Checking if template is valid.
if(!TemplateIsValid()) return ERR_INVALID_TEMPLATE;
// Starting identification process and supplying query template.
result = (GRConstants) _grfingerx.IdentifyPrepare(ref _tpt._tpt,
(int)GRConstants.GR_DEFAULT_CONTEXT);
// error?
if (result < 0) return (int)result;
162 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
// Getting enrolled templates from database.
rs = _DB.getTemplates();
while(rs.Read())
{
// Getting current template from recordset.
tptRef = _DB.getTemplate(rs);
// Comparing current template.
result = (GRConstants) _grfingerx.Identify(ref tptRef._tpt,
ref score,(int)GRConstants.GR_DEFAULT_CONTEXT);
// Checking if query template and the reference template match.
if(result == GRConstants.GR_MATCH)
{
id = _DB.getId(rs);
rs.Close();
return id;
}
else if (result < 0)
{
rs.Close();
return (int)result;
}
}
// Closing recordset.
rs.Close();
return (int)GRConstants.GR_NOT_MATCH;
}
// Check current fingerprint against another one in our database
public int Verify(int id, ref int score) {
TTemplate tptRef;
// Checking if template is valid.
if(!TemplateIsValid()) return ERR_INVALID_TEMPLATE;
// Getting template with the supplied ID from database.
tptRef = _DB.getTemplate(id);
// Checking if ID was found.
if ((tptRef._tpt==null) || (tptRef._size == 0))
{
return ERR_INVALID_ID;
}
// Comparing templates.
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 163
return (int) _grfingerx.Verify(ref _tpt._tpt,ref tptRef._tpt,
ref score, (int)GRConstants.GR_DEFAULT_CONTEXT);
}
// Show GrFinger version and type
public void MessageVersion()
{
byte majorVersion=0,minorVersion=0;
GRConstants result;
string vStr = "";
result = (GRConstants)_grfingerx.GetGrFingerVersion(ref majorVersion,
ref minorVersion);
if(result == GRConstants.GRFINGER_FULL)
vStr = "FULL";
else if(result == GRConstants.GRFINGER_LIGHT)
vStr = "LIGHT";
else if(result == GRConstants.GRFINGER_FREE)
vStr = "FREE";
MessageBox.Show("The GrFinger DLL version is " +
majorVersion + "." + minorVersion + ". \n" +
"The license type is '" + vStr + "'.","GrFinger Version");
}
//Importing necessary HDC functions
[DllImport("user32.dll",EntryPoint="GetDC")]
public static extern IntPtr GetDC(IntPtr ptr);
[DllImport("user32.dll",EntryPoint="ReleaseDC")]
public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDc);
// Database class.
public DBClass _DB;
// The last acquired image.
public TRawImage _raw;
// Reference to main form Image.
public PictureBox _pbPic;
// The template extracted from last acquired image.
private TTemplate _tpt;
// Reference to main form log.
private ListBox _lbLog;
//references Main form Auto Extract Check Box
private CheckBox _cbAutoExtract;
//references Main form Auto Identify Check Box
private CheckBox _cbAutoIdentify;
164 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
//references Main form enroll button
Button _btEnroll;
//references Main form extract button
Button _btExtract;
//references Main form identify button
Button _btIdentify;
//references Main form verify button
Button _btVerify;
// GrFingerX component
AxGrFingerXLib.AxGrFingerXCtrl _grfingerx;
};
Listing 3-2. DBClass.vb
Visual Basic 2005
'-------------------------------------------------------------------------------
'GrFinger Sample
'(c) 2005 Griaule Tecnologia Ltda.
'http://www.griaule.com
'-------------------------------------------------------------------------------
'
'This sample is provided with "GrFinger Fingerprint Recognition Library" and
'can't run without it. It's provided just as an example of using GrFinger
'Fingerprint Recognition Library and should not be used as basis for any
'commercial product.
'
'Griaule Tecnologia makes no representations concerning either the merchantability
'of this software or the suitability of this sample for any particular purpose.
'
'THIS SAMPLE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
'IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
'OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
'IN NO EVENT SHALL GRIAULE BE LIABLE FOR ANY DIRECT, INDIRECT,
'INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
'NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
'DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
'THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
'(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
'THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'
'You can download the free version of GrFinger directly from Griaule website.
'
'These notices must be retained in any copies of any part of this
'documentation and/or sample.
'
'-------------------------------------------------------------------------------
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 165
' --------------------------------------------------------------------------------
' Database routines
' --------------------------------------------------------------------------------
Imports System.Data.OleDb
Imports System.Runtime.InteropServices
' Template data
Public Class TTemplate
' Template itself
Public tpt As System.Array = Array.CreateInstance(GetType(Byte), _
GrFingerXLib.GRConstants.GR_MAX_SIZE_TEMPLATE)
' Template size
Public Size As Long
End Class
' Template list
Public Structure TTemplates
' ID
Public ID As Integer
' Template itself
Public template As TTemplate
End Structure
Public Class DBClass
' the database we'll be connecting to
Const DBFile As String = "GrFingerSample.mdb"
Const ConnectionString As String = _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
' the connection object
Dim connection As New OleDbConnection
' Open connection
Public Function OpenDB() As Boolean
Dim filePath As String
Try
filePath = Application.StartupPath() & "\" & DBFile
connection = New OleDb.OleDbConnection(ConnectionString & filePath)
Return True
Catch
Return False
End Try
End Function
166 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
' Close conection
Public Sub closeDB()
connection.Close()
End Sub
' Clear database
Public Sub clearDB()
Dim sqlCMD As OleDbCommand = _
New OleDbCommand("DELETE FROM enroll", connection)
' run "clear" query
sqlCMD.Connection.Open()
sqlCMD.ExecuteNonQuery()
sqlCMD.Connection.Close()
End Sub
' Add template to database. Returns added template ID.
Public Function AddTemplate(ByRef template As TTemplate) As Long
Dim da As New OleDbDataAdapter("select * from enroll", connection)
' Create SQL command containing ? parameter for BLOB.
da.InsertCommand = New OleDbCommand( _
"INSERT INTO enroll (template) Values(?)", connection)
da.InsertCommand.CommandType = CommandType.Text
da.InsertCommand.Parameters.Add("@template", _
OleDbType.Binary, template.Size, "template")
' Open connection
connection.Open()
' Fill DataSet.
Dim enroll As DataSet = New DataSet
da.Fill(enroll, "enroll")
' Add a new row.
' Create parameter for ? contained in the SQL statement.
Dim newRow As DataRow = enroll.Tables("enroll").NewRow()
newRow("template") = template.tpt
enroll.Tables("enroll").Rows.Add(newRow)
' Include an event to fill in the Autonumber value.
AddHandler da.RowUpdated, _
New OleDbRowUpdatedEventHandler(AddressOf OnRowUpdated)
' Update DataSet.
da.Update(enroll, "enroll")
connection.Close()
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 167
' return ID
Return newRow("ID")
End Function
' Event procedure for OnRowUpdated
Private Sub OnRowUpdated(ByVal sender As Object, _
ByVal args As OleDbRowUpdatedEventArgs)
' Include a variable and a command to retrieve identity value
' from Access database.
Dim newID As Integer = 0
Dim idCMD As OleDbCommand = _
New OleDbCommand("SELECT @@IDENTITY", connection)
If args.StatementType = StatementType.Insert Then
' Retrieve identity value and store it in column
newID = CInt(idCMD.ExecuteScalar())
args.Row("ID") = newID
End If
End Sub
' Returns a DataTable with all enrolled templates from database.
Public Function getTemplates() As TTemplates()
Dim ds As New DataSet
Dim da As New OleDbDataAdapter("select * from enroll", connection)
Dim ttpts As TTemplates()
Dim i As Integer
' Get query response
da.Fill(ds)
Dim tpts As DataRowCollection = ds.Tables(0).Rows
' Create response array
ReDim ttpts(tpts.Count)
' No results?
If tpts.Count = 0 Then Return ttpts
' get each template and put results in our array
For i = 1 To tpts.Count
ttpts(i).template = New TTemplate
ttpts(i).ID = tpts.Item(i - 1).Item("ID")
ttpts(i).template.tpt = tpts.Item(i - 1).Item("template")
ttpts(i).template.Size = ttpts(i).template.tpt.Length
Next
Return ttpts
End Function
' Returns template with supplied ID.
Public Function getTemplate(ByVal id As Long) As Byte()
Dim ds As New DataSet
168 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
Dim da As New OleDbDataAdapter( _
"select * from enroll where ID = " & id, connection)
Dim tpt As New TTemplate
' Get query response
da.Fill(ds)
Dim tpts As DataRowCollection = ds.Tables(0).Rows
' No results?
If tpts.Count <> 1 Then Return Nothing
' Deserialize template and return it
Return tpts.Item(0).Item("template")
End Function
End Class
C# 2005
/*
-------------------------------------------------------------------------------
GrFinger Sample
(c) 2005 Griaule Tecnologia Ltda.
http://www.griaule.com
-------------------------------------------------------------------------------
This sample is provided with "GrFinger Fingerprint Recognition Library" and
can't run without it. It's provided just as an example of using GrFinger
Fingerprint Recognition Library and should not be used as basis for any
commercial product.
Griaule Tecnologia makes no representations concerning either the merchantability
of this software or the suitability of this sample for any particular purpose.
THIS SAMPLE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL GRIAULE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You can download the free version of GrFinger directly from Griaule website.
These notices must be retained in any copies of any part of this
documentation and/or sample.
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 169
-------------------------------------------------------------------------------
*/
// -------------------------------------------------------------------------------
// Database routines
// -------------------------------------------------------------------------------
using System;
using System.Data;
using System.Data.OleDb;
using GrFingerXLib;
using System.Runtime.InteropServices;
// the template class
public class TTemplate
{
// Template data.
public System.Array _tpt;
// Template size
public int _size;
public TTemplate(){
// Create a byte buffer for the template
_tpt = new byte[(int)GRConstants.GR_MAX_SIZE_TEMPLATE];
_size = 0;
}
}
// the database class
public class DBClass{
// the connection object
private OleDbConnection _connection;
// temporary template for retrieving data from DB
private TTemplate tptBlob;
// the database we'll be connecting to
public readonly string CONNECTION_STRING =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=GrFingerSample.mdb";
public DBClass(){
}
// Open connection
public bool openDB()
{
170 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
_connection = new OleDbConnection();
_connection.ConnectionString = CONNECTION_STRING;
try{
_connection.Open();
}
catch{
return false;
}
tptBlob = new TTemplate();
return true;
}//END
// Close conection
public bool closeDB()
{
if(_connection.State != ConnectionState.Closed)
_connection.Close();
return true;
}
// Clear database
public bool clearDB()
{
OleDbCommand cmdClear = null;
cmdClear = new OleDbCommand("DELETE FROM enroll", _connection);
// run "clear" query
if(_connection.State == ConnectionState.Open)
cmdClear.ExecuteNonQuery();
return true;
}
// Add template to database. Returns added template ID.
public bool addTemplate(TTemplate tpt,ref int id)
{
OleDbCommand cmdInsert = null;
OleDbParameter dbParamInsert = null;
OleDbCommand cmdSelect = null;
try{
// Create SQL command containing ? parameter for BLOB.
cmdInsert = new OleDbCommand(
"INSERT INTO enroll(template) values(?) ", _connection);
// Create parameter for ? contained in the SQL statement.
System.Byte [] temp = new System.Byte[tpt._size + 1];
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 171
System.Array.Copy(tpt._tpt, 0, temp, 0, tpt._size);
dbParamInsert = new OleDbParameter("@template",
OleDbType.VarBinary, tpt._size,
ParameterDirection.Input, false, 0, 0,"ID",
DataRowVersion.Current, temp);
cmdInsert.Parameters.Add(dbParamInsert);
//execute query
if(_connection.State == ConnectionState.Open)
cmdInsert.ExecuteNonQuery();
}
catch{
return false;
}
try{
// Create SQL command containing ? parameter for BLOB.
cmdSelect = new OleDbCommand(
"SELECT top 1 ID FROM enroll ORDER BY ID DESC", _connection);
id = System.Convert.ToInt32(cmdSelect.ExecuteScalar());
}
catch {
return false;
}
return true;
}
// Returns an OleDbDataReader with all enrolled templates from database.
public OleDbDataReader getTemplates()
{
OleDbCommand cmdGetTemplates;
OleDbDataReader rs;
//setting up command
cmdGetTemplates = new OleDbCommand("SELECT * FROM enroll", _connection);
rs = cmdGetTemplates.ExecuteReader();
return rs;
}
// Returns template with the supplied ID.
public TTemplate getTemplate(int id)
{
172 CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION
OleDbCommand cmd = null;
OleDbDataReader dr = null;
tptBlob._size = 0;
try
{
cmd = new OleDbCommand(System.String.Concat(
"SELECT * FROM enroll WHERE ID = ",
System.Convert.ToString((int)id)), _connection);
dr = cmd.ExecuteReader();
// Get query response
dr.Read();
getTemplate(dr);
dr.Close();
}
catch{
dr.Close();
}
return tptBlob;
}
// Return template data from an OleDbDataReader
public TTemplate getTemplate(OleDbDataReader rs)
{
long readedBytes;
tptBlob._size = 0;
// alloc space
System.Byte[] temp = new System.Byte[
(int)GRConstants.GR_MAX_SIZE_TEMPLATE];
// get bytes
readedBytes = rs.GetBytes(1, 0, temp, 0,temp.Length);
// copy to structure
System.Array.Copy(temp, 0, tptBlob._tpt,0,(int)readedBytes);
// set real size
tptBlob._size = (int)readedBytes;
return tptBlob;
}
// Return enrollment ID from an OleDbDataReader
public int getId(OleDbDataReader rs)
{
return rs.GetInt32(0);
}
}
CHAPTER 3 ■ INCORPORATING FINGERPRINT RECOGNITION INTO YOUR .NET APPLICATION 173


175

تم تعديل هذه المشاركة بواسطة الاخير زمانه في 14 أغسطس 2008 في 08:20

/index.php/topic/264448-%D8%A7%D9%84%D8%A8%D8%AF%D8%A7%D9%8A%D8%A9-%D9%85%D8%B9-%D8%A7%D9%84%D8%A7%D9%86%D8%AF%D8%B1%D9%88%D9%8A%D8%AF/

 

اني وان كنت الاخير زمانه ---- لأتِ بما لم تستطعه الاوائلُ

#5

هذا هو الفصل ، اذا يفيدك أرفعلك الكتاب لأنه أوضح ويحوي على صور،،

المشكلة لا أستطيع رفعه هنا على المنتدى

post-47438-1218691641_thumb.jpg

/index.php/topic/264448-%D8%A7%D9%84%D8%A8%D8%AF%D8%A7%D9%8A%D8%A9-%D9%85%D8%B9-%D8%A7%D9%84%D8%A7%D9%86%D8%AF%D8%B1%D9%88%D9%8A%D8%AF/

 

اني وان كنت الاخير زمانه ---- لأتِ بما لم تستطعه الاوائلُ

#6
اقتباس
المشكلة لا أستطيع رفعه هنا على المنتدى

ايه المشكلة ؟

لو حجمه كبير اضغطه و قسمه الي اجزاء

#7

انا من مصر يا اخى

تستطيع ان ترفع الكتاب على موقع http://rapidshare.com

فهو مجانى وتستطيع تحميل ملفات علية حتى 100 ميجا

#11
اقتباس
لو حجمه كبير اضغطه و قسمه الي اجزاء

جل اخي احمد هذا ما قصدته ، حجم المرفق كبير.

تفضل اخي الكريم

http://rapidshare.com/files/137602779/Apre...n.2007.rar.html

اتمنى ان اكون قدمت مساعدة

/index.php/topic/264448-%D8%A7%D9%84%D8%A8%D8%AF%D8%A7%D9%8A%D8%A9-%D9%85%D8%B9-%D8%A7%D9%84%D8%A7%D9%86%D8%AF%D8%B1%D9%88%D9%8A%D8%AF/

 

اني وان كنت الاخير زمانه ---- لأتِ بما لم تستطعه الاوائلُ

#13

السلام عليكم ورحمة الله وبركاتة

الكتاب يتطلب ملفات

Fingerprint SDK

وذلك لربط جهاز البصمة الخاص بمايكروسوفت ببرنامج على الجهاز

وهذا هو موقع الشركة ولكنة غير مجانى http://www.griaulebiometrics.com/page/en-us/fingerprint_sdk

ارجو المساعدة

#14

أظن ان الموقع مجاني ، قط يحتاج الى تسجيل ،

سجل به ثم بعد ذلك أضغط تحميل.

سجلتُ به وحاولت التحميل لكن خط النت لدي لم يسمح

/index.php/topic/264448-%D8%A7%D9%84%D8%A8%D8%AF%D8%A7%D9%8A%D8%A9-%D9%85%D8%B9-%D8%A7%D9%84%D8%A7%D9%86%D8%AF%D8%B1%D9%88%D9%8A%D8%AF/

 

اني وان كنت الاخير زمانه ---- لأتِ بما لم تستطعه الاوائلُ

#15

مجانى يا اخى لمده 90 يوم فقط اما سعرة فهو 180 دولار

وتستطيع روئية ذلك من ذلك الرابط http://www.griaulebiometrics.com/page/en-us/shopping_cart

#16

السلام عليكم ورحمة الله وبركاته

هذه اول مشاركه لى فى هذا الموقع

يا ريت اللى نزل الكتاب او عنده يرفعه على الموقع او على أى سيرفر حتى يستفيد منه الاخرين

مواضيع مشابهة