예제 #1
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();
        }
예제 #2
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");
 }
        public string DoFingerPrint(Stream stream)
        {
            AfisEngine Afis = new AfisEngine();

            var fs = new SourceAFIS.Simple.Fingerprint();

            fs.AsBitmap = new System.Drawing.Bitmap(stream);


            var person = new Person();

            person.Fingerprints.Add(fs);

            Afis.Extract(person);

            return(person.Fingerprints[0].AsXmlTemplate.ToString());
        }
예제 #4
0
        static void Main(string[] args)
        {
            //var t = HexString2.Split().Select(s => Convert.ToByte(s, 16)).ToArray();
            var t = StringToByteArray(HexFromTemplate);

            var afisEngine = new AfisEngine();
            var enrollPrint = new Fingerprint { AsIsoTemplate = t };
            var enrollPerson = new Person(enrollPrint);
            var verifyPrint = new Fingerprint { AsIsoTemplate = t };
            var verifyPerson = new Person(verifyPrint);

            var matchScore = afisEngine.Verify(enrollPerson, verifyPerson);

            Console.WriteLine("Template length: {0}", enrollPrint.Template.Length);
            Console.WriteLine("Matching Score: {0}", matchScore);
            Console.WriteLine("Finished");
            Console.ReadLine();
        }
예제 #5
0
        private void SaveFrame_Click(object sender, EventArgs e)
        {
            Recognition.Fingerprint fp1 = new Recognition.Fingerprint();
            fp1.AsBitmap = ((Bitmap)m_picture.Image);
            candidate.Fingerprints.Add(fp1);
            afis.Extract(candidate);

            var user = afis.Identify(candidate, fingerTemplates.Values).FirstOrDefault();

            if (user == null)
            {
                MessageBox.Show("Пользователь не опознан");
            }
            else
            {
                MessageBox.Show("Здравствуйте, " + Names_List[user.Id]);
                mainform.fingerusername = Names_List[user.Id];
            }
        }
예제 #6
0
        public float FullVerifyFromChain([FromBody] JObject json)
        {
            try {
                var data = json.ToObject<CandidateDataObjects.FullVerifyFromChain>();

                using (var ms = new MemoryStream(Convert.FromBase64String(data.FingerprintImageBase64))) {
                    var b = new Bitmap(ms);
                    var f = new Fingerprint {AsBitmap = b};
                    return CandidateDelegate.FullVerifyFromChain(Convert.FromBase64String(data.ChainIdBase64),
                        data.Password, f,
                        Keys.PublicKey(PublicKeyPath));
                }
            }
            catch (Exception e) {
                var resp = new HttpResponseMessage(HttpStatusCode.OK) {
                    Content = new StringContent(JsonConvert.SerializeObject(new ApiError(e.GetType().Name, e.Message))),
                    ReasonPhrase = "Internal Error Occured"
                };
                throw new HttpResponseException(resp);
            }
        }
예제 #7
0
        private void button3_Click(object sender, EventArgs e)
        {
            var connectDialog = new FpsConnectForm();

            Enabled = false;
            var connectDr = connectDialog.ShowDialog(this);
            if (connectDr != DialogResult.OK) button3.Enabled = false;
            connectDialog.Close();
            Enabled = true;

            var f = new Fingerprint();

            if (connectDialog.IsConnected) {
                Enabled = false;

                var scanForm = new ScanFingerForm();
                var dr = scanForm.ShowDialog(this);
                if (dr == DialogResult.OK) {
                    f.AsBitmap = scanForm.Fingerprint;
                }
                scanForm.Dispose();

                Enabled = true;
            }
            else {
                MessageBox.Show(Resources.FPS_NOT_CONNECTED_ERROR);
            }

            float authLikelyhood;
            try {
                authLikelyhood =
                    CandidateDelegate.VerifyFingerprint(CandidateDelegate.Unpack(PackedData, Password, _publicKey), f);
            }
                // ReSharper disable once UnusedVariable
            catch (CryptographicException ex) {
                MessageBox.Show(Resources.NOT_VERIFY_ID_ERROR);
                return;
            }
            MessageBox.Show(Resources.AUTH_LIKLEYHOOD_MESSAGE + authLikelyhood.ToString("R"));
        }
예제 #8
0
파일: Home.cs 프로젝트: Grania/ctm-project
        private void bwLoadFingerPrints_DoWork(object sender, DoWorkEventArgs e)
        {
            if (fingerPrintDB != null)
            {
                e.Cancel = true;
                return;
            }
            fingerPrintDB = new List<Customer>();

            if (AccountManage.customerDT == null)
            {
                AccountManage.customerDT = new CustomerTableAdapter().GetData();
            }
            foreach (DataRow row in AccountManage.customerDT.Rows)
            {
                if (row.Field<bool>("IsActive") && row.Field<byte[]>("FingerPrintIMG") != null
                    && row.Field<string>("TypeShortName") != "DF")
                {
                    Customer customer = new Customer()
                    {
                        Username = row.Field<string>("Username"),
                        TypetShortName = row.Field<string>("TypeShortName"),
                        MealValue = row.Field<int>("MealValue"),
                        CanDebt = row.Field<bool>("CanDebt"),
                        CanEatMore = row.Field<bool>("CanEatMore"),
                        MoreMealValue = row.Field<int?>("MoreMealValue")
                    };
                    Fingerprint fp = new Fingerprint();
                    MemoryStream ms = new MemoryStream(row.Field<byte[]>("FingerPrintIMG"));
                    Image returnImage = Image.FromStream(ms);
                    fp.AsBitmap = (Bitmap)returnImage;
                    customer.Fingerprints.Add(fp);
                    afis.Extract(customer);

                    fingerPrintDB.Add(customer);
                }
            }

            e.Result = e.Argument;
        }
예제 #9
0
파일: Home.cs 프로젝트: Grania/ctm-project
        private void bwStart_DoWork(object sender, DoWorkEventArgs e)
        {
            DeviceModel device = e.Argument as DeviceModel;

            try
            {
                string path = Application.StartupPath;
                BackgroundWorker bw = device.backgroundWokder;

                if (device.scheduleMealSetDetailID != null)
                {
                    DeviceControl.setLCDText(device.serial, "Phuc vu suat: " + device.mealSetLabel.ToString());
                }
                else
                {
                    DeviceControl.setLCDText(device.serial, "Phuc vu suat\ntu do");
                }

                while (true)
                {
                    Customer cus = new Customer();

                    string IMGPath = DeviceControl.getImage(device.scannerAddress, bw);

                    if (bw.CancellationPending)
                    {
                        DeviceControl.setLCDText(device.serial, "Da dung lai.");
                    }

                    if (IMGPath == null)
                    {
                        return;
                    }

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

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

                    Customer matchCus = afis.Identify(cus, fingerPrintDB).FirstOrDefault() as Customer;

                    if (matchCus == null)
                    {
                        DeviceControl.setLCDText(device.serial, "Khong tim thay\nvan tay phu hop");
                        Thread.Sleep(500);
                        DeviceControl.setLED(device.serial, 1, true);
                        Thread.Sleep(1500);
                        DeviceControl.setLED(device.serial, 1, false);
                    }
                    else
                    {
                        Bill bill = DataAccess.PayForFood(matchCus, device.eatMoreFlag, device.scheduleMealSetDetailID, device.mealSetName);

                        DeviceControl.setLCDText(device.serial, matchCus.TypetShortName + ":" + matchCus.Username
                            + "\n" + bill.alert);

                        device.eatMoreFlag = false;

                        MainForm.transactionViewForm.AddRow(bill);

                        if (bill.isSuccess)
                        {
                            IncreaseTransactinCount();
                            DeviceControl.setLED(device.serial, 2, true);
                        }
                        else
                        {
                            DeviceControl.setLED(device.serial, 1, true);
                        }

                        Thread.Sleep(1500);

                        if (bill.isSuccess)
                        {
                            DeviceControl.setLED(device.serial, 2, false);
                        }
                        else
                        {
                            DeviceControl.setLED(device.serial, 1, false);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi khi lấy vân tay.");
                Log.ErrorLog(ex.Message);
                return;
            }
        }
예제 #10
0
 /// <summary>
 /// Create deep copy of the <see cref="Fingerprint"/>.
 /// </summary>
 /// <returns>Deep copy of this <see cref="Fingerprint"/>.</returns>
 public Fingerprint Clone()
 {
     Fingerprint clone = new Fingerprint();
     clone.Image = Image != null ? (byte[,])Image.Clone() : null;
     clone.Decoded = Decoded != null ? Decoded.Clone() : null;
     clone.Finger = Finger;
     return clone;
 }
예제 #11
0
파일: Home.cs 프로젝트: Grania/ctm-project
        public static void LoadCustomerData()
        {
            if (fingerPrintDB == null)
            {
                fingerPrintDB = new List<Customer>();
                lastUpdatedFingerPrintDB = null;
            }

            DataTable customerData;
            if (lastUpdatedFingerPrintDB == null)
            {
                lastUpdatedFingerPrintDB = (DateTime)System.Data.SqlTypes.SqlDateTime.MinValue;
                customerData = new CustomerTableAdapter().GetData();
            }
            else
            {
                customerData = new CustomerTableAdapter().GetDataFromDate(lastUpdatedFingerPrintDB.Value
                , lastUpdatedFingerPrintDB.Value);
            }

            lock (fingerPrintDB)
            {
                foreach (DataRow row in customerData.Rows)
                {
                    DateTime lastUpdated = row.Field<DateTime>("LastUpdated");
                    DateTime? lastUpdatedFingerPrint = row.Field<DateTime?>("LastUpdatedFingerPrint");

                    if (lastUpdated > lastUpdatedFingerPrintDB || lastUpdatedFingerPrint > lastUpdatedFingerPrintDB)
                    {
                        string username = row.Field<string>("Username");
                        bool isActive = row.Field<bool>("IsActive");
                        string typeShortName = row.Field<string>("TypeShortName");

                        int index = 0;
                        bool found = false;
                        for (; index < fingerPrintDB.Count; index++)
                        {
                            if (fingerPrintDB[index].Username == username)
                            {
                                found = true;
                                break;
                            }
                        }

                        if (lastUpdated > lastUpdatedFingerPrintDB)
                        {
                            if (isActive && typeShortName != Customer.DefaultTypeShortName)
                            {
                                int mealValue = row.Field<int>("MealValue");
                                bool canDebt = row.Field<bool>("CanDebt");
                                bool canEatMore = row.Field<bool>("CanEatMore");
                                int? moreMealValue = row.Field<int?>("MoreMealValue");

                                if (found)
                                {
                                    //update customer
                                    fingerPrintDB[index].MealValue = mealValue;
                                    fingerPrintDB[index].CanDebt = canDebt;
                                    fingerPrintDB[index].CanEatMore = canEatMore;
                                    fingerPrintDB[index].MoreMealValue = moreMealValue;
                                }
                                else
                                {
                                    if (lastUpdatedFingerPrint != null)
                                    {
                                        //insert customer
                                        fingerPrintDB.Add(new Customer()
                                        {
                                            Username = username,
                                            TypetShortName = typeShortName,
                                            MealValue = mealValue,
                                            CanDebt = canDebt,
                                            CanEatMore = canEatMore,
                                            MoreMealValue = moreMealValue
                                        });
                                        index = fingerPrintDB.Count - 1;
                                    }
                                }
                            }
                            else
                            {
                                if (found)
                                {
                                    //remove customer
                                    fingerPrintDB.RemoveAt(index);
                                }

                                continue;
                            }
                        }

                        if (lastUpdatedFingerPrint > lastUpdatedFingerPrintDB)
                        {
                            if (found)
                            {
                                Fingerprint fp = new Fingerprint();
                                MemoryStream ms = new MemoryStream(row.Field<byte[]>("FingerPrintIMG"));
                                Image returnImage = Image.FromStream(ms);
                                fp.AsBitmap = (Bitmap)returnImage;

                                fingerPrintDB[index].Fingerprints = new List<Fingerprint>();
                                fingerPrintDB[index].Fingerprints.Add(fp);
                                afis.Extract(fingerPrintDB[index]);
                            }
                        }
                    }
                }

                lastUpdatedFingerPrintDB = XmlSync.GetLastSync();
            }
        }
예제 #12
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);
        }
예제 #13
0
 /// <summary>
 ///     Fully verify a user from a chain. Full verify includes fingerprint, password and signature check
 /// </summary>
 /// <param name="chainId">The id of the chain to verify</param>
 /// <param name="password">The candidates password</param>
 /// <param name="fp">The candidates fingerprint</param>
 /// <param name="publicKey">The public key to verify the data with</param>
 /// <returns>The threshold at which the fingerprint verified</returns>
 public static float FullVerifyFromChain(byte[] chainId, string password, Fingerprint fp, RSAParameters publicKey)
 {
     var packed = GetPackedCandidate(chainId);
     return VerifyFingerprint(Unpack(packed, password, publicKey), fp);
 }
예제 #14
0
        private void updateID_Click(object sender, EventArgs e)
        {
            if (!_c.IsComplete()) {
                MessageBox.Show(
                    Resources
                        .GeneratorForm_uploadBlockchain_Click_Cannot_generate_an_and_ID_for_an_incomplete_candidate_,
                    Resources.ERROR, MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }

            if (string.IsNullOrWhiteSpace(chainId.Text)) {
                MessageBox.Show(Resources.CHAIN_ID_EMPTY, Resources.ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (string.IsNullOrWhiteSpace(password.Text)) {
                MessageBox.Show(Resources.PASSWORD_EMPTY_ERROR, Resources.ERROR, MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }

            if (!password.Text.Equals(confirmPassword.Text)) {
                MessageBox.Show(Resources.PASSWORDS_NOT_MATCH, Resources.ERROR, MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }

            var d = MessageBox.Show(Resources.UPDATE_ID_WARNING, Resources.ARE_YOU_SURE, MessageBoxButtons.YesNo,
                MessageBoxIcon.Question);
            if (d != DialogResult.Yes) return;

            var fp = new Fingerprint();
            if (connectDialog.IsConnected) {
                var scanForm = new ScanFingerForm();
                var dr = scanForm.ShowDialog(this);
                if (dr == DialogResult.OK) {
                    fp.AsBitmap = scanForm.Fingerprint;
                }
                else {
                    scanForm.Dispose();
                    return;
                }

                scanForm.Dispose();
            }
            else {
                MessageBox.Show(Resources.FPS_NOT_CONNECTED_ERROR, Resources.ERROR, MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }
            chainId.Text =
                Convert.ToBase64String(CandidateDelegate.UpdateCandidate(_c, password.Text, fp, PrivateKey,
                    Convert.FromBase64String(chainId.Text)));
            Clipboard.SetText(chainId.Text);
        }
예제 #15
0
        /// <summary>
        ///     - Verifies that we are allowed to update this chain
        ///     - Enrolls a new candidate chain with a CandidateOldVersionRecord referencing the old chain
        ///     - Adds a OldVersionRecord to the old chain referencing the new chain
        ///     - Adds a ChainUpdateRecord to the chain requesting update, forwarding it to the new chain.
        ///     This operation is irreversable.
        /// </summary>
        /// <param name="newCandidate">The updated candidate information</param>
        /// <param name="password">The password provided by the candidate</param>
        /// <param name="fp">The fingerprint to verify against</param>
        /// <param name="privKey">The private key to pack the data with</param>
        /// <param name="chainToUpdate">The chain ID of the chain to be updated</param>
        /// <returns>The chain ID pointing to the updated candidate</returns>
        public static byte[] UpdateCandidate(Candidate newCandidate, string password, Fingerprint fp,
            RSAParameters privKey, byte[] chainToUpdate)
        {
            if (FullVerifyFromChain(chainToUpdate, password, fp, privKey) < 50f)
                throw new AccessConfidenceTooLowException("Access confidence too low to update candidate.");

            var newChainId = EnrollCandidate(newCandidate, password, privKey);

            var ovr = new CandidateOldVersionRecord(chainToUpdate, newChainId);
            var cur = new CandidateUpdatedRecord(chainToUpdate, newChainId);

            var oldRecordEntry = Entry.NewEntry(ovr.Pack(privKey), null, newChainId);
            var newRecordEntry = Entry.NewEntry(cur.Pack(privKey), null, chainToUpdate);

            Entry.CommitEntry(oldRecordEntry, FactomWallet);
            Entry.CommitEntry(newRecordEntry, FactomWallet);

            Thread.Sleep(10100);

            Entry.RevealEntry(oldRecordEntry);
            Entry.RevealEntry(newRecordEntry);

            return newChainId;
        }
예제 #16
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);
            }
        }
        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" }));
                }
            };
        }
예제 #18
0
        /// <summary>
        ///     Unpacks the message from a MessagePack object
        ///     This method should not be called directly, use deserialize instead.
        /// </summary>
        /// <param name="unpacker">The unpacker</param>
        public void UnpackFromMessage(Unpacker unpacker)
        {
            string dcs, dac, dad, dbd, dbb, day, dau, dag, dai, daj, dak, dcg;
            int dbc;

            if (!unpacker.IsMapHeader) throw SerializationExceptions.NewIsNotMapHeader();

            if (UnpackHelpers.GetItemsCount(unpacker) != MapCount)
                throw SerializationExceptions.NewUnexpectedArrayLength(MapCount, UnpackHelpers.GetItemsCount(unpacker));

            for (var i = 0; i < MapCount; i++) {
                string key;

                if (!unpacker.ReadString(out key)) throw SerializationExceptions.NewUnexpectedEndOfStream();

                switch (key) {
                    case "DCS": {
                        if (!unpacker.ReadString(out dcs)) throw SerializationExceptions.NewMissingProperty("dcs");
                        Dcs = dcs;
                        break;
                    }
                    case "DAC": {
                        if (!unpacker.ReadString(out dac)) throw SerializationExceptions.NewMissingProperty("dac");
                        Dac = dac;
                        break;
                    }
                    case "DAD": {
                        if (!unpacker.ReadString(out dad)) throw SerializationExceptions.NewMissingProperty("dad");
                        Dad = dad;
                        break;
                    }
                    case "DBD": {
                        if (!unpacker.ReadString(out dbd)) throw SerializationExceptions.NewMissingProperty("dbd");
                        Dbd = DateTime.Parse(dbd);
                        break;
                    }
                    case "DBB": {
                        if (!unpacker.ReadString(out dbb)) throw SerializationExceptions.NewMissingProperty("dbb");
                        Dbb = DateTime.Parse(dbb);
                        break;
                    }
                    case "DBC": {
                        if (!unpacker.ReadInt32(out dbc)) throw SerializationExceptions.NewMissingProperty("dbc");
                        Dbc = (Sex) dbc;
                        break;
                    }
                    case "DAY": {
                        if (!unpacker.ReadString(out day)) throw SerializationExceptions.NewMissingProperty("day");
                        Day = GetEyeColor(day);
                        break;
                    }
                    case "DAU": {
                        if (!unpacker.ReadString(out dau)) throw SerializationExceptions.NewMissingProperty("dau");
                        Dau = new Height {AnsiFormat = dau};
                        break;
                    }
                    case "DAG": {
                        if (!unpacker.ReadString(out dag)) throw SerializationExceptions.NewMissingProperty("dag");
                        Dag = dag;
                        break;
                    }
                    case "DAI": {
                        if (!unpacker.ReadString(out dai)) throw SerializationExceptions.NewMissingProperty("dai");
                        Dai = dai;
                        break;
                    }
                    case "DAJ": {
                        if (!unpacker.ReadString(out daj)) throw SerializationExceptions.NewMissingProperty("daj");
                        Daj = daj;
                        break;
                    }
                    case "DAK": {
                        if (!unpacker.ReadString(out dak)) throw SerializationExceptions.NewMissingProperty("dak");
                        Dak = new PostalCode {AnsiFormat = dak};
                        break;
                    }
                    case "DCG": {
                        if (!unpacker.ReadString(out dcg)) throw SerializationExceptions.NewMissingProperty("dcg");
                        Dcg = dcg;
                        break;
                    }
                    case "ZAA": {
                        if (!unpacker.Read()) throw SerializationExceptions.NewMissingProperty("zaa");
                        var ms = new MemoryStream(unpacker.LastReadData.AsBinary());
                        Image = Image.FromStream(ms);
                        break;
                    }
                    case "ZAB": {
                        if (!unpacker.Read()) throw SerializationExceptions.NewMissingProperty("zab");
                        Fingerprint = new Fingerprint {AsIsoTemplate = unpacker.LastReadData.AsBinary()};
                        break;
                    }
                }
            }
        }
예제 #19
0
 private static Person SetupQueryPerson(Person queryPerson,String path)
 {
     Fingerprint fp = new Fingerprint();
     fp.AsIsoTemplate = File.ReadAllBytes(path);
     return new Person(fp);
 }
예제 #20
0
//		async  Task<ViewQueryResponse<string>> GetPersonListAsync ()
		async  Task GetPersonListAsync (Container container)
		{
			//List<MyPerson> database = new List<MyPerson>();
			//List<MyPerson> database = FilesService.Database;

			//string sourceDirectory = @"/Users/chrisk/source/KiwiRest/RestFiles/App_Data/files";
			//AfisEngine Afis = new AfisEngine();
			DateTime date1 = DateTime.Now;
			Console.WriteLine("Starting FingerprintDatabase:  " + date1);
//			WebClient client = new WebClient ();
			//string uri = "http://localhost:5984/prints/_all_docs&include_docs=true";
			//			string data = client.DownloadString (uri);
			//			var fromJson = JsonSerializer.DeserializeFromString<AllDocs>(data);
			var myCouchClient = new MyCouch.MyCouchClient("http://localhost:5984/prints");
			ViewQueryResponse<string> result = null;
			try 
			{
				var queryView = new QueryViewRequest("_all_docs");
				queryView.Configure(query => query
					.IncludeDocs(true));
				result = await myCouchClient.Views.QueryAsync<string>(queryView);
				var rows = result.Rows;

//				foreach (ViewQueryResponse<SimpleFingerprint> row in rows)
				foreach (ViewQueryResponse<string,string>.Row row in rows)
				{
					Console.WriteLine("Lookin' at " + row);
					string doc = row.IncludedDoc;
					var person = new MyPerson ();
//					SimpleFingerprint print = TypeSerializer.DeserializeFromString<SimpleFingerprint>(doc);
					var jsonObj = JsonSerializer.DeserializeFromString<JsonObject>(doc);
					person._id = jsonObj["_id"];
					var jsonFingerprints = jsonObj["simpleFingerprint"];
					//var Filename = jsonObj["Filename"];
//					var serialFingerprints = JsonSerializer.DeserializeFromString<List<JsonObject>>(jsonFingerprints);
					var serialFingerprints = JsonArrayObjects.Parse(jsonFingerprints);
					//var fps = JsonSerializer.DeserializeFromString<Dictionary<string, string>>(jsonFingerprints);
					//var fp = JsonSerializer.DeserializeFromString<JsonObject>(jsonObj["simpleFingerprint"]);
					//SimpleFingerprint sf = JsonSerializer.DeserializeFromString<SimpleFingerprint>(jsonObj["simpleFingerprint"]);
					List<Fingerprint> fingerprints = new List<Fingerprint> ();
					foreach (KeyValuePair<string,string> pair in serialFingerprints[0]) {
						Fingerprint simpleFingerprint = new Fingerprint ();
						String value = pair.Value;
						if (value != null)
						{
							char[] delimiterChars = { ':' };
							string[] printPair = value.Split(delimiterChars);
							if (printPair[0] == "Base64Template")
							{
								byte[] printArray = System.Convert.FromBase64String(printPair[1]);
								simpleFingerprint.Template = printArray;
								fingerprints.Add(simpleFingerprint);
							}
						}
						//var print = printPair[1];
						//byte[] printArray = System.Convert.FromBase64String(print);
						//simpleFingerprint.Template = printArray;
//						simpleFingerprint.Filename = Filename;
						//fingerprints.Add(simpleFingerprint);
//						foreach (KeyValuePair<string,string> pair in fprint) {
//							SimpleFingerprint simpleFingerprint = new SimpleFingerprint ();
//							var strBase64Template = JsonSerializer.DeserializeFromString<string>(pair.Key);
////							simpleFingerprint.Base64Template = strBase64Template["Base64Template"];
//							fingerprints.Add(simpleFingerprint);
//						}

					}
//					foreach (KeyValuePair<string,string> pair in serialFingerprints)
//					{
//						var prints = JsonSerializer.DeserializeFromString<JsonObject>(pair.Key);
//						foreach (KeyValuePair<string,string> print in prints)
//						{
//							SimpleFingerprint simpleFingerprint = new SimpleFingerprint ();
//							var strBase64Template = JsonSerializer.DeserializeFromString<string>(print.Key);
////							simpleFingerprint.Base64Template = print["Base64Template"];
//							fingerprints.Add(simpleFingerprint);
//						}
//					}
					person.Fingerprints = fingerprints;
					//person.Filename = jsonObj["Filename"];
					person.Uuid = jsonObj["Uuid"];
					//database.Add(person);
					FingerprintDatabase.AddData(person);
					Console.WriteLine("Added person to FingerprintDatabase.");
				}
				//container.Register(database);

			}
			catch (Exception e) {
				Console.WriteLine("Error: " + e);
			}

//			return result;
		}
예제 #21
0
        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;
            }
        }
예제 #22
0
        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" });
            };
        }