Beispiel #1
0
 static void Main(string[] args)
 {
     String fvc = "FVC2006";
     String db = "Db1_a"; // 1
     String prefix = fvc + "-" + db;
     String pathImage = "E:/College/Semester 7/Tentang TA/Oprek FVC/DVD/"+fvc+"/Dbs/"+db;
     String pathIso = "E:/College/Semester 7/Tentang TA/Oprek FVC/DVD/"+fvc+"/Dbs/Temp-"+db;
     Directory.CreateDirectory(pathIso);
     String[] files = Directory.GetFiles(pathImage);
     int i = 0;
     Stopwatch watch = Stopwatch.StartNew();
     foreach(String uriFp in files){
         try
         {
             Fingerprint fp = new Fingerprint();
             fp.AsBitmapSource = new BitmapImage(new Uri(uriFp, UriKind.RelativeOrAbsolute));
             Person ps = new Person();
             ps.Fingerprints.Add(fp);
             AFIS.Extract(ps);
             File.WriteAllBytes(pathIso + "/" + prefix + "_"+ Path.GetFileNameWithoutExtension(uriFp)+".template", fp.AsIsoTemplate);
             Console.WriteLine("Progress : "+ (((float) (++i)/files.Length) * 100)+" %");
         }catch(Exception ex){
             Console.WriteLine(" Skip!!"+ex.Message);
         }
     }
     watch.Stop();
     String [] lines = new String[1];
     lines[0] = "Time : " + watch.ElapsedMilliseconds + " ms";
     File.AppendAllLines(pathIso + "/properties.txt", lines);
     Console.WriteLine("Time : "+ watch.ElapsedMilliseconds + " ms");
     Console.WriteLine("Done");
 }
Beispiel #2
0
        static void Main(string[] args)
        {
            Person queryPerson = null;
            //  String path = "E:/College/Semester 7/Tentang TA/Oprek FVC/Template/FVC2000/Db1_a/FVC2000-Db1_a_1_1.template";
            String path = "E:/College/Semester 7/Tentang TA/Oprek FVC/Template/Summary/FVC2000-Db1_a_1_1.template";
            queryPerson = SetupQueryPerson(queryPerson,path);

            Fingerprint fp = new Fingerprint();
            Person dataPerson = new Person(fp);
            float verify;

            String fvc = "FVC2000";
            String db = "Db1_a";
            String prefix = fvc + "-" + db;
            //String pathTemplate = "E:/College/Semester 7/Tentang TA/Oprek FVC/Template/" + fvc + "/" + db;
            String pathTemplate = "E:/College/Semester 7/Tentang TA/Oprek FVC/Template/Summary";
            String[] files = Directory.GetFiles(pathTemplate);

            int counter = 0;
            foreach(String uriTmp in files){
                if (!Path.GetFileNameWithoutExtension(uriTmp).Equals("properties"))
                {
                    fp.AsIsoTemplate = File.ReadAllBytes(uriTmp);
                    verify = AFIS.Verify(queryPerson, dataPerson);
                    if(verify!=0)
                        File.AppendAllText("c:/infoPenting",Path.GetFileName(uriTmp) + "\t" + verify+"\n");
                }
                Console.WriteLine("Progress = "+((float) ++counter/files.Length)*100 +" %");
            }
            Console.WriteLine("Done");
            Console.ReadKey();
        }
        public UpdateFingerPrint(uint scannerAddr, string username)
        {
            InitializeComponent();
            lblStatus.Text = String.Empty;
            lblTargetUsername.Text = "Tên người dùng: " + username;

            fingerImageFile = null;

            _person1 = null;
            _person2 = null;

            afis = new AfisEngine();

            cbxFingerPosition.DataSource = FingerPositionDictionary.getList();
            cbxFingerPosition.DisplayMember = "Value";
            cbxFingerPosition.ValueMember = "Key";

            cbxFingerPosition.SelectedIndex = 5;

            _scannerAddr = scannerAddr;

            backgroundWorker.RunWorkerAsync();
        }
        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                Thread.Sleep(500);

                string path = Application.StartupPath;
                BackgroundWorker bw = sender as BackgroundWorker;

                while (true)
                {
                    if (_person1 == null && _person2 == null)
                    {
                        changeLabel("Hãy đặt ngón tay vào máy quét.");

                        _person1 = new Person();

                        string IMGPath = DeviceControl.getImage(_scannerAddr, bw);

                        if (IMGPath == null)
                        {
                            return;
                        }

                        Fingerprint fp = new Fingerprint();
                        fp.AsBitmapSource = new BitmapImage(new Uri(IMGPath, UriKind.RelativeOrAbsolute));

                        _person1.Fingerprints.Add(fp);
                        afis.Extract(_person1);

                        panel1.BackgroundImage = Image.FromFile(IMGPath);
                    }
                    else if (_person1 != null && _person2 == null)
                    {
                        changeLabel("Hãy đặt ngón tay vào máy quét.");

                        _person2 = new Person();

                        string IMGPath = DeviceControl.getImage(_scannerAddr, bw);

                        if (IMGPath == null)
                        {
                            return;
                        }

                        changeLabel("Đang so sánh.");

                        Fingerprint fp = new Fingerprint();
                        fp.AsBitmapSource = new BitmapImage(new Uri(IMGPath, UriKind.RelativeOrAbsolute));

                        _person2.Fingerprints.Add(fp);
                        afis.Extract(_person2);

                        float score = afis.Verify(_person1, _person2);
                        if (score < 25)
                        {
                            _person1 = _person2;
                            _person2 = null;

                            panel1.BackgroundImage = Image.FromFile(IMGPath);

                            changeLabel("Không khớp");
                            Thread.Sleep(2000);
                        }
                        else
                        {
                            fingerImageFile = IMGPath;

                            string selectedValue = "5";
                            cbxFingerPosition.Invoke((MethodInvoker)delegate
                            {
                                selectedValue = cbxFingerPosition.SelectedValue.ToString();
                            });

                            fingerPostition = int.Parse(selectedValue);
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi khi lấy và so sánh ảnh.");
                Log.ErrorLog(ex.Message);
                return;
            }
        }
Beispiel #5
0
 IEnumerable<Person> GetMatchingCandidates(Person[] candidateArray, BestMatchSkipper.PersonsSkipScore[] results)
 {
     foreach (var match in results)
         if (match.Score >= Threshold)
             yield return candidateArray[match.Person];
 }
Beispiel #6
0
 List<Template> FlattenHierarchy(Person[] persons, Finger finger, out List<int> personIndexes)
 {
     List<Template> templates = new List<Template>();
     personIndexes = new List<int>();
     for (int personIndex = 0; personIndex < persons.Length; ++personIndex)
     {
         Person person = persons[personIndex];
         person.CheckForNulls();
         for (int i = 0; i < person.Fingerprints.Count; ++i)
         {
             Fingerprint fingerprint = person.Fingerprints[i];
             if (IsCompatibleFinger(finger, fingerprint.Finger))
             {
                 templates.Add(fingerprint.Decoded);
                 personIndexes.Add(personIndex);
             }
         }
     }
     return templates;
 }
Beispiel #7
0
        /// <summary>
        /// Compute similarity score between two <see cref="Person"/>s.
        /// </summary>
        /// <param name="probe">First of the two persons to compare.</param>
        /// <param name="candidate">Second of the two persons to compare.</param>
        /// <returns>Similarity score indicating similarity between the two persons or 0 if there is no match.</returns>
        /// <remarks>
        /// <para>
        /// <see cref="Verify"/> method compares two <see cref="Person"/>s, <see cref="Fingerprint"/> by <see cref="Fingerprint"/>, and returns
        /// floating-point similarity score that indicates degree of similarity between
        /// the two <see cref="Person"/>s. If this score falls below <see cref="Threshold"/>, <see cref="Verify"/> method returns zero.
        /// </para>
        /// <para>
        /// <see cref="Person"/>s passed to this method must have valid <see cref="Fingerprint.Template"/>
        /// for every <see cref="Fingerprint"/>, i.e. they must have passed through <see cref="Extract"/> method.
        /// </para>
        /// </remarks>
        /// <seealso cref="Threshold"/>
        /// <seealso cref="MinMatches"/>
        /// <seealso cref="Identify"/>
        public float Verify(Person probe, Person candidate)
        {
            lock (this)
            {
                probe.CheckForNulls();
                candidate.CheckForNulls();
                BestMatchSkipper collector = new BestMatchSkipper(1, MinMatches - 1);
                Parallel.ForEach(probe.Fingerprints, probeFp =>
                    {
                        var candidateTemplates = (from candidateFp in candidate.Fingerprints
                                                  where IsCompatibleFinger(probeFp.Finger, candidateFp.Finger)
                                                  select candidateFp.Decoded).ToList();

                        ParallelMatcher.PreparedProbe probeIndex = Matcher.Prepare(probeFp.Decoded);
                        float[] scores = Matcher.Match(probeIndex, candidateTemplates);

                        lock (collector)
                            foreach (float score in scores)
                                collector.AddScore(0, score);
                    });

                return ApplyThreshold(collector.GetSkipScore(0));
            }
        }
Beispiel #8
0
        /// <summary>
        /// Compares one <see cref="Person"/> against a set of other <see cref="Person"/>s and returns best matches.
        /// </summary>
        /// <param name="probe">Person to look up in the collection.</param>
        /// <param name="candidates">Collection of persons that will be searched.</param>
        /// <returns>All matching <see cref="Person"/> objects in the collection or an empty collection if
        /// there is no match. Results are sorted by score in descending order. If you need only one best match,
        /// call <see cref="Enumerable.FirstOrDefault{T}(IEnumerable{T})"/> method on the returned collection.</returns>
        /// <remarks>
        /// <para>
        /// Compares probe <see cref="Person"/> to all candidate <see cref="Person"/>s and returns the most similar
        /// candidates. Calling <see cref="Identify"/> is conceptually identical to calling <see cref="Verify"/> in a loop
        /// except that <see cref="Identify"/> is significantly faster than loop of <see cref="Verify"/> calls.
        /// If there is no candidate with score at or above <see cref="Threshold"/>, <see cref="Identify"/> returns
        /// empty collection.
        /// </para>
        /// <para>
        /// Most applications need only the best match, which can be obtained by calling
        /// <see cref="Enumerable.FirstOrDefault{T}(IEnumerable{T})"/> method on the returned collection.
        /// Matching score for every returned <see cref="Person"/> can be obtained by calling
        /// <see cref="Verify"/> on probe <see cref="Person"/> and the matching <see cref="Person"/>.
        /// </para>
        /// <para>
        /// <see cref="Person"/>s passed to this method must have valid <see cref="Fingerprint.Template"/>
        /// for every <see cref="Fingerprint"/>, i.e. they must have passed through <see cref="Extract"/> method.
        /// </para>
        /// </remarks>
        /// <seealso cref="Threshold"/>
        /// <seealso cref="MinMatches"/>
        /// <seealso cref="Verify"/>
        public IEnumerable<Person> Identify(Person probe, IEnumerable<Person> candidates)
        {
            probe.CheckForNulls();
            Person[] candidateArray = candidates.ToArray();
            BestMatchSkipper.PersonsSkipScore[] results;
            lock (this)
            {
                BestMatchSkipper collector = new BestMatchSkipper(candidateArray.Length, MinMatches - 1);
                Parallel.ForEach(probe.Fingerprints, probeFp =>
                    {
                        List<int> personsByFingerprint = new List<int>();
                        List<Template> candidateTemplates = FlattenHierarchy(candidateArray, probeFp.Finger, out personsByFingerprint);

                        ParallelMatcher.PreparedProbe probeIndex = Matcher.Prepare(probeFp.Decoded);
                        float[] scores = Matcher.Match(probeIndex, candidateTemplates);

                        lock (collector)
                            for (int i = 0; i < scores.Length; ++i)
                                collector.AddScore(personsByFingerprint[i], scores[i]);
                    });
                results = collector.GetSortedScores();
            }
            return GetMatchingCandidates(candidateArray, results);
        }
Beispiel #9
0
 /// <summary>
 /// Extract fingerprint template(s) to be used during matching.
 /// </summary>
 /// <param name="person">Person object to use for template extraction.</param>
 /// <remarks>
 /// <para>
 /// <see cref="Extract"/> method takes <see cref="Fingerprint.Image"/> from every <see cref="Fingerprint"/>
 /// in <paramref name="person"/> and constructs fingerprint template that it stores in
 /// <see cref="Fingerprint.Template"/> property of the respective <see cref="Fingerprint"/>. This step must
 /// be performed before the <see cref="Person"/> is used in <see cref="Verify"/> or <see cref="Identify"/> method,
 /// because matching is done on fingerprint templates, not on fingerprint images.
 /// </para>
 /// <para>
 /// Fingerprint image can be discarded after extraction, but it is recommended
 /// to keep it in case the <see cref="Fingerprint.Template"/> needs to be regenerated due to SourceAFIS
 /// upgrade or other reason.
 /// </para>
 /// </remarks>
 /// <seealso cref="Dpi"/>
 public void Extract(Person person)
 {
     lock (this)
     {
         foreach (Fingerprint fp in person.Fingerprints)
         {
             TemplateBuilder builder = Extractor.Extract(fp.Image, Dpi);
             fp.Decoded = new SerializedFormat().Export(builder);
         }
     }
 }
Beispiel #10
0
 /// <summary>
 /// Create deep copy of the <see cref="Person"/>.
 /// </summary>
 /// <returns>Deep copy of the <see cref="Person"/>.</returns>
 /// <remarks>
 /// This method also clones all <see cref="Fingerprint"/> objects contained
 /// in this <see cref="Person"/>.
 /// </remarks>
 public Person Clone()
 {
     Person clone = new Person();
    // clone.Id = Id;
     foreach (Fingerprint fp in Fingerprints)
         clone.Fingerprints.Add(fp.Clone());
     return clone;
 }
Beispiel #11
0
        /// <summary>
        ///     Verify a candidates fingerprint
        /// </summary>
        /// <param name="c">The candidate to compare against</param>
        /// <param name="fp">The provided fingerprint</param>
        /// <returns>A float from 0 to 100 which represents the strength of the fingerprint match. Higher is better.</returns>
        public static float VerifyFingerprint(Candidate c, Fingerprint fp)
        {
            var afis = new AfisEngine();

            var test = new Person(fp);
            afis.Extract(test);

            var candidate = new Person(c.Fingerprint);

            return afis.Verify(candidate, test);
        }
        public IndexModule()
        {
            Get["/"] = parameters =>
            {
                return View["index"];
            };

            Get["/upload"] = parameters =>
            {
                    return View["upload"];
            };

            Get["/certificate"] = parameters =>
            {
                return View["cert"];
            };

            Get["/result"] = parameters =>
            {
                string enhancedQRCodePath = Path.Combine("data", "qrdata") + @"\" + "EnhancedqrImage.bmp";
                Bitmap QRcodeImage = new Bitmap(Bitmap.FromFile(enhancedQRCodePath));

                Rectangle cropArea = new Rectangle();
                cropArea.Width = 357;
                cropArea.Height = 392;
                cropArea.X = (QRcodeImage.Width - cropArea.Width) / 2;
                cropArea.Y = (QRcodeImage.Height - cropArea.Height) / 2;
                Bitmap bmpCrop = QRcodeImage.Clone(cropArea, QRcodeImage.PixelFormat);

                string rawFPImage = Path.Combine("data", "qrdata") + @"\" + "fingerprint.bmp";
                bmpCrop.Save(rawFPImage);

                LuminanceSource source = new BitmapLuminanceSource(QRcodeImage);
                BinaryBitmap newbitmap = new BinaryBitmap(new HybridBinarizer(source));
                Result result = new MultiFormatReader().decodeWithState(newbitmap);

                if (result.Text != requestTime)
                {
                    return Response.AsJson(new { Result = "Authentication failure" });
                }
                else
                {
                    //Write your code here!(next time!)
                    //return Response.AsJson(new { Result = result.Text });
                }

                return Response.AsImage(rawFPImage);
            };

            Get["/securityUpload"] = parameters =>
            {
                return View["secert"];
            };

            Post["/severification"] = parameters =>
            {
                var file = this.Request.Files.ElementAt<HttpFile>(0);
                string uploadPath = Path.Combine("data", "test", file.Name);
                if (!Directory.Exists(Path.Combine("data", "test"))) Directory.CreateDirectory(Path.Combine("data", "test"));
                using (var fileStream = new FileStream(uploadPath, FileMode.Create))
                {
                    file.Value.CopyTo(fileStream);
                }

                string QRcodePath = Path.Combine("data", "qrdata") + @"\" + "qrImage.bmp";

                Bitmap fpImage = new Bitmap(Bitmap.FromFile(uploadPath));
                Bitmap RawQRImage = new Bitmap(Bitmap.FromFile(QRcodePath));

                Bitmap QRImage = new Bitmap(RawQRImage.Width, RawQRImage.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                using (Graphics g = Graphics.FromImage(QRImage))
                {
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    g.DrawImage(RawQRImage, 0, 0);
                }

                int middleImgW = Math.Min((int)(realSize.Width / 3.5), fpImage.Width);
                int middleImgH = Math.Min((int)(realSize.Height / 3.5), fpImage.Height);
                int middleImgL = (QRImage.Width - middleImgW) / 2;
                int middleImgT = (QRImage.Height - middleImgH) / 2;

                System.Drawing.Graphics MyGraphic = System.Drawing.Graphics.FromImage(QRImage);

                MyGraphic.FillRectangle(Brushes.White, middleImgL, middleImgT, middleImgW, middleImgH);
                MyGraphic.DrawImage(fpImage, middleImgL, middleImgT, middleImgW, middleImgH);

                string enhancedQRCodePath = Path.Combine("data", "qrdata") + @"\" + "EnhancedqrImage.bmp";
                QRImage.Save(enhancedQRCodePath);
                return Response.AsImage(enhancedQRCodePath);
            };

            Get["/barcode"] = parameters =>
            {
                BarcodeWriter writer = new BarcodeWriter();
                writer.Format = BarcodeFormat.QR_CODE;
                writer.Options = new QrCodeEncodingOptions
                {
                    DisableECI = true,
                    CharacterSet = "UTF-8",
                    Width = 1840,
                    Height = 1840,
                    ErrorCorrection = ErrorCorrectionLevel.H
                };
                requestTime = DateTime.Now.ToString();
                Bitmap qrImage = writer.Write(requestTime);

                string path = Path.Combine("data", "qrdata");
                if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                string imagePath = path + @"\" + "qrImage.bmp";
                qrImage.Save(imagePath);

                return Response.AsImage(imagePath);
            };


            Post["/verification"] = parameters =>
            {
                string userId = (string)this.Request.Form.userId;
                List<Model.Fingerprint> fingerprints = SqlHelper.getImages(userId);

                var file = this.Request.Files.ElementAt<HttpFile>(0);
                string uploadPath = Path.Combine("data", "test", file.Name);
                if (!Directory.Exists(Path.Combine("data", "test"))) Directory.CreateDirectory(Path.Combine("data", "test"));
                using (var fileStream = new FileStream(uploadPath, FileMode.Create))
                {
                    file.Value.CopyTo(fileStream);
                }
                SourceAFIS.Simple.Fingerprint fp1 = new SourceAFIS.Simple.Fingerprint();
                fp1.AsBitmap = new Bitmap(Bitmap.FromFile(uploadPath));
                Person person1 = new Person();
                person1.Fingerprints.Add(fp1);
                Afis.Extract(person1);

                List<MatchResult> results = new List<MatchResult>();

                foreach (var fp in fingerprints)
                {
                    SourceAFIS.Simple.Fingerprint fp2 = new SourceAFIS.Simple.Fingerprint();
                    fp2.AsBitmap = new Bitmap(Bitmap.FromFile(fp.fpPath));
                    Person person2 = new Person();
                    person2.Fingerprints.Add(fp2);
                    Afis.Extract(person2);


                    MatchResult result = new MatchResult();
                    result.fingerprint = fp.fpName + fp.sampleNumber.ToString();
                    result.score = Afis.Verify(person1, person2);

                    results.Add(result);
                }

                return Response.AsJson<List<MatchResult>>(results);
            };

            Post["/upload"] = parameters =>
            {
                User user = new User();
                Model.Fingerprint fp1 = new Model.Fingerprint();
                Model.Fingerprint fp2 = new Model.Fingerprint();
                Model.Fingerprint fp3 = new Model.Fingerprint();
                Model.Fingerprint fp4 = new Model.Fingerprint();
                Model.Fingerprint fp5 = new Model.Fingerprint();

                user.userId = (string)this.Request.Form.id;
                user.userName = (string)this.Request.Form.name;                

                fp1.fpName = (string)this.Request.Form.fpname1;
                fp2.fpName = (string)this.Request.Form.fpname2;
                fp3.fpName = (string)this.Request.Form.fpname3;
                fp4.fpName = (string)this.Request.Form.fpname4;
                fp5.fpName = (string)this.Request.Form.fpname5;

                fp1.sampleNumber = (int)this.Request.Form.samplenumber1;
                fp2.sampleNumber = (int)this.Request.Form.samplenumber2;
                fp3.sampleNumber = (int)this.Request.Form.samplenumber3;
                fp4.sampleNumber = (int)this.Request.Form.samplenumber4;
                fp5.sampleNumber = (int)this.Request.Form.samplenumber5;

                fp1.userID = user.userId;
                fp2.userID = user.userId;
                fp3.userID = user.userId;
                fp4.userID = user.userId;
                fp5.userID = user.userId;

                fp1.fpID = fp1.userID + fp1.fpName + fp1.sampleNumber.ToString();
                fp2.fpID = fp1.userID + fp2.fpName + fp2.sampleNumber.ToString();
                fp3.fpID = fp3.userID + fp3.fpName + fp3.sampleNumber.ToString();
                fp4.fpID = fp4.userID + fp4.fpName + fp4.sampleNumber.ToString();
                fp5.fpID = fp5.userID + fp5.fpName + fp5.sampleNumber.ToString();

                var file1 = this.Request.Files.ElementAt<HttpFile>(0);
                var file2 = this.Request.Files.ElementAt<HttpFile>(1);
                var file3 = this.Request.Files.ElementAt<HttpFile>(2);
                var file4 = this.Request.Files.ElementAt<HttpFile>(3);
                var file5 = this.Request.Files.ElementAt<HttpFile>(4);

                fp1.fpPath = @"data\" + user.userName + @"\" + fp1.fpID + file1.Name.Substring(file1.Name.Length -4,  4);
                fp2.fpPath = @"data\" + user.userName + @"\" + fp2.fpID + file2.Name.Substring(file2.Name.Length - 4, 4);
                fp3.fpPath = @"data\" + user.userName + @"\" + fp3.fpID + file3.Name.Substring(file3.Name.Length - 4, 4);
                fp4.fpPath = @"data\" + user.userName + @"\" + fp4.fpID + file4.Name.Substring(file4.Name.Length - 4, 4);
                fp5.fpPath = @"data\" + user.userName + @"\" + fp5.fpID + file5.Name.Substring(file5.Name.Length - 4, 4);

                //fp1.fpPath = Path.Combine("data", user.userName, fp1.fpID + file1.Name.Substring(file1.Name.Length - 4, 4));
                if (!Directory.Exists(Path.Combine("data", user.userName))) Directory.CreateDirectory(Path.Combine("data", user.userName));
                using (var fileStream = new FileStream(fp1.fpPath, FileMode.Create))
                {
                    file1.Value.CopyTo(fileStream);
                }
                using (var fileStream = new FileStream(fp2.fpPath, FileMode.Create))
                {
                    file2.Value.CopyTo(fileStream);
                }
                using (var fileStream = new FileStream(fp3.fpPath, FileMode.Create))
                {
                    file3.Value.CopyTo(fileStream);
                }
                using (var fileStream = new FileStream(fp4.fpPath, FileMode.Create))
                {
                    file4.Value.CopyTo(fileStream);
                }
                using (var fileStream = new FileStream(fp5.fpPath, FileMode.Create))
                {
                    file5.Value.CopyTo(fileStream);
                }

                if (!SqlHelper.isExistUser(user)) SqlHelper.insertToUser(user);
                int i1 = SqlHelper.insertToFingerprint(fp1);
                int i2 = SqlHelper.insertToFingerprint(fp2);
                int i3 = SqlHelper.insertToFingerprint(fp3);
                int i4 = SqlHelper.insertToFingerprint(fp4);
                int i5 = SqlHelper.insertToFingerprint(fp5);
                if (i1!=0 && i2!=0 && i3!=0 && i4!=0 && i5!=0)
                    return Response.AsJson(new { Result = "Insert Sucess" });
                else
                    return Response.AsJson(new { Result = "Insert Failed" });
            };

            Get["/getUser"] = parameters =>
            {
                string myconn = "Database='fingerprint';Data Source=localhost;User ID=lich;Password=123456;CharSet=utf8;";
                string mysql = "SELECT * from user";
                MySqlConnection myconnection = new MySqlConnection(myconn);
                myconnection.Open();
                MySqlCommand mycommand = new MySqlCommand(mysql, myconnection);
                MySqlDataReader myreader = mycommand.ExecuteReader();
                
                
                List<User> userList = new List<User>();
                while (myreader.Read())
                {
                    User user = new User();
                    user.userId = myreader.GetString(0);
                    user.userName = myreader.GetString(1);
                    userList.Add(user);
                }
                myreader.Close();
                myconnection.Close();                
                return Response.AsJson<List<User>>(userList);
            };

            Get["/inserttest"] = parameters =>
            {
                User user = new User();
                user.userId = "13T2001";
                user.userName = "******";
                int i = SqlHelper.insertToUser(user);
                if (i != 0) return Response.AsJson(new { Result = "Insert Sucess" });
                else return Response.AsJson(new { Result = "Insert Failed" });
            };
        }
Beispiel #13
0
 private static Person SetupQueryPerson(Person queryPerson,String path)
 {
     Fingerprint fp = new Fingerprint();
     fp.AsIsoTemplate = File.ReadAllBytes(path);
     return new Person(fp);
 }
Beispiel #14
0
        /// <summary>
        ///     Packs the candidate to a MessagePack objects
        ///     This method should not be called directly, use serialize instead.
        /// </summary>
        /// <param name="packer">The packer</param>
        /// <param name="options">The packer options</param>
        public void PackToMessage(Packer packer, PackingOptions options)
        {
            // pack the header for the amount of items in the map
            packer.PackMapHeader(MapCount);

            packer.Pack("DCS");
            packer.Pack(Dcs);

            packer.Pack("DAC");
            packer.Pack(Dac);

            packer.Pack("DAD");
            packer.Pack(Dad);

            packer.Pack("DBD");
            packer.Pack(Dbd.ToString(DateFormat, CultureInfo.InvariantCulture));

            packer.Pack("DBB");
            packer.Pack(Dbb.ToString(DateFormat, CultureInfo.InvariantCulture));

            packer.Pack("DBC");
            packer.Pack((int) Dbc);

            packer.Pack("DAY");
            packer.Pack(Day.AnsiFormat());

            packer.Pack("DAU");
            packer.Pack(Dau.AnsiFormat);

            packer.Pack("DAG");
            packer.Pack(Dag);

            packer.Pack("DAI");
            packer.Pack(Dai);

            packer.Pack("DAJ");
            packer.Pack(Daj);

            packer.Pack("DAK");
            packer.Pack(Dak.AnsiFormat);

            packer.Pack("DCG");
            packer.Pack(Dcg);

            // pack image
            packer.Pack("ZAA");
            var imageConverter = new ImageConverter();
            packer.Pack((byte[]) imageConverter.ConvertTo(Image, typeof (byte[])));

            // pack fingerprint
            packer.Pack("ZAB");

            if (Fingerprint.Image != null) {
                var afis = new AfisEngine();
                var p = new Person(Fingerprint);
                afis.Extract(p);
            }
            if (Fingerprint.AsIsoTemplate != null) packer.Pack(Fingerprint.AsIsoTemplate);
        }
Beispiel #15
0
        public bool loadData(string Folder_location)
        {
            if (Directory.Exists(Folder_location))
            {
                string myconnectionString = "DataSource=" + Application.StartupPath + "/../../ProjectData.sdf;" + "Password=VuMyc2iFdP0TiDgI7n";
                try
                {
                    Names_List.Clear();
                    Names_List_ID.Clear();
                    trainingImages.Clear();

                    using (SqlCeConnection con = new SqlCeConnection(myconnectionString))
                    {
                        con.Open();
                        using (SqlCeCommand com = new SqlCeCommand("SELECT * from fingerprints", con))
                        {
                            SqlCeDataReader reader = com.ExecuteReader();
                            UnicodeEncoding UE     = new UnicodeEncoding();
                            while (reader.Read())
                            {
                                long            fingerprintId = reader.GetInt64(0);
                                string          path          = reader.GetString(1);
                                string          username      = reader.GetString(2);
                                string          password      = @"cl560Rc9g7ETrT18"; // key for decrypting file
                                byte[]          key           = UE.GetBytes(password);
                                FileStream      fsCrypt       = new FileStream(path, FileMode.Open);
                                RijndaelManaged RMCrypto      = new RijndaelManaged();
                                RMCrypto.BlockSize *= 2;
                                CryptoStream cs = new CryptoStream(fsCrypt,
                                                                   RMCrypto.CreateDecryptor(key, key),
                                                                   CryptoStreamMode.Read);

                                Names_List_ID.Add(Names_List.Count);
                                Names_List.Add(username);
                                Bitmap image = new Bitmap(cs);
                                trainingImages.Add(image);
                                cs.Close();
                                fsCrypt.Close();
                            }
                        }
                    }

                    if (trainingImages.ToArray().Length != 0)
                    {
                        int len = trainingImages.ToArray().Length;
                        Dictionary <string, bool> names = new Dictionary <string, bool>();

                        for (int i = 0; i < len; i++)
                        {
                            if (!names.ContainsKey(Names_List[i]))
                            {
                                names[Names_List[i].ToString()] = true;
                                Recognition.Person      temp       = new Recognition.Person();
                                Recognition.Fingerprint fingertemp = new Recognition.Fingerprint();
                                fingertemp.AsBitmap = (Bitmap)trainingImages[i];
                                temp.Fingerprints.Add(fingertemp);
                                temp.Id = i;
                                fingerTemplates.Add(Names_List[i], temp);
                            }
                            else
                            {
                                Recognition.Fingerprint fingertemp = new Recognition.Fingerprint();
                                fingertemp.AsBitmap = (Bitmap)trainingImages[i];
                                fingerTemplates[Names_List[i]].Fingerprints.Add(fingertemp);
                            }
                        }

                        foreach (var item in fingerTemplates)
                        {
                            afis.Extract(item.Value);
                        }


                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                catch (System.Exception ex)
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
Beispiel #16
0
        //TODO: Abstract CaptureResult so it will work with any fingerprint scanner.
        private void OnCaptured(CaptureResult captureResult)
        {
            browser.GetMainFrame().ExecuteJavaScriptAsync("showPleaseWait();");
            //mark schroeder20170703
            if (PatientBridge.cannotCaptureLeftFingerprint == true)
            {
                Laterality = FHIRUtilities.LateralitySnoMedCode.Right;
            }

            if (currentCaptureInProcess == false)
            {
                if ((PatientBridge.hasValidLeftFingerprint == true && Laterality == FHIRUtilities.LateralitySnoMedCode.Left) || (PatientBridge.hasValidRightFingerprint == true && Laterality == FHIRUtilities.LateralitySnoMedCode.Right))
                {
                    //mark schroeder 20170701 do not capture more left fingerprints if left is set. Same for right
                    return;
                }
                else
                {
                    try
                    {
                        //mark schroeder 20170701 use this to stop more capture attempts while processing. Added to below if statememt
                        currentCaptureInProcess    = true;
                        maxFingerprintScanAttempts = Convert.ToInt16(System.Configuration.ConfigurationManager.AppSettings["maxFingerprintScanAttempts"].ToString());
                        fingerprintScanAttempts++;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        return;
                    }

                    if (_patientBridge.captureSite != FHIRUtilities.CaptureSiteSnoMedCode.Unknown && _patientBridge.laterality != FHIRUtilities.LateralitySnoMedCode.Unknown)
                    {
                        if (fingerprintScanAttempts <= maxFingerprintScanAttempts)
                        {
#if NAVIGATE
                            DisplayOutput("Captured finger image....");
#endif
                            // Check capture quality and throw an error if poor or incomplete capture.
                            if (!biometricDevice.CheckCaptureResult(captureResult))
                            {
                                return;
                            }

                            Constants.CaptureQuality quality = captureResult.Quality;
                            if ((int)quality != 0)
                            {
                                //call javascript to inform UI that the capture quality was too low to accept.
#if NAVIGATE
                                DisplayOutput("Fingerprint quality was too low to accept. Quality = " + quality.ToString());
#endif
                                return;
                            }

                            Type   captureResultType = captureResult.GetType();
                            string deviceClassName   = captureResultType.ToString();
                            string deviceName        = "";
                            if (deviceClassName == "DPUruNet.CaptureResult")
                            {
                                deviceName = "DigitalPersona U.Are.U 4500";
                            }

                            SourceAFIS.Simple.Person currentCapture = new SourceAFIS.Simple.Person();

                            Fingerprint newFingerPrint = new Fingerprint();
                            foreach (Fid.Fiv fiv in captureResult.Data.Views)
                            {
                                newFingerPrint.AsBitmap = ImageUtilities.CreateBitmap(fiv.RawImage, fiv.Width, fiv.Height);
                            }
                            currentCapture.Fingerprints.Add(newFingerPrint);
                            Afis.Extract(currentCapture);
                            Template tmpCurrent = newFingerPrint.GetTemplate();

                            if (_minutiaCaptureController.MatchFound == false)
                            {
                                if (_minutiaCaptureController.AddMinutiaTemplateProbe(tmpCurrent) == true)
                                {
                                    // Good pair found.  Query web service for a match.
                                    FingerPrintMinutias newFingerPrintMinutias = new FingerPrintMinutias
                                                                                     (SessionID, _minutiaCaptureController.BestTemplate1, Laterality, CaptureSite);
                                    PatientBridge.PatientFHIRProfile.AddFingerPrint(newFingerPrintMinutias,
                                                                                    deviceName,
                                                                                    _minutiaCaptureController.BestTemplate1.OriginalDpi,
                                                                                    _minutiaCaptureController.BestTemplate1.OriginalHeight,
                                                                                    _minutiaCaptureController.BestTemplate1.OriginalWidth);

                                    newFingerPrintMinutias = new FingerPrintMinutias
                                                                 (SessionID, _minutiaCaptureController.BestTemplate2, Laterality, CaptureSite);
                                    PatientBridge.PatientFHIRProfile.AddFingerPrint(newFingerPrintMinutias,
                                                                                    deviceName,
                                                                                    _minutiaCaptureController.BestTemplate2.OriginalDpi,
                                                                                    _minutiaCaptureController.BestTemplate2.OriginalHeight,
                                                                                    _minutiaCaptureController.BestTemplate2.OriginalWidth);

                                    Media media = PatientBridge.PatientFHIRProfile.FingerPrintFHIRMedia(newFingerPrintMinutias, deviceName, tmpCurrent.OriginalDpi, tmpCurrent.OriginalHeight, tmpCurrent.OriginalWidth);

                                    // TODO: REMOVE THIS LINE!  ONLY FOR TESTING
                                    //FHIRUtilities.SaveJSONFile(media, @"C:\JSONTest");

                                    HttpsClient    dataTransport = new HttpsClient();
                                    Authentication auth;
                                    if (Utilities.Auth == null)
                                    {
                                        auth = SecurityUtilities.GetAuthentication(NoIDServiceName);
                                    }
                                    else
                                    {
                                        auth = Utilities.Auth;
                                    }
                                    PatientBridge.fhirAddress = new Uri(SearchBiometricsUri);
                                    dataTransport.SendFHIRMediaProfile(PatientBridge.fhirAddress, auth, media);
                                    string lateralityString  = FHIRUtilities.LateralityToString(Laterality);
                                    string captureSiteString = FHIRUtilities.CaptureSiteToString(CaptureSite);
#if NAVIGATE
                                    string output = lateralityString + " " + captureSiteString + " fingerprint accepted. Score = " + _minutiaCaptureController.BestScore + ", Fingerprint sent to server: Response = " + dataTransport.ResponseText;
                                    DisplayOutput(output);
#endif
                                    if (dataTransport.ResponseText.ToLower().Contains("error") == true || dataTransport.ResponseText.ToLower().Contains("index") == true)
                                    {
                                        string message = "Critical Identity Error Occured In Fingerprint Capture method. Please contact your adminstrator: " + dataTransport.ResponseText + " Error code = 909";
                                        MessageBox.Show(message);
                                        browser.GetMainFrame().ExecuteJavaScriptAsync("pageRefresh();");
                                        return;
                                    }
                                    if (dataTransport.ResponseText.ToLower().Contains(@"noid://") == true)
                                    {
                                        // Match found, inform JavaScript that this is an returning patient for Identity.
                                        PatientBridge.PatientFHIRProfile.LocalNoID  = dataTransport.ResponseText;                                         //save the localNoID
                                        PatientBridge.PatientFHIRProfile.NoIDStatus = "Pending";
                                        browser.GetMainFrame().ExecuteJavaScriptAsync("showIdentity('" + PatientBridge.PatientFHIRProfile.LocalNoID + "');");
                                    }
                                    else if (dataTransport.ResponseText.ToLower() == "pending")
                                    {
                                        MessageBox.Show("You are already checked in.  If you believe this is an error, please contact staff");
                                        browser.GetMainFrame().ExecuteJavaScriptAsync("pageRefresh();");
                                        return;
                                    }
                                    else
                                    {
                                        if (PatientBridge.hasValidLeftFingerprint == true)
                                        {
                                            if (MatchLeftAndRight() == true)
                                            {
                                                MessageBox.Show("Both right and left capture sites are the same.  Please start over.");
                                                browser.GetMainFrame().ExecuteJavaScriptAsync("pageRefresh();");
                                                return;
                                            }
                                        }
                                        // Match not found, inform JavaScript the capture pair is complete and the patient can move to the next step.
                                        browser.GetMainFrame().ExecuteJavaScriptAsync("showComplete('" + Laterality.ToString() + "');");
                                        if (Laterality == FHIRUtilities.LateralitySnoMedCode.Left)
                                        {
                                            Laterality  = FHIRUtilities.LateralitySnoMedCode.Right;
                                            CaptureSite = FHIRUtilities.CaptureSiteSnoMedCode.IndexFinger;
                                            _firstMinutiaCaptureController        = _minutiaCaptureController;
                                            _minutiaCaptureController             = new MinutiaCaptureController(_minimumAcceptedMatchScore);
                                            PatientBridge.hasValidLeftFingerprint = true;
                                        }
                                        else if (Laterality == FHIRUtilities.LateralitySnoMedCode.Right)
                                        {
                                            Laterality  = FHIRUtilities.LateralitySnoMedCode.Unknown;
                                            CaptureSite = FHIRUtilities.CaptureSiteSnoMedCode.Unknown;
                                            PatientBridge.hasValidRightFingerprint = true;
                                        }
                                        fingerprintScanAttempts = 0;                                         //reset scan attempt count on successful scan
                                    }
                                }
                                else
                                {
                                    // Good fingerprint pairs not found yet.  inform JavaScript to promt the patient to try again.
                                    browser.GetMainFrame().ExecuteJavaScriptAsync("showFail('" + Laterality.ToString() + "');");
#if NAVIGATE
                                    DisplayOutput("Fingerprint NOT accepted. Score = " + _minutiaCaptureController.BestScore);
#endif
                                    currentCaptureInProcess = false;
                                    return;
                                }
                            }
                        }
                        else
                        {
                            //int testy = CaptureSite.ToString().IndexOf("Thumb");
                            if (CaptureSite.ToString().IndexOf("Thumb") == -1)
                            {
                                browser.GetMainFrame().ExecuteJavaScriptAsync("alert('You have exceeded the maximum allowed scan attempts for your " + Laterality.ToString() + " " + CaptureSite + " Lets try another finger.');");
                            }
                            fingerprintScanAttempts = 0;                             //reset scan attempt count on successful scan
                            //get next laterality and capture site. Order of precedence is left, then right. Index, middle, ring, little, thumb
                            switch (Laterality.ToString() + CaptureSite.ToString())
                            {
                            case "LeftIndexFinger":
                                attemptedScannedFingers.Add(Laterality.ToString() + CaptureSite.ToString());
                                browser.GetMainFrame().ExecuteJavaScriptAsync("setLateralitySite('selectLeftMiddle');");
                                CaptureSite = FHIRUtilities.CaptureSiteSnoMedCode.MiddleFinger;
                                Laterality  = FHIRUtilities.LateralitySnoMedCode.Left;
                                break;

                            case "LeftMiddleFinger":
                                attemptedScannedFingers.Add(Laterality.ToString() + CaptureSite.ToString());
                                browser.GetMainFrame().ExecuteJavaScriptAsync("setLateralitySite('selectLeftRing');");
                                CaptureSite = FHIRUtilities.CaptureSiteSnoMedCode.RingFinger;
                                Laterality  = FHIRUtilities.LateralitySnoMedCode.Left;
                                break;

                            case "LeftRingFinger":
                                attemptedScannedFingers.Add(Laterality.ToString() + CaptureSite.ToString());
                                browser.GetMainFrame().ExecuteJavaScriptAsync("setLateralitySite('selectLeftLittle');");
                                CaptureSite = FHIRUtilities.CaptureSiteSnoMedCode.LittleFinger;
                                Laterality  = FHIRUtilities.LateralitySnoMedCode.Left;
                                break;

                            case "LeftLittleFinger":
                                attemptedScannedFingers.Add(Laterality.ToString() + CaptureSite.ToString());
                                browser.GetMainFrame().ExecuteJavaScriptAsync("setLateralitySite('selectLeftThumb');");
                                CaptureSite = FHIRUtilities.CaptureSiteSnoMedCode.Thumb;
                                Laterality  = FHIRUtilities.LateralitySnoMedCode.Left;
                                break;

                            case "LeftThumb":
                                attemptedScannedFingers.Add(Laterality.ToString() + CaptureSite.ToString());
                                browser.GetMainFrame().ExecuteJavaScriptAsync("moveToRightHandScan();");
                                CaptureSite            = FHIRUtilities.CaptureSiteSnoMedCode.IndexFinger;
                                Laterality             = FHIRUtilities.LateralitySnoMedCode.Right;
                                hasLeftFingerprintScan = false;
                                break;

                            case "RightIndexFinger":
                                hasLeftFingerprintScan = _patientBridge.hasValidLeftFingerprint;
                                attemptedScannedFingers.Add(Laterality.ToString() + CaptureSite.ToString());
                                browser.GetMainFrame().ExecuteJavaScriptAsync("setLateralitySite('selectRightMiddle');");
                                CaptureSite = FHIRUtilities.CaptureSiteSnoMedCode.MiddleFinger;
                                Laterality  = FHIRUtilities.LateralitySnoMedCode.Right;
                                break;

                            case "RightMiddleFinger":
                                attemptedScannedFingers.Add(Laterality.ToString() + CaptureSite.ToString());
                                browser.GetMainFrame().ExecuteJavaScriptAsync("setLateralitySite('selectRightRing');");
                                CaptureSite = FHIRUtilities.CaptureSiteSnoMedCode.RingFinger;
                                Laterality  = FHIRUtilities.LateralitySnoMedCode.Right;
                                break;

                            case "RightRingFinger":
                                attemptedScannedFingers.Add(Laterality.ToString() + CaptureSite.ToString());
                                browser.GetMainFrame().ExecuteJavaScriptAsync("setLateralitySite('selectRightLittle');");
                                CaptureSite = FHIRUtilities.CaptureSiteSnoMedCode.LittleFinger;
                                Laterality  = FHIRUtilities.LateralitySnoMedCode.Right;
                                break;

                            case "RightLittleFinger":
                                attemptedScannedFingers.Add(Laterality.ToString() + CaptureSite.ToString());
                                browser.GetMainFrame().ExecuteJavaScriptAsync("setLateralitySite('selectRightThumb');");
                                CaptureSite = FHIRUtilities.CaptureSiteSnoMedCode.Thumb;
                                Laterality  = FHIRUtilities.LateralitySnoMedCode.Right;
                                break;

                            case "RightThumb":
                                attemptedScannedFingers.Add(Laterality.ToString() + CaptureSite.ToString());
                                hasRightFingerprintScan   = false;
                                _minutiaCaptureController = null;
                                if (hasLeftFingerprintScan == false)
                                {
                                    _firstMinutiaCaptureController = null;
                                }
                                CaptureSite = FHIRUtilities.CaptureSiteSnoMedCode.Unknown;
                                Laterality  = FHIRUtilities.LateralitySnoMedCode.Unknown;
                                browser.GetMainFrame().ExecuteJavaScriptAsync("clickNoRightHandFingerPrint();");
                                break;

                            default:
                                break;
                            }
                            //define walk through fingers and ability to override
                        }
                    }
                    else
                    {
                        if (hasLeftFingerprintScan == true && hasRightFingerprintScan == true)
                        {
                            browser.GetMainFrame().ExecuteJavaScriptAsync("alert('You have successfully completed this step. Please proceed to the next page by clicking the NEXT button below');");
                        }
                        else
                        {
                            browser.GetMainFrame().ExecuteJavaScriptAsync("alert('Must be on the correct page to accept a fingerprint scan. Please follow the instructions on the screen.');");
                        }
#if NAVIGATE
                        DisplayOutput("Must be on the correct page to accept a fingerprint scan.");
#endif
                    }
                    currentCaptureInProcess = false;
                }
            }
            else
            {
                browser.GetMainFrame().ExecuteJavaScriptAsync("alert('Current Scan In Process. Please wait and follow the on screen instructions.');");
            }
        }