Exemplo n.º 1
1
        //private void verify(NImage nImage)
        //{
        //    var biometricClient = new Neurotec.Biometrics.Client.NBiometricClient();
        //    var subject = new NSubject();
        //    var finger = new NFinger { Image = nImage };
        //    subject.Fingers.Add(finger);
        //    //subject.Fingers[0].Image.Save(subject.Fingers[0].Position + ".png");
        //    biometricClient.CreateTemplate(subject);
        //    if (subject.Fingers[0].Objects[0].Template == null)
        //    {
        //        throw new Exception("Template is null");
        //    }
        //    var subject2 = new NSubject();
        //    var finger2 = new NFinger { Image = nImage };
        //    subject2.Fingers.Add(finger2);
        //    //subject.Fingers[0].Image.Save(subject.Fingers[0].Position + ".png");
        //    biometricClient.CreateTemplate(subject2);
        //    if (subject2.Fingers[0].Objects[0].Template == null)
        //    {
        //        throw new Exception("Template2 is null");
        //    }
        //    var status = biometricClient.Verify(subject, subject2);
        //    if (status != NBiometricStatus.Ok)
        //    {
        //        throw new Exception("Verification failed");
        //    }
        //}
        public Dictionary<string, byte[]> GetTemplatesFromWSQImage(int id, byte[] buffer)
        {
            //string dbFingerTable = System.Configuration.ConfigurationManager.AppSettings["dbFingerTable"];
            //string dbFingerColumn = System.Configuration.ConfigurationManager.AppSettings["dbFingerColumn"];
            //string dbIdColumn = System.Configuration.ConfigurationManager.AppSettings["dbIdColumn"];

            ////return;

            //SqlConnection conn = null;
            //SqlConnection conn2 = null;
            //SqlCommand cmd = null;
            //SqlCommand cmd2 = null;
            //SqlDataReader reader = null;

            //NSubject subject;

            //List<WsqImage> fingersCollection = null;
            //ArrayList fingersCollection = null;
            //ArrayList arr = new ArrayList(10);
            //MemoryStream[] ms = new MemoryStream[11];
            //MemoryStream ms;
            //byte[] buffer = new byte[0];
            //int id = 0;
            //int rowNumber = 0;

            //StringBuilder sb = new StringBuilder();
            Dictionary<string, byte[]> templates = new Dictionary<string, byte[]>();
            templates.Add("wsq", buffer);

            Dictionary<int, string> dict = new Dictionary<int, string>();
            dict.Add(0, "li");
            dict.Add(1, "lm");
            dict.Add(2, "lr");
            dict.Add(3, "ll");
            dict.Add(4, "ri");
            dict.Add(5, "rm");
            dict.Add(6, "rr");
            dict.Add(7, "rl");
            dict.Add(8, "lt");
            dict.Add(9, "rt");

            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Binder = new WsqSerializationBinder.MyBinder<WsqImage>();

            //formatter.Binder = new WsqSerializationBinder.GenericBinder<WsqImage>();

            //private NBiometricClient _biometricClient;

            var biometricClient = new NBiometricClient { UseDeviceManager = true, BiometricTypes = NBiometricType.Finger };
            _biometricClient.FingersFastExtraction = true;
            biometricClient.FingersTemplateSize = NTemplateSize.Small;
            biometricClient.FingersQualityThreshold = 48;
            biometricClient.Initialize();

            //Stopwatch sw = new Stopwatch();
            //Stopwatch stwd = new Stopwatch();
            //Stopwatch stws = new Stopwatch();
            //stw.Start();
            //stwd.Start();
            //stws.Start();

            //try
            //{
            //conn = buildConnectionString();
            //var connStr = getConnectionString();
            //conn = new SqlConnection(connStr);
            //conn.Open();
            //conn2 = new SqlConnection(connStr);
            //conn2.Open();
            //cmd = new SqlCommand();
            //cmd.Connection = conn;

            //cmd.CommandText = "SELECT " + dbIdColumn + "," + dbFingerColumn + " FROM " + dbFingerTable + " WHERE AppID = 20095420";

            //cmd.CommandText = "SELECT " + dbIdColumn + "," + dbFingerColumn + " FROM " + dbFingerTable + " WHERE datalength(" + dbFingerColumn + ") IS NOT NULL";
            //cmd.CommandText = String.Format("SELECT AppID, AppWsq FROM (SELECT ROW_NUMBER() OVER(ORDER BY AppID) AS row, AppID, AppWsq FROM Egy_T_FingerPrint WHERE datalength(AppWsq) IS NOT NULL) r WHERE row > {0} and row <= {1}", from, to);
            //cmd.CommandText = String.Format("SELECT AppID, AppWsq FROM Egy_T_FingerPrint WITH (NOLOCK) WHERE datalength(AppWsq) IS NOT NULL ORDER BY AppID ASC OFFSET {0} ROWS FETCH NEXT {1} ROWS ONLY ", from, count);
            //                cmd.CommandText = String.Format("SELECT AppID, AppWsq FROM Egy_T_FingerPrint WITH (NOLOCK) ORDER BY AppID ASC OFFSET {0} ROWS FETCH NEXT {1} ROWS ONLY ", from, count);
            //cmd.CommandText = "SELECT AppID, AppWsq FROM Egy_T_FingerPrint WHERE AppID = 20095423";

            //reader = cmd.ExecuteReader();
            //while (reader.Read())
            //{
            //    rowNumber++;
            //    //                    Console.WriteLine("{0}", rowNumber + from);

            //    if (!reader.IsDBNull(1))
            //    {
            //        id = (int)reader[dbIdColumn];
            //        buffer = (byte[])reader[dbFingerColumn];

            ArrayList fingersCollection = null;

            using (var ms = new MemoryStream(buffer))
            {
                fingersCollection = formatter.Deserialize(ms) as ArrayList;
                //using(MemoryStream memStream = new MemoryStream(100))
                //ms[0] = new MemoryStream(buffer);

            }

            //try
            //{
            //    //stwd.Restart();
            //    fingersCollection = formatter.Deserialize(ms) as ArrayList;
            //    //fingersCollection = formatter.Deserialize(ms[0]) as ArrayList;
            //    //Console.WriteLine("Deserialize ArrayList, Time elapsed: {0}, AppId: {1}", stwd.Elapsed, id);
            //}
            ////catch (Exception ex) { throw new Exception(ex.ToString()); }
            ////catch (Exception) { continue; }
            //finally { ms.Close(); }
            //finally { ms[0].Close(); }

            //if (cmd2 != null)
            //{
            //    cmd2.Dispose();
            //    cmd2 = null;
            //}

            //scontinue;

            //if (sb.Length != 0)
            //    sb.Clear();

            //stws.Restart();
            //String indx = "";

            NSubject subject = new NSubject();

            NImage nImage = null;
            NFinger finger = null;
            //NFRecord template = null;

            for (int i = 0; i < fingersCollection.Count; i++)
            {
                if (fingersCollection[i] != null)
                {
                    try
                    {
                        //ms[i + 1] = new MemoryStream((fingersCollection[i] as WsqImage).Content);
                        //nImage = NImageFormat.Wsq.LoadImage(ms[i + 1]);
                        //nImage = NImage.FromStream(ms[i + 1], NImageFormat.Wsq);
                        nImage = NImage.FromMemory((fingersCollection[i] as WsqImage).Content, NImageFormat.Wsq);

                        finger = new NFinger { Image = nImage };
                        //if (subject.Fingers.Count > 0)
                        //    subject.Fingers.RemoveAt(0);

                        //var subject = new NSubject();
                        subject.Fingers.Add(finger);
                        switch (i)
                        {
                            case 0:
                                finger.Position = NFPosition.LeftIndex;
                                break;
                            case 1:
                                finger.Position = NFPosition.LeftMiddle;
                                break;
                            case 2:
                                finger.Position = NFPosition.LeftRing;
                                break;
                            case 3:
                                finger.Position = NFPosition.LeftLittle;
                                break;
                            case 4:
                                finger.Position = NFPosition.RightIndex;
                                break;
                            case 5:
                                finger.Position = NFPosition.RightMiddle;
                                break;
                            case 6:
                                finger.Position = NFPosition.RightRing;
                                break;
                            case 7:
                                finger.Position = NFPosition.RightLittle;
                                break;
                            case 8:
                                finger.Position = NFPosition.LeftThumb;
                                break;
                            case 9:
                                finger.Position = NFPosition.RightThumb;
                                break;
                        }

                    }
                    catch (Exception)
                    {
                        continue;
                        //throw new Exception(string.Format("Error creating image retrieved from database {0}", ex.Message));
                    }
                    finally
                    {
                        if (finger != null)
                        {
                            finger.Dispose();
                            finger = null;
                        }

                        if (nImage != null)
                        {
                            nImage.Dispose();
                            nImage = null;
                        }

                        //if (ms[i + 1] != null)
                        //{
                        //    ms[i + 1].Close();
                        //    ms[i + 1] = null;
                        //}
                    }
                }
            }

            //sw = System.Diagnostics.Stopwatch.StartNew();
            try
            {
                biometricClient.CreateTemplate(subject);
            }
            catch (Exception ex) {
                while (ex.InnerException != null)
                    ex = ex.InnerException;
                throw new Exception(ex.Message);
            }

            //sw.Stop();
            //TimeSpan ts = sw.Elapsed;
            //string elapsedTime = String.Format("{0:00}.{1:00}", ts.Seconds, ts.Milliseconds / 10);
            //Console.WriteLine("RunTime " + elapsedTime);

            bool valid; NFPosition pos = NFPosition.Unknown; //NFRecord record = null;
            for (int i = 0; i < fingersCollection.Count; i++)
            {
                //indx = "@" + dict[i];

                //if (sb.Length == 0)
                //{
                //    cmd2 = new SqlCommand();
                //    cmd2.Connection = conn2;

                //    sb.Append("update {0} with (serializable) SET ");
                //}
                //else
                //    sb.Append(",");

                //sb.Append(dict[i] + "=" + indx);
                //cmd2.Parameters.Add(indx, SqlDbType.VarBinary);

                //valid = false;

                if (fingersCollection[i] != null)
                {
                    switch (i)
                    {
                        case 0:
                            pos = NFPosition.LeftIndex;
                            break;
                        case 1:
                            pos = NFPosition.LeftMiddle;
                            break;
                        case 2:
                            pos = NFPosition.LeftRing;
                            break;
                        case 3:
                            pos = NFPosition.LeftLittle;
                            break;
                        case 4:
                            pos = NFPosition.RightIndex;
                            break;
                        case 5:
                            pos = NFPosition.RightMiddle;
                            break;
                        case 6:
                            pos = NFPosition.RightRing;
                            break;
                        case 7:
                            pos = NFPosition.RightLittle;
                            break;
                        case 8:
                            pos = NFPosition.LeftThumb;
                            break;
                        case 9:
                            pos = NFPosition.RightThumb;
                            break;
                    }

                    //if (sb.Length == 0)
                    //{
                    //    cmd2 = new SqlCommand();
                    //    cmd2.Connection = conn2;

                    //    sb.Append("update {0} with (serializable) SET ");
                    //}
                    //else
                    //    sb.Append(",");

                    //ms[i + 1] = new MemoryStream();
                    //formatter.Serialize(ms[i + 1], template);

                    //sb.Append(dict[i] + "=" + indx);
                    //cmd2.Parameters.Add(indx, SqlDbType.VarBinary);

                    valid = false;
                    int k = 0;
                    for (k = 0; k < subject.Fingers.Count; k++)
                    {
                        if (subject.Fingers[k].Position == pos)
                        {
                            if (subject.Fingers[k].Objects.First().Status == NBiometricStatus.Ok)
                            {
                                if (subject.Fingers[k].Objects.First().Quality != 254)
                                {
                                    valid = true;
                                    //Console.WriteLine(" ----- Size: {0}", subject.Fingers[k].Objects.First().Template.GetSize());

                                }
                            }

                            break;
                        }
                    }

                    if (!valid)
                    {
                        templates.Add(dict[i], new byte[0]);
                    }
                    else
                    {
                        templates.Add(dict[i], subject.Fingers[k].Objects.First().Template.Save().ToArray());
                        //record = subject.Fingers[k].Objects.First().Template;
                        //cmd2.Parameters[indx].Value = record.Save().ToArray();
                    }
                }
                else
                {
                    templates.Add(dict[i], new byte[0]);
                }
            }

            //try
            //{
            //    var db = new DAO.Database();
            //    db.SaveWSQTemplate(id, templates);
            //}
            //catch (Exception ex)
            //{
            //    throw new Exception(ex.Message);
            //}

            if (subject != null)
                subject.Dispose();

            if (biometricClient != null)
                biometricClient.Dispose();

            if (fingersCollection != null)
            {
                fingersCollection.Clear();
                fingersCollection = null;
            }

            return templates;
        }
Exemplo n.º 2
0
        public EnrollToDatabase(NBiometricStatus status, NSubject subject)
        {
            var biometricClient = new NBiometricClient {
                UseDeviceManager = true
            };
            //database connection through constructor
            Connection con = new Connection(biometricClient);


            //add into database
            NBiometricTask enrollTask =
                biometricClient.CreateTask(NBiometricOperations.Enroll, subject);

            biometricClient.PerformTask(enrollTask);
            status = enrollTask.Status;
            if (status != NBiometricStatus.Ok)
            {
                MessageBox.Show("Enrollment was unsuccessful. status:" + status);
                if (enrollTask.Error != null)
                {
                    throw enrollTask.Error;
                }
                // return -1;
            }
            MessageBox.Show("Enrollment was successful.");
        }
Exemplo n.º 3
0
        private async void MainFormLoadAsync(object sender, EventArgs e)
        {
            _biometricClient = new NBiometricClient
            {
                BiometricTypes           = NBiometricType.Face,
                UseDeviceManager         = true,
                FacesCheckIcaoCompliance = true,
                FacesQualityThreshold    = byte.Parse("0"),
            };

            await _biometricClient.InitializeAsync();

            if (!DesignMode)
            {
                try
                {
                    nViewZoomSlider1.View  = fvPreview;
                    lblStatus.Text         = string.Empty;
                    _deviceManager         = _biometricClient.DeviceManager;
                    saveImageDialog.Filter = NImages.GetSaveFileFilterString();
                    UpdateCameraList();
                }
                catch (Exception ex)
                {
                    Utils.ShowException(ex);
                }
            }
        }
Exemplo n.º 4
0
 public NSubject FingerViewController(NSubject subject, NBiometricClient biometricClient)
 {
     using (biometricClient = new NBiometricClient {
         UseDeviceManager = true
     })
         using (var deviceManager = biometricClient.DeviceManager)
         {
             deviceManager.DeviceTypes = NDeviceType.FingerScanner;
             deviceManager.Initialize();
             biometricClient.FingerScanner = (NFScanner)deviceManager.Devices[0];
             if (biometricClient.FingerScanner == null)
             {
                 MessageBox.Show("Please connect your fingerprint scanner");
             }
             else
             {
                 NFinger subjectFinger = new NFinger();
                 MessageBox.Show("Place your finger on the scanner");
                 subjectFinger.CaptureOptions = NBiometricCaptureOptions.Stream;
                 subject = new NSubject();
                 subject.Fingers.Add(subjectFinger);
             }
         }
     return(subject);
 }
        //Helps to automatically trigger the scanning of next finger if the
        //number of already captured fingers is less than 10
        public void InitNextFingerScan(FingerDescription previousDescription, int previousFingerprintScanPosition)
        {
            _deviceManager = new NDeviceManager();
            if (previousFingerprintScanPosition > 0)
            {
                _fingerprintScanPosition = previousFingerprintScanPosition;
                _FingerDescription       = previousDescription;
            }
            else
            {
                _fingerprintCount = _formMain.GetActiveUserFingerRecordsCount();
                if (_fingerprintCount <= 10)
                {
                    //Get the next finger to be scanned using the previous scanned finger
                    var next = (int)previousDescription;
                    next += 1;
                    _FingerDescription       = (FingerDescription)next;
                    _fingerprintScanPosition = next;
                }
            }

            _biometricClient = new NBiometricClient {
                UseDeviceManager = true, BiometricTypes = NBiometricType.Finger
            };
            _biometricClient.Initialize();

            _EnrollFromSingleFingerScanner = new EnrollFromScanner(this, _CaptureFingerNotifyer, _FingerDescription, _fingerprintScanPosition, _fingerprintCount)
            {
                CaptureFingerNotifyer = _CaptureFingerNotifyer,
                Dock            = DockStyle.Fill,
                BiometricClient = _biometricClient
            };
            Controls.Clear();
            Controls.Add(_EnrollFromSingleFingerScanner);
        }
Exemplo n.º 6
0
        private void FormCapturePhotograph_Load(object sender, EventArgs e)
        {
            try
            {
                _biometricClient = new NBiometricClient {
                    BiometricTypes = NBiometricType.Face, UseDeviceManager = true, FacesCheckIcaoCompliance = true
                };
                _biometricClient.Initialize();

                _enrollFromCamera = new EnrollFromCamera
                {
                    CapturePhotoNotifyer = _CapturePhotoNotifyer,
                    Dock            = DockStyle.Fill,
                    BiometricClient = _biometricClient
                };

                Controls.Add(_enrollFromCamera);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                AppErrorLogger.LogError(ex.StackTrace, ex.Source, ex.Message);
                if (ex.InnerException != null)
                {
                    AppErrorLogger.LogError(ex.StackTrace, ex.Source, ex.Message);
                }
            }
        }
 public BiometriaBuscador()
 {
     _connStr         = ObtenerConexion();
     _biometricClient = new NBiometricClient {
         UseDeviceManager = true, BiometricTypes = NBiometricType.Finger | NBiometricType.Face | NBiometricType.Iris | NBiometricType.Voice
     };
 }
        public VerificationFromDatabase(NSubject subject)
        {
            var biometricClient = new NBiometricClient {
                UseDeviceManager = true
            };
            //database connection through constructor
            Connection con = new Connection(biometricClient);

            NBiometricTask identifyTask = biometricClient.CreateTask(NBiometricOperations.Verify, subject);

            biometricClient.PerformTask(identifyTask);
            NBiometricStatus status = identifyTask.Status;

            if (status != NBiometricStatus.Ok)
            {
                MessageBox.Show("Identification was unsuccessful." + status);
                // Console.ReadLine();
                if (identifyTask.Error != null)
                {
                    throw identifyTask.Error;
                }
                //return -1;
            }

            foreach (var matchingResult in subject.MatchingResults)
            {
                Console.WriteLine("Matched with ID: '{0}' with score {1}", matchingResult.Id, matchingResult.Score);
                MessageBox.Show("Matched with ID: " + matchingResult.Id + " with score: " + matchingResult.Score);
                // Console.ReadLine();
            }
        }
Exemplo n.º 9
0
        public BioProcessor()
        {
            try {
                _biometricClient = new NBiometricClient();
            } catch (Exception ex)
            {
                if (ex.InnerException != null)
                    ex = ex.InnerException;

                throw new Exception(ex.Message);
            }
        }
Exemplo n.º 10
0
        public static void Register(NBiometricClient client)
        {
            string databasePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);

            databasePath = Path.Combine(databasePath, "MugMatcher");
            if (!Directory.Exists(databasePath))
            {
                Directory.CreateDirectory(databasePath);
            }
            databasePath = Path.Combine(databasePath, "MugMatcher.db");

            client.SetDatabaseConnectionToSQLite(databasePath);
        }
        private void FormCaptureSingleScannerFinger_Load(object sender, EventArgs e)
        {
            _biometricClient = new NBiometricClient {
                UseDeviceManager = true, BiometricTypes = NBiometricType.Finger
            };
            _biometricClient.Initialize();
            _EnrollFromSingleFingerScanner = new EnrollFromScanner(this, _CaptureFingerNotifyer, _FingerDescription, _fingerprintScanPosition, _fingerprintCount)
            {
                CaptureFingerNotifyer = _CaptureFingerNotifyer,
                Dock            = DockStyle.Fill,
                BiometricClient = _biometricClient
            };

            Controls.Add(_EnrollFromSingleFingerScanner);
        }
Exemplo n.º 12
0
        private bool CheckDuplicate(FingerImageRecord fRecord)
        {
            try
            {
                if (FingerprintRecords.Count == 0)
                {
                    FingerprintRecords.Add(fRecord);
                    return(true);
                }

                //NBuffer .GetTemplateBuffer()

                using (var biometricClient = new NBiometricClient())
                {
                    // Set matching threshold
                    biometricClient.MatchingThreshold = (int)Settings.Default.MatchingScore;

                    // Set matching speed
                    biometricClient.FingersMatchingSpeed = NMatchingSpeed.Low;

                    var matcherFound = false;
                    FingerprintRecords.ForEach(item =>
                    {
                        if (item.FingerTemplate != null)
                        {
                            var status = biometricClient.Verify(fRecord.FingerSubject, item.FingerSubject);
                            if (status == NBiometricStatus.Ok)
                            {
                                matcherFound = true;
                                item         = fRecord;
                            }
                        }
                    });

                    if (matcherFound)
                    {
                        return(false);
                    }
                    FingerprintRecords.Add(fRecord);
                    return(true);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, @"Process Fingerprint");
                return(false);
            }
        }
Exemplo n.º 13
0
        public IdentificationFromImage(string subjectID, string templateFile)
        {
            string components = "Biometrics.FingerMatching";

            //obtain license

            ControllerUtils.ObtainLicense(components);
            using (var biometricClient = new NBiometricClient())
                // Read template


                using (NSubject subject = CreateSubject(templateFile, subjectID))
                {
                    //Identification done from IdentificationFromDatabase constructor
                    IdentificationFromDatabase identify = new IdentificationFromDatabase(subject);
                }
        }
Exemplo n.º 14
0
        private void ClientInit()
        {
            _biometricClient = new NBiometricClient {
                BiometricTypes = NBiometricType.Face, UseDeviceManager = true
            };
            _biometricClient.Initialize();
            _biometricClient.FacesTemplateSize = NTemplateSize.Small;

            if (!_isSegmentationActivated.HasValue)
            {
                _isSegmentationActivated = NLicense.IsComponentActivated("Biometrics.FaceSegmentsDetection");
            }

            _biometricClient.FacesDetectAllFeaturePoints = _isSegmentationActivated.Value;
            _biometricClient.FacesQualityThreshold       = 50;

            _deviceManager = _biometricClient.DeviceManager;
        }
Exemplo n.º 15
0
        public Verification(string subjectID)
        {
            {
                string fileName = "E:\\Fingerprint sample\\Latest Sample\\Second Template Generated";

                string components = "Biometrics.FingerMatching";
                ControllerUtils.ObtainLicense(components);
                using (var biometricClient = new NBiometricClient())
                    // Read template


                    using (NSubject subject = CreateSubject(fileName, subjectID))
                    {
                        //Identification done from IdentificationFromDatabase constructor
                        VerificationFromDatabase verify = new VerificationFromDatabase(subject);
                    }
            }
        }
Exemplo n.º 16
0
        public EnrollmentFromImage(string subjectID, string imageFile)
        {
            string components = "Biometrics.FingerExtraction";

            //call Obtain License to obtain license
            ControllerUtils.ObtainLicense(components);

            try {
                using (var biometricClient = new NBiometricClient {
                    UseDeviceManager = true
                })
                    // using (var deviceManager = biometricClient.DeviceManager)
                    using (var subject = new NSubject())
                        using (var finger = new NFinger())
                        {
                            finger.FileName = imageFile;
                            subject.Fingers.Add(finger);
                            subject.Id = subjectID; //ID number in the database

                            //Set finger template size (recommended, for enroll to database, is large)
                            biometricClient.FingersTemplateSize = NTemplateSize.Large;

                            NBiometricStatus status = NBiometricStatus.InternalError;

                            //creates template using the image
                            status = biometricClient.CreateTemplate(subject);
                            if (status == NBiometricStatus.Ok)
                            {
                                ControllerUtils.SaveTemplate(subject);

                                //enroll into database using EnrollToDatabase Constructor
                                EnrollToDatabase enrollToDatabase = new EnrollToDatabase(status, subject);
                            }
                            else
                            {
                                Console.WriteLine("Extraction failed! Status: {0}", status);
                            }
                        }
            }catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            // return 0;
        }
Exemplo n.º 17
0
        private void LockFormFormClosed(object sender, FormClosedEventArgs e)
        {
            if (_subject != null)
            {
                _subject.Dispose();
                _subject = null;
            }

            if (_biometricClient != null)
            {
                _biometricClient.Dispose();
                _biometricClient = null;
            }

            Settings.Default.LockFormWidth  = Width;
            Settings.Default.LockFormHeight = Height;
            Settings.Default.Save();
            Settings.Default.Reload();
        }
Exemplo n.º 18
0
 public void FingerViewController(NFingerView fingerView)
 {
     using (var biometricClient = new NBiometricClient {
         UseDeviceManager = true
     })
         using (var deviceManager = biometricClient.DeviceManager)
         {
             deviceManager.DeviceTypes = NDeviceType.FingerScanner;
             deviceManager.Initialize();
             biometricClient.FingerScanner = (NFScanner)deviceManager.Devices[0];
             while (biometricClient.FingerScanner != null)
             {
                 NFinger subjectFinger = new NFinger();
                 MessageBox.Show("Place your finger on the scanner");
                 subjectFinger.CaptureOptions = NBiometricCaptureOptions.Stream;
                 var subject = new NSubject();
                 subject.Fingers.Add(subjectFinger);
             }
         }
 }
Exemplo n.º 19
0
        private async void btnIdentifyFromScanner_Click(object sender, EventArgs e)
        {
            using (var biometricClient = new NBiometricClient {
                UseDeviceManager = true
            })
                using (var deviceManager = biometricClient.DeviceManager)
                {
                    deviceManager.DeviceTypes = NDeviceType.FingerScanner;
                    deviceManager.Initialize();
                    biometricClient.FingerScanner = (NFScanner)deviceManager.Devices[0];
                    if (biometricClient.FingerScanner == null)
                    {
                        MessageBox.Show(@"Please connect a fingerprint scanner");
                    }
                    else
                    {
                        subjectFinger = new NFinger();
                        MessageBox.Show("Place your finger on the scanner");

                        subjectFinger.CaptureOptions = NBiometricCaptureOptions.Stream;

                        subject = new NSubject();
                        subject.Fingers.Add(subjectFinger);

                        subjectFinger.PropertyChanged  += OnAttributesPropertyChanged;
                        FingerViewIdentification.Finger = subjectFinger;

                        FingerViewIdentification.ShownImage = ShownImage.Original;
                        FingerViewIdentification.Show();
                        biometricClient.FingersReturnBinarizedImage = true;

                        NBiometricTask task = biometricClient.CreateTask(NBiometricOperations.Capture /* | NBiometricOperations.CreateTemplate*/, subject);
                        //NBiometricStatus status = biometricClient.Capture(subject);
                        //status = biometricClient.CreateTemplate(subject);
                        var performTask = await biometricClient.PerformTaskAsync(task);

                        // EnrollmentFromScanner enrollmentFromScanner = new EnrollmentFromScanner(subjectID, subject);
                        IdentificationFromScanner identificationByScanner = new IdentificationFromScanner(subjectID, subject);
                    }
                }
        }
Exemplo n.º 20
0
        public Scanner()
        {
            if (!_registered)
            {
                NLicense.ObtainComponents("/local", 5000, BiometricsComponents);
            }
            _registered = true;

            _biometricClient = new NBiometricClient
            {
                MatchingThreshold            = 48,
                FacesMatchingSpeed           = NMatchingSpeed.Low,
                FacesDetectBaseFeaturePoints = true,
                FacesDetectAllFeaturePoints  = true,
                FacesRecognizeEmotion        = true,
                FacesRecognizeExpression     = true,
                FacesDetectProperties        = true,
                FacesDetermineGender         = true,
                FacesDetermineAge            = true
            };
        }
Exemplo n.º 21
0
        private async void MainForm_Load(object sender, EventArgs e)
        {
            if (_args.Count() > 0)
            {
                EstablecerParametros();

                connStr = ObtenerConexion(_verificarHuellaInfo.Servicename);
            }
            else
            {
                MessageBox.Show("No se recibieron los parametros de busqueda");
            }

            _biometricClient = new NBiometricClient {
                UseDeviceManager = true, BiometricTypes = NBiometricType.Face | NBiometricType.Finger | NBiometricType.Iris | NBiometricType.Voice, FacesCheckIcaoCompliance = false
            };

            await _biometricClient.InitializeAsync();

            Inicializar();
        }
Exemplo n.º 22
0
        public VeriEyeProcessorModel()
        {
            if (this.ObtainLicenses())
            {
                this.biometricClient = new NBiometricClient
                {
                    UseDeviceManager = true,
                    CustomDataSchema = NBiographicDataSchema.Parse("(Path string)")
                };
                this.IsProcessorReady = this.ConnectToDB();
                if (!Directory.Exists(this.PathToImages))
                {
                    Directory.CreateDirectory(this.PathToImages);
                }

                if (!Directory.Exists(Path.Combine("IrisDB", "0")))
                {
                    Directory.CreateDirectory(Path.Combine("IrisDB", "0"));
                }
            }
        }
Exemplo n.º 23
0
        static int Main(string[] args)
        {
            Util.PrintTutorialHeader(args);

            if (args.Length < 2)
            {
                return(Usage());
            }

            //=========================================================================
            // CHOOSE LICENCES !!!
            //=========================================================================
            // ONE of the below listed "licenses" lines is required for unlocking this sample's functionality. Choose licenses that you currently have on your device.
            // If you are using a TRIAL version - choose any of them.

            const string licenses = "FingerMatcher, FingerExtractor";

            //const string licenses = "FingerFastMatcher,FaceFastMatcher,IrisFastMatcher,PalmFastMatcher,VoiceFastMatcher";

            //=========================================================================

            //=========================================================================
            // TRIAL MODE
            //=========================================================================
            // Below code line determines whether TRIAL is enabled or not. To use purchased licenses, don't use below code line.
            // GetTrialModeFlag() method takes value from "Bin/Licenses/TrialFlag.txt" file. So to easily change mode for all our examples, modify that file.
            // Also you can just set TRUE to "TrialMode" property in code.

            NLicenseManager.TrialMode = Util.GetTrialModeFlag();

            Console.WriteLine("Trial mode: " + NLicenseManager.TrialMode);

            //=========================================================================

            var anyMatchingComponent = false;

            try
            {
                // Obtain licenses
                foreach (string license in licenses.Split(','))
                {
                    if (NLicense.Obtain("/local", 5000, license))
                    {
                        Console.WriteLine("Obtained license: {0}", license);
                        anyMatchingComponent = true;
                    }
                }
                if (!anyMatchingComponent)
                {
                    throw new NotActivatedException("Could not obtain any matching license");
                }

                using (var biometricClient = new NBiometricClient())
                    // Read probe template
                    using (NSubject probeSubject = CreateSubject(args[0], "ProbeSubject"))
                    {
                        // Read gallery templates and enroll them
                        NBiometricTask enrollTask = biometricClient.CreateTask(NBiometricOperations.Enroll, null);
                        for (int i = 1; i < args.Length; ++i)
                        {
                            enrollTask.Subjects.Add(CreateSubject(args[i], string.Format("GallerySubject_{0}", i)));
                        }
                        biometricClient.PerformTask(enrollTask);
                        NBiometricStatus status = enrollTask.Status;
                        if (status != NBiometricStatus.Ok)
                        {
                            Console.WriteLine("Enrollment was unsuccessful. Status: {0}.", status);
                            if (enrollTask.Error != null)
                            {
                                throw enrollTask.Error;
                            }
                            return(-1);
                        }

                        // Set matching threshold
                        biometricClient.MatchingThreshold = 48;

                        // Set parameter to return matching details
                        biometricClient.MatchingWithDetails = true;

                        // Identify probe subject
                        status = biometricClient.Identify(probeSubject);
                        if (status == NBiometricStatus.Ok)
                        {
                            foreach (var matchingResult in probeSubject.MatchingResults)
                            {
                                Console.WriteLine("Matched with ID: '{0}' with score {1}", matchingResult.Id, matchingResult.Score);
                                if (matchingResult.MatchingDetails != null)
                                {
                                    Console.WriteLine(MatchingDetailsToString(matchingResult.MatchingDetails));
                                }
                            }
                        }
                        else if (status == NBiometricStatus.MatchNotFound)
                        {
                            Console.WriteLine("Match not found!");
                        }
                        else
                        {
                            Console.WriteLine("Identification failed. Status: {0}", status);
                            return(-1);
                        }
                    }

                return(0);
            }
            catch (Exception ex)
            {
                return(Util.PrintException(ex));
            }
        }
Exemplo n.º 24
0
    protected void Page_Load(object sender, EventArgs e)
    {
        const int    Port       = 5000;
        const string Address    = "/local";
        const string Components = "Biometrics.FaceExtraction,Biometrics.FaceMatching,Biometrics.FaceDetection,Devices.Cameras,Biometrics.FaceSegmentsDetection";

        foreach (string component in Components.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
        {
            NLicense.ObtainComponents(Address, Port, component);
        }
        _biometricClient = new NBiometricClient {
            BiometricTypes = NBiometricType.Face, UseDeviceManager = true
        };
        _biometricClient.Initialize();
        this.FileUpload1.Attributes.Add("onchange", "test2();");

        float        item  = _biometricClient.FacesMaximalRoll;
        List <float> items = new List <float>();

        for (float i = 15; i <= 180; i += 15)
        {
            items.Add((i));
        }
        if (!items.Contains(item))
        {
            items.Add(item);
        }
        items.Sort();

        int index = items.IndexOf(item);

        for (int i = 0; i != items.Count; i++)
        {
            cbRollAngle.Items.Add(items[i].ToString());
        }
        cbRollAngle.SelectedIndex = index;

        item = _biometricClient.FacesMaximalYaw;
        items.Clear();
        for (float i = 15; i <= 90; i += 15)
        {
            items.Add((i));
        }
        if (!items.Contains(item))
        {
            items.Add(item);
        }
        items.Sort();

        index = items.IndexOf(item);
        for (int i = 0; i != items.Count; i++)
        {
            cbYawAngle.Items.Add(items[i].ToString());
        }
        cbYawAngle.SelectedIndex = index;
        DataSet set = isLogin(Session["result"]);

        if (set.DataSetName == "result")
        {
            ListView1.DataSource = set;
            ListView1.DataBind();
        }
    }
Exemplo n.º 25
0
 public void Connection(NBiometricClient biometricClient)
 {
     biometricClient.SetDatabaseConnectionToOdbc("Dsn=mssql_dsn;UID=sa;PWD=ddm@TT", "subjects");
 }
Exemplo n.º 26
0
        public int run(int from, int to, int count)
        {
            string dbFingerTable = System.Configuration.ConfigurationManager.AppSettings["dbFingerTable"];
            string dbFingerColumn = System.Configuration.ConfigurationManager.AppSettings["dbFingerColumn"];
            string dbIdColumn = System.Configuration.ConfigurationManager.AppSettings["dbIdColumn"];

            SqlConnection conn = null;
            SqlCommand cmd = null;
            SqlDataReader reader = null;

            int AppId = 0;
            //int rowNumber = 0;

            _biometricClient = new NBiometricClient { UseDeviceManager = true, BiometricTypes = NBiometricType.Finger };
            _biometricClient.Initialize();

            Stopwatch sw = new Stopwatch();

            NSubject subject2 = null;
            int score = 0;
            int numberOfMatches = 0;
            NBiometricStatus status;
            int retcode = 0;

            var fingerArray = new string[2] { "ri", "rm" };

            byte[][] buffer = new byte[2][];

            try
            {
                var connStr = getConnectionString();
                conn = new SqlConnection(connStr);
                conn.Open();
                cmd = new SqlCommand();
                cmd.Connection = conn;

                cmd.CommandText = String.Format("SELECT AppID, {2}, {3} FROM Egy_T_FingerPrint WITH (NOLOCK) WHERE datalength(AppWsq) IS NOT NULL ORDER BY AppID ASC OFFSET {0} ROWS FETCH NEXT {1} ROWS ONLY ", from, count, fingerArray[0], fingerArray[1]);

                reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    if (terminateProcess)
                        break;

                    //rowNumber++;
                    //Console.WriteLine("{0}", rowNumber + from);

                    numberOfMatches = 0;

                    if (!reader.IsDBNull(0))
                    {
                        AppId = reader.GetInt32(0);
                        //Console.WriteLine("{0}", AppId);

                        if (!reader.IsDBNull(1) && ((byte[])reader[fingerArray[0]]).Length > 1)
                        {
                            buffer[0] = (byte[])reader[fingerArray[0]];

                            subject2 = NSubject.FromMemory(buffer[0]);

                            //_biometricClient.MatchingWithDetails = true;

                            //sw.Start();

                            status = _biometricClient.Verify(subject, subject2);

                            //sw.Stop();
                            //Console.WriteLine(" ------------------------- Time elapsed: {0}", sw.Elapsed);

                            if (status == NBiometricStatus.Ok)
                            {
                                score = subject.MatchingResults[0].Score;
                                numberOfMatches++;
                            }

                            subject2.Clear();
                        }

                        if (!reader.IsDBNull(2) && ((byte[])reader[fingerArray[1]]).Length > 1)
                        {
                            buffer[1] = (byte[])reader[fingerArray[1]];

                            subject2 = NSubject.FromMemory(buffer[1]);

                            _biometricClient.MatchingWithDetails = true;
                            status = _biometricClient.Verify(subject, subject2);

                            if (status == NBiometricStatus.Ok)
                            {
                                score = subject.MatchingResults[0].Score;
                                numberOfMatches++;
                            }

                            subject2.Clear();
                        }
                    }

                    if (numberOfMatches == 2)
                    {
                        Console.WriteLine(" ----- AppID: {0}", AppId);
                        retcode = AppId;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                try
                {
                    if (reader != null)
                        reader.Close();

                    if (conn != null && conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                        conn = null;
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }

            return retcode;
        }
Exemplo n.º 27
0
        //public void run(int from, int to, int count, int threadId)
        //public void run(int from, int to)
        public void run(int from, int count)
        {
            string dbFingerTable = System.Configuration.ConfigurationManager.AppSettings["dbFingerTable"];
            string dbFingerColumn = System.Configuration.ConfigurationManager.AppSettings["dbFingerColumn"];
            string dbIdColumn = System.Configuration.ConfigurationManager.AppSettings["dbIdColumn"];

            //return;

            //SqlConnection conn = null;
            //SqlConnection conn2 = null;
            //SqlCommand cmd = null;
            //SqlCommand cmd2 = null;
            //SqlDataReader reader = null;

            NSubject subject;

            //List<WsqImage> fingersCollection = null;
            ArrayList fingersCollection = null;
            //ArrayList arr = new ArrayList(10);
            //MemoryStream[] ms = new MemoryStream[11];
            MemoryStream ms = null;
            //MemoryStream ms;
            byte[] buffer = new byte[0];
            int id = 0;
            int rowNumber = 0;

            StringBuilder sb = new StringBuilder();

            Dictionary<int, string> dict = new Dictionary<int, string>();
            dict.Add(0, "li");
            dict.Add(1, "lm");
            dict.Add(2, "lr");
            dict.Add(3, "ll");
            dict.Add(4, "ri");
            dict.Add(5, "rm");
            dict.Add(6, "rr");
            dict.Add(7, "rl");
            dict.Add(8, "lt");
            dict.Add(9, "rt");

            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Binder = new WsqSerializationBinder.MyBinder<WsqImage>();
            //formatter.Binder = new WsqSerializationBinder.GenericBinder<WsqImage>();

            _biometricClient = new NBiometricClient { UseDeviceManager = true, BiometricTypes = NBiometricType.Finger };
            _biometricClient.FingersFastExtraction = false;
            _biometricClient.FingersTemplateSize = NTemplateSize.Small;
            _biometricClient.FingersQualityThreshold = 48;
            _biometricClient.Initialize();

            Stopwatch sw = new Stopwatch();
            //Stopwatch stwd = new Stopwatch();
            //Stopwatch stws = new Stopwatch();
            //stw.Start();
            //stwd.Start();
            //stws.Start();

            try
            {
                //conn = buildConnectionString();

                var connectionString = getConnectionString();
                connectionString += String.Format(";Max Pool Size={0}", _maxPoolSize);
                using (SqlConnection conn = new SqlConnection(connectionString))
                using (SqlConnection conn2 = new SqlConnection(connectionString))
                {
                    //conn = new SqlConnection(connStr);
                    conn.Open();
                    //conn2 = new SqlConnection(connStr);
                    conn2.Open();
                    SqlCommand cmd = new SqlCommand();
                    cmd.CommandTimeout = 0;
                    cmd.Connection = conn;
                    SqlCommand cmd2 = null;
                    //SqlCommand cmd2 = new SqlCommand();
                    //cmd2.CommandTimeout = 0;
                    //cmd2.Connection = conn2;

                    //cmd.CommandText = "SELECT " + dbIdColumn + "," + dbFingerColumn + " FROM " + dbFingerTable + " WHERE AppID = 20095420";

                    //cmd.CommandText = "SELECT " + dbIdColumn + "," + dbFingerColumn + " FROM " + dbFingerTable + " WHERE datalength(" + dbFingerColumn + ") IS NOT NULL";
                    //cmd.CommandText = String.Format("SELECT AppID, AppWsq FROM (SELECT ROW_NUMBER() OVER(ORDER BY AppID) AS row, AppID, AppWsq FROM Egy_T_FingerPrint WHERE datalength(AppWsq) IS NOT NULL) r WHERE row > {0} and row <= {1}", from, to);
                    //cmd.CommandText = String.Format("SELECT AppID, AppWsq FROM Egy_T_FingerPrint WITH (NOLOCK) WHERE datalength(AppWsq) IS NOT NULL ORDER BY AppID ASC OFFSET {0} ROWS FETCH NEXT {1} ROWS ONLY ", from, count);
                    cmd.CommandText = String.Format("SELECT AppID, AppWsq FROM Egy_T_FingerPrint WITH (NOLOCK) ORDER BY AppID ASC OFFSET {0} ROWS FETCH NEXT {1} ROWS ONLY ", from, count);
                    //cmd.CommandText = "SELECT AppID, AppWsq FROM Egy_T_FingerPrint WHERE AppID = 20095423";

                    //sw.Start();
                    //reader = cmd.ExecuteReader();
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            rowNumber++;
                            if (rowNumber % 10 == 0)
                            {
                                //Console.WriteLine("{0} ----- Time elapsed: {1}", rowNumber + from, sw.Elapsed);
                                Console.WriteLine("{0}", rowNumber + from);
                                //Console.WriteLine(" ----- Time elapsed: {0}", sw.Elapsed);
                                //sw.Restart();
                            }

                            //continue;

                            if (!reader.IsDBNull(1))
                            {
                                id = (int)reader[dbIdColumn];
                                buffer = (byte[])reader[dbFingerColumn];
                                ms = new MemoryStream(buffer);
                                //ms[0] = new MemoryStream(buffer);

                                try
                                {
                                    //stwd.Restart();
                                    fingersCollection = formatter.Deserialize(ms) as ArrayList;
                                    //fingersCollection = formatter.Deserialize(ms[0]) as ArrayList;
                                    //Console.WriteLine("Deserialize ArrayList, Time elapsed: {0}, AppId: {1}", stwd.Elapsed, id);
                                }
                                //catch (Exception ex) { throw new Exception(ex.ToString()); }
                                catch (Exception) { continue; }
                                finally { ms.Close(); }
                                //finally { ms[0].Close(); }

                                //if (cmd2 != null)
                                //{
                                //    cmd2.Dispose();
                                //    cmd2 = null;
                                //}
                                //continue;

                                if (sb.Length != 0)
                                    sb.Clear();

                                //stws.Restart();
                                String indx = "";

                                subject = new NSubject();

                                NImage nImage = null;
                                //NFRecord template = null;

                                //continue;

                                //if (id == 20000017)
                                //{
                                //    sw.Start();
                                //    for (int j = 0; j < 100; j++) {

                                //        for (int i = 0; i < fingersCollection.Count; i++)
                                //        {
                                //            if (fingersCollection[i] != null)
                                //            {

                                //                nImage = NImage.FromMemory((fingersCollection[i] as WsqImage).Content, NImageFormat.Wsq);

                                //            }
                                //        }
                                //    }
                                //    Console.WriteLine(" ----- Time elapsed: {0}", sw.Elapsed);

                                //    return;
                                //}

                                for (int i = 0; i < fingersCollection.Count; i++)
                                {
                                    if (fingersCollection[i] != null)
                                    {
                                        try
                                        {
                                            //ms[i + 1] = new MemoryStream((fingersCollection[i] as WsqImage).Content);
                                            //nImage = NImageFormat.Wsq.LoadImage(ms[i + 1]);
                                            //nImage = NImage.FromStream(ms[i + 1], NImageFormat.Wsq);

                                            //break;

                                            //sw.Restart();
                                            nImage = NImage.FromMemory((fingersCollection[i] as WsqImage).Content, NImageFormat.Wsq);
                                            //Console.WriteLine(" ----- Time elapsed: {0}", sw.Elapsed);
                                            //sw.Reset();

                                            //break;

                                            var finger = new NFinger { Image = nImage };
                                            //if (subject.Fingers.Count > 0)
                                            //    subject.Fingers.RemoveAt(0);

                                            //break;

                                            //var subject = new NSubject();
                                            //sw.Restart();
                                            subject.Fingers.Add(finger);
                                            //Console.WriteLine(" ----- Time elapsed: {0}", sw.Elapsed);

                                            //break;

                                            switch (i)
                                            {
                                                case 0:
                                                    finger.Position = NFPosition.LeftIndex;
                                                    break;
                                                case 1:
                                                    finger.Position = NFPosition.LeftMiddle;
                                                    break;
                                                case 2:
                                                    finger.Position = NFPosition.LeftRing;
                                                    break;
                                                case 3:
                                                    finger.Position = NFPosition.LeftLittle;
                                                    break;
                                                case 4:
                                                    finger.Position = NFPosition.RightIndex;
                                                    break;
                                                case 5:
                                                    finger.Position = NFPosition.RightMiddle;
                                                    break;
                                                case 6:
                                                    finger.Position = NFPosition.RightRing;
                                                    break;
                                                case 7:
                                                    finger.Position = NFPosition.RightLittle;
                                                    break;
                                                case 8:
                                                    finger.Position = NFPosition.LeftThumb;
                                                    break;
                                                case 9:
                                                    finger.Position = NFPosition.RightThumb;
                                                    break;
                                            }

                                        }
                                        catch (Exception ex)
                                        {
                                            if (ex.Message.Equals("Operation is not activated"))
                                                throw new Exception(ex.Message);

                                            continue;
                                            //throw new Exception(string.Format("Error creating image retrieved from database {0}", ex.Message));
                                        }
                                        finally
                                        {
                                            if (nImage != null)
                                            {
                                                nImage.Dispose();
                                                nImage = null;
                                            }

                                            //if (ms[i + 1] != null)
                                            //{
                                            //    ms[i + 1].Close();
                                            //    ms[i + 1] = null;
                                            //}
                                        }
                                    }
                                }

                                //continue;

                                //sw = System.Diagnostics.Stopwatch.StartNew();
                                _biometricClient.CreateTemplate(subject);
                                //sw.Stop();
                                //TimeSpan ts = sw.Elapsed;
                                //string elapsedTime = String.Format("{0:00}.{1:00}", ts.Seconds, ts.Milliseconds / 10);
                                //Console.WriteLine("RunTime " + elapsedTime);

                                bool valid; NFPosition pos = NFPosition.Unknown; NFRecord record = null;
                                for (int i = 0; i < fingersCollection.Count; i++)
                                {
                                    indx = "@" + dict[i];

                                    if (sb.Length == 0)
                                    {
                                        //cmd2.Cancel();
                                        cmd2 = new SqlCommand();
                                        cmd2.CommandTimeout = 0;
                                        cmd2.Connection = conn2;

                                        sb.Append("update {0} with (serializable) SET ");
                                    }
                                    else
                                        sb.Append(",");

                                    sb.Append(dict[i] + "=" + indx);
                                    cmd2.Parameters.Add(indx, SqlDbType.VarBinary);

                                    //valid = false;

                                    if (fingersCollection[i] != null)
                                    {
                                        switch (i)
                                        {
                                            case 0:
                                                pos = NFPosition.LeftIndex;
                                                break;
                                            case 1:
                                                pos = NFPosition.LeftMiddle;
                                                break;
                                            case 2:
                                                pos = NFPosition.LeftRing;
                                                break;
                                            case 3:
                                                pos = NFPosition.LeftLittle;
                                                break;
                                            case 4:
                                                pos = NFPosition.RightIndex;
                                                break;
                                            case 5:
                                                pos = NFPosition.RightMiddle;
                                                break;
                                            case 6:
                                                pos = NFPosition.RightRing;
                                                break;
                                            case 7:
                                                pos = NFPosition.RightLittle;
                                                break;
                                            case 8:
                                                pos = NFPosition.LeftThumb;
                                                break;
                                            case 9:
                                                pos = NFPosition.RightThumb;
                                                break;
                                        }

                                        //if (sb.Length == 0)
                                        //{
                                        //    cmd2 = new SqlCommand();
                                        //    cmd2.Connection = conn2;

                                        //    sb.Append("update {0} with (serializable) SET ");
                                        //}
                                        //else
                                        //    sb.Append(",");

                                        //ms[i + 1] = new MemoryStream();
                                        //formatter.Serialize(ms[i + 1], template);

                                        //sb.Append(dict[i] + "=" + indx);
                                        //cmd2.Parameters.Add(indx, SqlDbType.VarBinary);

                                        valid = false;
                                        int k = 0;
                                        for (k = 0; k < subject.Fingers.Count; k++)
                                        {
                                            if (subject.Fingers[k].Position == pos)
                                            {
                                                if (subject.Fingers[k].Objects.First().Status == NBiometricStatus.Ok)
                                                {
                                                    if (subject.Fingers[k].Objects.First().Quality != 254)
                                                    {
                                                        valid = true;
                                                        //Console.WriteLine(" ----- Size: {0}", subject.Fingers[k].Objects.First().Template.GetSize());

                                                    }
                                                }

                                                break;
                                            }
                                        }

                                        if (!valid)
                                            cmd2.Parameters[indx].Value = new byte[0];
                                        else
                                        {
                                            record = subject.Fingers[k].Objects.First().Template;
                                            cmd2.Parameters[indx].Value = record.Save().ToArray();
                                        }
                                    }
                                    else
                                    {
                                        cmd2.Parameters[indx].Value = new byte[0];
                                    }
                                }

                                if (sb.Length != 0)
                                {
                                    sb.Append(" where {1} = @id");
                                    cmd2.CommandText = String.Format(sb.ToString(), dbFingerTable, dbIdColumn);
                                    cmd2.Parameters.Add("@id", SqlDbType.Int);
                                    cmd2.Parameters["@id"].Value = id;

                                    //conn2 = new SqlConnection(getConnectionString());
                                    //conn2.Open();
                                    //cmd2.Connection = MyConnection.Connection2;
                                    cmd2.ExecuteNonQuery();

                                    //cmd2.CommandText = String.Format(@"update {0} with (serializable) SET li = @li
                                    //    where {1} = @id", dbFingerTable, dbIdColumn);
                                }

                                /*
                                                        cmd2.Parameters.Add("@id", SqlDbType.Int);
                                                        cmd2.Parameters["@id"].Value = id;

                                                        cmd2.Parameters.Add("@li", SqlDbType.VarBinary);
                                                        cmd2.Parameters["@li"].Value = arr[0];
                                                        //cmd.Parameters.Add("@lm", SqlDbType.VarBinary);
                                                        //cmd.Parameters["@lm"].Value = arr[1];

                                                        cmd2.ExecuteNonQuery();
                                */
                                //TimeSpan ts = stws.Elapsed;
                                //string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00000000}",
                                //            ts.Hours, ts.Minutes, ts.Seconds,
                                //            ts.Milliseconds);

                                //Console.WriteLine("Serialize WsqImage, Time elapsed: {0}", elapsedTime);

                                //Console.WriteLine("Serialize WsqImage, Time elapsed: {0}", stws.Elapsed);
                                //Console.WriteLine("TaskId: {0}, Serialize WsqImage, Time elapsed: {1}", threadId, stws.ElapsedMilliseconds);
                                //Console.WriteLine("AppId: {0}", id);

                                //arr.Clear();
                                //if (record != null)
                                //{
                                //    record.Dispose();
                                //    record = null;
                                //}

                                subject = null;

                                if (fingersCollection != null)
                                {
                                    fingersCollection.Clear();
                                    fingersCollection = null;
                                }

                                //for (int i = 0; i < 11; i++)
                                //{
                                //    if (ms[i] != null)
                                //    {
                                //        ms[i].Close();
                                //        ms[i] = null;
                                //    }
                                //}

                                //if (id % 10 == 0)
                                //{
                                //    //Console.WriteLine(id);
                                //    Console.WriteLine("Number of Records Retrieved: {0}, Time elapsed: {1}", numRecordsRetrieved, stw.Elapsed);
                                //    //Console.WriteLine("Thread Id: {3], Number of Records Retrieved: {0}, Time elapsed: {1}", numRecordsRetrieved, stw.Elapsed, threadId);
                                //    //stw.Restart();
                                //}
                            }
                        }
                    }
                }
                //Console.WriteLine("From: {0}, To: {1}, Number of Records Retrieved: {2}", from, to, numRecordsRetrieved);
                //Console.WriteLine("Thread Id: {0}, Number of Records Retrieved: {1}, Time elapsed: {2}", threadId, numRecordsRetrieved, stw.Elapsed);

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            //finally
            //{
            //    try
            //    {
            //        if (reader != null)
            //            reader.Close();

            //        if (conn != null && conn.State == ConnectionState.Open)
            //        {
            //            conn.Close();
            //            conn = null;
            //        }

            //        if (conn2 != null && conn2.State == ConnectionState.Open)
            //        {
            //            conn2.Close();
            //            conn2 = null;
            //        }
            //    }
            //    catch (Exception ex)
            //    {
            //        throw new Exception(ex.Message);
            //    }
            //}
        }
Exemplo n.º 28
0
        internal static BiometricsRecord GetBiometricsRecord(BiometricsRecord _BiometricsRecord, string SourceFileDir)
        {
            String userDir = SourceFileDir + "\\" + _BiometricsRecord.EnrollmentId + "\\";

            //Find Images If Exists and Save in Biometrics Record

            //Get Signature
            if (File.Exists(userDir + "sign_image.jpg"))
            {
                byte[] imageBytes = File.ReadAllBytes(userDir + "sign_image.jpg");
                Image image = Image.FromStream(new MemoryStream(imageBytes));
                _BiometricsRecord.Signature = image;
            }

            //Get Photo
            if (File.Exists(userDir + "photo_image.jpg"))
            {
                byte[] imageBytes = File.ReadAllBytes(userDir + "photo_image.jpg");
                Image image = Image.FromStream(new MemoryStream(imageBytes));
                _BiometricsRecord.Photograph = image;
            }

            //Get Photo Template
            if (File.Exists(userDir + "photo_template.tem"))
            {
                byte[] imageBytes = File.ReadAllBytes(userDir + "photo_template.tem");
                _BiometricsRecord.PhotographTemplate = imageBytes;
            }

            //Get Finger Images
            foreach (var fingerDescription in Enum.GetValues(typeof(FingerDescription)))
            {
                string fingerFile = userDir + fingerDescription + ".jpg";
                string fingerTemplateFile = userDir + fingerDescription + ".tem";

                Image image = null;
                if (File.Exists(fingerFile))
                {
                    byte[] imageBytes = File.ReadAllBytes(fingerFile);
                    image = Image.FromStream(new MemoryStream(imageBytes));
                }

                //Get Finger Template
                if (File.Exists(fingerTemplateFile))
                {
                    var imageBytes = File.ReadAllBytes(fingerTemplateFile);
                    var fingerprintBuffer = new NBuffer(imageBytes);

                    //NFinger finger, NBuffer fingerTemplate
                    using (var biometricClient = new NBiometricClient())
                    using (var subject = new NSubject())
                    using (var finger = new NFinger())
                    {
                        //Read finger image from enrollment and add it to NFinger object
                        finger.Image = NImage.FromMemory(fingerprintBuffer, NImageFormat.Wsq);
                        //add NFinger object to NSubject
                        subject.Fingers.Add(finger);
                        ////Set finger template size (recommended, for enroll to database, is large) (optional)
                        //biometricClient.FingersTemplateSize = NTemplateSize.Large;

                        //Create template from added finger image
                        var status = biometricClient.CreateTemplate(subject);
                        if (status == NBiometricStatus.Ok)
                        {
                            _BiometricsRecord.SaveActiveUserFingerRecords(finger, subject, (FingerDescription)fingerDescription);
                        }
                    }
                }
            }
            //Get Grouped Finger Templates
            if (File.Exists(userDir + "fingers_template.tem"))
            {
                byte[] imageBytes = File.ReadAllBytes(userDir + "fingers_template.tem");
                _BiometricsRecord.FingerTemplates = imageBytes;
            }
            return _BiometricsRecord;
        }
        public IdentificationFromScanner(string subjectID, NSubject subject)
        {
            const string components = "Biometrics.FingerExtraction,Biometrics.FingerMatching";

            //Obtain license
            ControllerUtils.ObtainLicense(components);

            using (var biometricClient = new NBiometricClient {
                UseDeviceManager = true
            })
                using (var deviceManager = biometricClient.DeviceManager)
                    // using (var subject = new NSubject())
                    using (var finger = new NFinger())
                    {
                        ////set type of the device used
                        //deviceManager.DeviceTypes = NDeviceType.FingerScanner;
                        ////initialize the NDeviceManager
                        //deviceManager.Initialize();

                        //int i;
                        ////get count of connected devices
                        //int count = deviceManager.Devices.Count;

                        //if (count > 0)
                        //    MessageBox.Show("found " + count + "finger scanners");
                        //else
                        //{
                        //    MessageBox.Show("no finger scanners found, exiting ...\n");
                        //    // return -1;
                        //}
                        ////list detected scanners
                        //if (count > 1)
                        //    MessageBox.Show("Please select finger scanner from the list: ");
                        //for (i = 0; i < count; i++)
                        //{
                        //    NDevice device = deviceManager.Devices[i];
                        //    MessageBox.Show(i + 1 + " " + device.DisplayName);
                        //}
                        ////finger scanner selection by user
                        //if (count > 1)
                        //{
                        //    MessageBox.Show("Please enter finger scanner index: ");
                        //    string line = Console.ReadLine();
                        //    if (line == null) throw new ApplicationException("Nothing read from standard input");
                        //    i = int.Parse(line);
                        //    if (i > count || i < 1)
                        //    {
                        //        MessageBox.Show("Incorrect index provided, exiting ...");
                        //        //return -1;
                        //    }
                        //}
                        //i--;

                        ////set the selected finger scanner as NBiometricClient Finger Scanner
                        //biometricClient.FingerScanner = (NFScanner)deviceManager.Devices[i];

                        ////add NFinger to NSubject
                        //subject.Fingers.Add(finger);
                        //MessageBox.Show("Place your finger on the scanner");
                        ////start capturing
                        //NBiometricStatus status = biometricClient.Capture(subject);
                        //if (status != NBiometricStatus.Ok)
                        //{
                        //    MessageBox.Show("Failed to capture: " + status);
                        //    // return -1;
                        //}
                        //MessageBox.Show("Captured ");
                        //Set finger template size (recommended, for enroll to database, is large) (optional)
                        biometricClient.FingersTemplateSize = NTemplateSize.Large;
                        subject.Id = subjectID;
                        //Create template from added finger image
                        NBiometricStatus status = biometricClient.CreateTemplate(subject);
                        //identification from IdentificationFromDatabase from model class
                        IdentificationFromDatabase idm = new IdentificationFromDatabase(subject);
                    }
        }
Exemplo n.º 30
0
        internal bool SaveBiometricsRecords(BiometricsRecord BiometricsRecord, string DestFileDir)
        {
            NFTemplate _NFTemplate = new NFTemplate();
            //Create Folder for the User
            String userDir = DestFileDir + "\\" + BiometricsRecord.EnrollmentId + "\\";
            if (!Directory.Exists(userDir))
            {
                DirectoryInfo dir = Directory.CreateDirectory(userDir);
            }

            //Save User Signature
            if (BiometricsRecord.Signature != null)
            {
                BiometricsRecord.Signature.Save(userDir + "sign_image.jpg");
            }

            //Save User Photo
            if (BiometricsRecord.Photograph != null)
            {
                BiometricsRecord.Photograph.Save(userDir + "photo_image.jpg");
                File.WriteAllBytes(userDir + "photo_template.tem", BiometricsRecord.PhotographTemplate.ToArray());
            }

            if (BiometricsRecord.FingerprintRecords.Count > 0)
            {
                //save Fingerprint
                foreach (var userFingerprint in BiometricsRecord.FingerprintRecords)
                {
                    userFingerprint.FingerImage.Save(userDir + userFingerprint.FingerDescription + ".jpg");
                    File.WriteAllBytes(userDir + userFingerprint.FingerDescription + ".tem", userFingerprint.FingerTemplate.ToArray());

                    //Add FingerTemplate to NFTemplate

                    if (userFingerprint.FingerRecord != null)
                    {
                        _NFTemplate.Records.Add(userFingerprint.FingerRecord);
                    }
                    else
                    {
                        var wsq = new NBuffer(userFingerprint.FingerWsq);

                        //var image = NImage.FromMemory(wsq, NImageFormat.Wsq).ToBitmap();

                        //NFinger finger, NBuffer fingerTemplate
                        using (var biometricClient = new NBiometricClient())
                        using (var subject = new NSubject())
                        using (var finger = new NFinger())
                        {
                            //Read finger image from enrollment and add it to NFinger object
                            finger.Image = NImage.FromMemory(wsq, NImageFormat.Wsq);
                            //add NFinger object to NSubject
                            subject.Fingers.Add(finger);
                            ////Set finger template size (recommended, for enroll to database, is large) (optional)
                            //biometricClient.FingersTemplateSize = NTemplateSize.Large;

                            //Create template from added finger image
                            var status = biometricClient.CreateTemplate(subject);
                            if (status == NBiometricStatus.Ok)
                            {
                                userFingerprint.FingerRecord = finger.Objects[0].Template;
                                _NFTemplate.Records.Add(finger.Objects[0].Template);
                            }
                        }
                        //NLicense.ReleaseComponents("Biometrics.FingerExtraction");
                    }

                }

                //Save Grouped FingerTemplates
                var ms = new NMemoryStream();
                _NFTemplate.Save(ms);
                BiometricsRecord.FingerTemplates = ms.ToArray();
                File.WriteAllBytes(userDir + "fingers_template.tem", BiometricsRecord.FingerTemplates);

            }

            //Save User Record as Serilalised Binary Data
            BinarySerialization.WriteToBinaryFile(userDir + "UserRecord.crims", BiometricsRecord);

            //If the code runs to this point without Failure, We are good
            return true;
        }