Ejemplo 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;
        }
Ejemplo n.º 2
0
        public ScanResult Scan(string referencePath, string candidatePath)
        {
            //SqlLite.Register(biometricClient);

            var reference = CreateSubject(referencePath, false);
            var candidate = CreateSubject(candidatePath, true);
            var result    = new ScanResult(candidatePath);

            _biometricClient.CreateTemplate(reference);
            _biometricClient.CreateTemplate(candidate);

            var task = _biometricClient.CreateTask(NBiometricOperations.Enroll | NBiometricOperations.DetectSegments, null);

            candidate.Id = "Candidate_0";
            task.Subjects.Add(candidate);
            var subjectIndex = 0;

            foreach (var subject in candidate.RelatedSubjects)
            {
                subject.Id = $"Candidate_{++subjectIndex}";
                task.Subjects.Add(subject);
            }
            _biometricClient.PerformTask(task);

            result.Status = _biometricClient.Identify(reference);
            if (reference.MatchingResults.Count > 0)
            {
                var matchingResult = reference.MatchingResults[0];
                result.Score = matchingResult.Score;
                var faceResults = new List <FaceResult>();
                foreach (var face in candidate.Faces)
                {
                    faceResults.AddRange(face.Objects.Select(attributes => new FaceResult(attributes)));
                }
                result.FaceResults = faceResults;
            }

            return(result);
        }
Ejemplo n.º 3
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;
        }
        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);
                    }
        }
Ejemplo n.º 5
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;
        }
Ejemplo n.º 6
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;
        }
Ejemplo n.º 7
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);
            //    }
            //}
        }