예제 #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;
        }
        //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);
        }
예제 #3
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);
                }
            }
        }
        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);
        }
예제 #5
0
파일: LockForm.cs 프로젝트: wwj229/NLock
        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;
        }
예제 #6
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();
        }
    }
예제 #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);
            //    }
            //}
        }
예제 #8
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;
        }