コード例 #1
0
ファイル: Ndef.cs プロジェクト: elicec/springcard.pcsc.sdk
 public Ndef(byte _TNF, string _TYPE)
 {
     _TNF    &= 0x07;
     _header &= 0xF8;
     _header |= _TNF;
     _type    = CardBuffer.BytesFromString(_TYPE);
 }
コード例 #2
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public byte[] GetATR()
        {
            CardBuffer cardAtr = reader.CardAtr;

            Console.WriteLine(cardAtr.AsString(" "));
            return(cardAtr.Bytes);
        }
コード例 #3
0
ファイル: MainForm.cs プロジェクト: Sryn/springcard.pcsc.sdk
        void ReaderListChanged(string ReaderName, uint ReaderState, CardBuffer CardAtr)
        {
            /* The ReaderListChanged function is called as a delegate (callback) by the SCardReaderList object  */
            /* withing its backgroung thread. Therefore we must use the BeginInvoke syntax to switch back from  */
            /* the context of the background thread to the context of the application's main thread. Overwise   */
            /* we'll get a security violation when trying to access the window's visual components (that belong */
            /* to the application's main thread and can't be safely manipulated by background threads).         */
            if (InvokeRequired)
            {
                Console.WriteLine("ReaderListChanged (in background thread)");
                this.BeginInvoke(new ReaderListChangedInvoker(ReaderListChanged), ReaderName, ReaderState, CardAtr);
                return;
            }

            Console.WriteLine("ReaderListChanged (in main thread)");

            if (ReaderName != null)
            {
                /* A reader-related event */
                /* ---------------------- */

                UpdateReaderState(ReaderName, ReaderState, CardAtr);
            }
            else
            {
                /* The list of readers has changed, let's rebuild it */
                /* ------------------------------------------------- */

                UpdateReaderList();
            }
        }
コード例 #4
0
ファイル: Form1.cs プロジェクト: elicec/springcard.pcsc.sdk
        /// <summary>
        /// Callback used when the reader's status change
        /// As this method is called from a thread, you can't directly modify the user interface
        /// </summary>
        /// <param name="readerState"></param>
        /// <param name="cardAtr"></param>
        private void readerStatusChanged(uint readerState, CardBuffer cardAtr)
        {
            // When you are in a thread you can't directly modify the user interface
            if (InvokeRequired)
            {
                this.BeginInvoke(new readerStatusChangedInvoker(readerStatusChanged), readerState, cardAtr);
                return;
            }
            btnRead.Enabled      = false;
            txtAsciiContent.Text = "";
            txtFinalStatus.Text  = "";
            txtHexData.Text      = "";
            lblCardAtr.Text      = "";
            lblStatus.Text       = SCARD.ReaderStatusToString(readerState);

            if (cardAtr != null)
            {
                lblCardAtr.Text = cardAtr.AsString(" ");
                channel         = new SCardChannel(reader);
                if (!channel.Connect())
                {
                    lblStatus.Text = "Error, can't connect to the card";
                    return;
                }
                CAPDU capdu = new CAPDU(0xFF, 0xCA, 0x00, 0x00);    // Command sent to the reader
                RAPDU rapdu = channel.Transmit(capdu);              // Response sent from card
                if (rapdu.SW != 0x9000)                             // Something failed
                {
                    lblStatus.Text = "Get UID APDU failed!";
                    return;
                }
                btnRead.Enabled = true;
            }
        }
コード例 #5
0
        void DisplayReaderState(uint ReaderState, CardBuffer CardAtr)
        {
            lbReaderStatus.Text = SCARD.ReaderStatusToString(ReaderState);

            if (CardAtr != null)
            {
                lbCardAtr.Text = CardAtr.AsString(" ");
            }
            else
            {
                lbCardAtr.Text = "";
            }

            bool runable = false;

            if ((ReaderState & SCARD.STATE_PRESENT) != 0)
            {
                if ((ReaderState & SCARD.STATE_UNAVAILABLE) == 0)
                {
                    if ((ReaderState & SCARD.STATE_MUTE) == 0)
                    {
                        runable = true;
                    }
                }
            }

            btnRun.Enabled = runable;
        }
コード例 #6
0
            public bool setKeyB(string skey)
            {
                Logger.Trace("Setting Key B");
                CardBuffer bkey = new CardBuffer(skey.Trim());

                return(setKeyB(bkey.GetBytes()));
            }
コード例 #7
0
ファイル: Ndef.cs プロジェクト: elicec/springcard.pcsc.sdk
 public Ndef(byte _TNF, string _TYPE, byte[] _PAYLOAD)
 {
     _TNF    &= 0x07;
     _header &= 0xF8;
     _header |= _TNF;
     _type    = CardBuffer.BytesFromString(_TYPE);
     _payload = _PAYLOAD;
 }
コード例 #8
0
        /*
         * SCardControl
         * ------------
         */
        void BtnControlClick(object sender, EventArgs e)
        {
            RCtrlClear();

            DynamicByteProvider p;

            byte[] b;

            p = (DynamicByteProvider)hexBoxCCtrl.ByteProvider;

            b = new byte[p.Length];

            for (int i = 0; i < p.Length; i++)
            {
                b[i] = p.ReadByte(i);
            }

            CardBuffer cctrl = new CardBuffer(b);

            Settings.HistoryControl.Add(cctrl.AsString());
            hist_ctrl_idx = -1;

            CardBuffer rctrl = channel.Control(cctrl);

            if (rctrl == null)
            {
                ShowError();
            }
            else
            {
                ShowSuccess();

                b = rctrl.GetBytes();

                p = new DynamicByteProvider(b);

                hexBoxRCtrl.ByteProvider = p;

                if (b.Length > 0)
                {
                    eResultByte.Text = String.Format("{0}", 0 - (int)b[0]);

                    if (b[0] == 0)
                    {
                        eResultByteExplain.Text = "Success";
                    }
                    else
                    {
                        ushort sw = (ushort)(0x6F00 | b[0]);
                        eResultByteExplain.Text = SCARD.CardStatusWordsToString(sw);
                    }
                }

                hexBoxRCtrl.BackColor        = hexBoxCApdu.BackColor;
                eResultByte.BackColor        = eCardAtr.BackColor;
                eResultByteExplain.BackColor = eCardAtr.BackColor;
            }
        }
コード例 #9
0
        /// <summary>
        /// Save sector
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void BtnOkClick(object sender, EventArgs e)
        {
            byte[]     AccessBits;
            byte[]     SectorTrailer;
            byte[]     KeyA;
            byte[]     KeyB;
            CardBuffer cardbufA;
            CardBuffer cardbufB;

            if (!MemoryCardMifareClassic.Sector.isKeyValid(cbKeyA.Text))
            {
                MessageBox.Show(this, "Key A: please supply a valid 6-byte value, in hexadecimal (12 hex digits).", "Invalid entry", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.DialogResult = DialogResult.None;
                return;
            }

            if (!MemoryCardMifareClassic.Sector.isKeyValid(cbKeyB.Text))
            {
                MessageBox.Show(this, "Key B: please supply a valid 6-byte value, in hexadecimal (12 hex digits).", "Invalid entry", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.DialogResult = DialogResult.None;
                return;
            }

            AccessBits = computeSectorTrailer();
            if ((AccessBits == null) || (AccessBits.Length != 4))
            {
                MessageBox.Show(this, "Failed to compute the access bits.", "Internal error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.DialogResult = DialogResult.Cancel;
                return;
            }

            SectorTrailer = new byte[16];

            cardbufA = new CardBuffer(cbKeyA.Text);
            cardbufB = new CardBuffer(cbKeyB.Text);
            KeyA     = cardbufA.GetBytes();
            KeyB     = cardbufB.GetBytes();

            Array.ConstrainedCopy(KeyA, 0, SectorTrailer, 0, KeyA.Length);
            Array.ConstrainedCopy(AccessBits, 0, SectorTrailer, KeyA.Length, AccessBits.Length);
            Array.ConstrainedCopy(KeyB, 0, SectorTrailer, KeyA.Length + AccessBits.Length, KeyB.Length);

            // Save keyA and keyB
            Settings.RememberKeyA(cbKeyA.Text);
            Settings.RememberKeyB(cbKeyB.Text);

            if (!sector.setKeyA(KeyA) || !sector.setKeyB(KeyB))
            {
                MessageBox.Show(this, "Failed to define the new keys.", "Internal error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.DialogResult = DialogResult.Cancel;
                return;
            }
            this.DialogResult = DialogResult.OK;
        }
コード例 #10
0
            public bool setWritingKeyFromString(string key)
            {
                if (!isKeyValid(key))
                {
                    return(false);
                }
                CardBuffer bkey = new CardBuffer(key.Trim());

                writingKey = bkey.GetBytes();
                return(true);
            }
コード例 #11
0
        void DisplayReaderState(uint ReaderState, CardBuffer CardAtr)
        {
            lbReaderStatus.Text = SCARD.ReaderStatusToString(ReaderState);

            if (CardAtr != null)
            {
                lbCardAtr.Text = CardAtr.AsString(" ");
            }
            else
            {
                lbCardAtr.Text = "";
            }
        }
コード例 #12
0
        /**m* SpringCard.NFC/NfcTagType2.RecognizeAtr
         *
         * SYNOPSIS
         *   public static bool RecognizeAtr(CardBuffer atr)
         *   public static bool RecognizeAtr(SCardChannel channel)
         *
         *
         * DESCRIPTION
         *   Checks wether the ATR of the card corresponds to the ATR
         *   of a Mifare Ultralight or a Mifare Ultralight C card.
         *   Returns true on success.
         *
         **/
        public static bool RecognizeAtr(CardBuffer atr)
        {
            string s = atr.AsString("");

            if (s.Equals(ATR_MIFARE_UL))
            {
                Trace.WriteLine("ATR: Mifare UltraLight");
                return(true);
            }
            if (s.Equals(ATR_MIFARE_UL_C))
            {
                Trace.WriteLine("ATR: Mifare UltraLight C");
                return(true);
            }

            return(false);
        }
コード例 #13
0
        private int AddLine(byte[] pl, int len, int index, string desc, string cont)
        {
            byte[] desc_array = CardBuffer.BytesFromString(desc);

            if ((index + desc_array.Length) > len)
            {
                return(-1);
            }

            Array.ConstrainedCopy(desc_array, 0, pl, index, desc_array.Length);
            index += desc_array.Length;

            if ((index + cont.Length) > len)
            {
                return(-1);
            }

            Array.ConstrainedCopy(CardBuffer.BytesFromString(cont), 0, pl, index, cont.Length);
            index += cont.Length;

            if (index > len)
            {
                return(-1);
            }

            pl[index] = 0x0D;
            index++;
            if (index > len)
            {
                return(-1);
            }

            pl[index] = 0x0A;
            index++;
            if (index > len)
            {
                return(-1);
            }

            return(index);
        }
コード例 #14
0
ファイル: NfcTag.cs プロジェクト: elicec/springcard.pcsc.sdk
        private byte[] SerializeContent()
        {
            if ((Content == null) || (Content.Count == 0))
            {
                Trace.WriteLine("Nothing to serialize");
                return(null);
            }

            CardBuffer result = new CardBuffer();

            for (int i = 0; i < Content.Count; i++)
            {
                bool   is_begin = (i == 0) ? true : false;
                bool   is_end   = (i == (Content.Count - 1)) ? true : false;
                byte[] t        = Content[i].GetBytes(is_begin, is_end);

                result.Append(t);
            }

            return(result.GetBytes());
        }
コード例 #15
0
        void ReaderStatusChanged(uint ReaderState, CardBuffer CardAtr)
        {
            if (ReaderState == SCARD.STATE_UNAWARE)
            {
                Trace.WriteLine("*** Reader removed ***");

                if (_AdapterErrorCallback != null)
                {
                    _AdapterErrorCallback();
                }

                if (_llcp != null)
                {
                    _llcp.Stop();
                    _llcp = null;
                }
                _reader = null;
                return;
            }

            if ((ReaderState & SCARD.STATE_EMPTY) != 0)
            {
                if (_llcp != null)
                {
                    _llcp.Stop();
                    _llcp = null;
                }

                Trace.WriteLine("*** Target removed ***");
            }
            else
            if ((ReaderState & SCARD.STATE_UNAVAILABLE) != 0)
            {
            }
            else
            if ((ReaderState & SCARD.STATE_MUTE) != 0)
            {
            }
            else
            if ((ReaderState & SCARD.STATE_INUSE) != 0)
            {
            }
            else
            if ((ReaderState & SCARD.STATE_PRESENT) != 0)
            {
                Trace.WriteLine("*** Target arrived ***");

                if (_llcp == null)
                {
                    _llcp = new LlcpInitiator(_reader);

                    if (_CreateNdefCallback != null)
                    {
                        Ndef ndef = _CreateNdefCallback();

                        if (ndef != null)
                        {
                            Trace.WriteLine("Create SNEP Client (sender)");

                            SNEP_Client client = new SNEP_Client(ndef);

                            client.OnMessageSent = new SNEP_Client.SNEPMessageSentCallback(_NdefSentCallback);
                            client.MessageSentCallbackOnAcknowledge = true;

                            _llcp.RegisterClient(client);
                        }
                    }

                    _llcp.Start();
                }
            }
        }
コード例 #16
0
        protected override bool WriteContent(byte[] ndef_content)
        {
            Trace.WriteLine("Writing the NFC Forum type 2 Tag");

            if (ndef_content == null)
            {
                return(false);
            }

            /* Get the new NDEF TLV to store into the Tag */
            NfcTlv ndef_tlv = new NfcTlv(NDEF_MESSAGE_TLV, ndef_content);

            /* Remove the Terminator TLV (if some) */
            while ((_tlvs.Count > 0) && (_tlvs[_tlvs.Count - 1].T == TERMINATOR_TLV))
            {
                _tlvs.RemoveAt(_tlvs.Count - 1);
            }

            /* Where shall I put the NDEF TLV in the Tag ? */
            if (_tlvs.Count == 0)
            {
                _tlvs.Add(ndef_tlv);
            }
            else
            {
                for (int i = 0; i < _tlvs.Count; i++)
                {
                    if (_tlvs[i].T == NDEF_MESSAGE_TLV)
                    {
                        /* Replace this one */
                        _tlvs[i] = ndef_tlv;
                        ndef_tlv = null;
                        break;
                    }
                }

                if (ndef_tlv != null)
                {
                    /* No NDEF in the Tag beforehand? Let's add it the the end */
                    _tlvs.Add(ndef_tlv);
                }
            }

            CardBuffer actual_content = new CardBuffer();

            for (int i = 0; i < _tlvs.Count; i++)
            {
                actual_content.Append(_tlvs[i].Serialize());
            }

            if (actual_content.Length > Capacity())
            {
                Trace.WriteLine("The size of the content (with its TLVs) is bigger than the tag's capacity");
                return(false);
            }

            if ((actual_content.Length + 2) < Capacity())
            {
                /* Add a Terminator at the end */
                Trace.WriteLine("We add a TERMINATOR TLV at the end of the Tag");
                actual_content.Append((new NfcTlv(TERMINATOR_TLV, null)).Serialize());
            }

            /* And now write */
            ushort page = 4;

            for (long i = 0; i < actual_content.Length; i += 4)
            {
                byte[] buffer = new byte[4];

                for (long j = 0; j < 4; j++)
                {
                    if ((i + j) < actual_content.Length)
                    {
                        buffer[j] = actual_content.GetByte(i + j);
                    }
                }

                if (!WriteBinary(_channel, page, buffer))
                {
                    return(false);
                }
                page++;
            }

            return(true);
        }
コード例 #17
0
        protected override bool Read()
        {
            Trace.WriteLine("Reading the NFC Forum type 2 Tag");

            ushort page = 0;

            if (!Recognize(_channel, ref _formatted, ref _formattable, ref _locked))
            {
                return(false);
            }

            CardBuffer buffer = new CardBuffer();

            for (page = 0; page < 256; page += 4)
            {
                byte[] data = ReadBinary(_channel, page, READ_4_PAGES);

                if (data == null)
                {
                    break;
                }

                if (page > 0)
                {
                    bool same_as_header = true;
                    for (int i = 0; i < OFFSET_USER_DATA; i++)
                    {
                        if (data[i] != buffer.GetByte(i))
                        {
                            same_as_header = false;
                            break;
                        }
                    }
                    if (same_as_header)
                    {
                        break;
                    }
                }

                buffer.Append(data);
            }

            Trace.WriteLine("Read " + buffer.Length + "B of data from the Tag");

            _raw_data = buffer.GetBytes();

            _capacity = _raw_data.Length;
            if (_capacity <= OFFSET_USER_DATA)
            {
                _capacity = 0;
                return(false);
            }

            if (!_formatted)
            {
                /* Guess the capacity from the read area */
                if ((_capacity > 64) && !_formatted)
                {
                    /* Drop the 16 last bytes if they are not empty (locks on Mifare UltraLight C) */
                    bool locks_found = false;
                    for (long i = _capacity - 16; i < _capacity; i++)
                    {
                        if (_raw_data[i] != 0)
                        {
                            locks_found = true;
                            break;
                        }
                    }
                    if (locks_found)
                    {
                        Trace.WriteLine("Locks found at the end");
                        _capacity -= 16;
                    }
                }
                _capacity -= OFFSET_USER_DATA;
                Trace.WriteLine("The Tag is not formatted, capacity=" + _capacity + "B");
            }
            else
            {
                /* Read the capacity in the CC */
                _capacity = 8 * _raw_data[14];
                Trace.WriteLine("The Tag is formatted, capacity read from the CC=" + _capacity + "B");
            }

            /* Is the tag empty ? */
            _is_empty = true;
            for (long i = 0; i < _capacity; i++)
            {
                if (_raw_data[OFFSET_USER_DATA + i] != 0)
                {
                    _is_empty = false;
                    break;
                }
            }

            if (_is_empty)
            {
                Trace.WriteLine("The Tag is empty");
                return(true);
            }

            byte[] ndef_data = null;

            if (!ParseUserData(buffer.GetBytes(OFFSET_USER_DATA, -1), ref ndef_data))
            {
                Trace.WriteLine("The parsing of the Tag failed");
                return(false);
            }

            if (ndef_data == null)
            {
                Trace.WriteLine("The Tag doesn't contain a NDEF");
                _is_empty = true;
                return(true);
            }

            _is_empty = false;

            Ndef[] t = Ndef.Parse(ndef_data);
            if (t == null)
            {
                Trace.WriteLine("The NDEF is invalid or unsupported");
                return(false);
            }

            Trace.WriteLine(t.Length + " NDEF record(s) found in the Tag");

            /* This NDEF is the new content of the tag */
            Content.Clear();
            for (int i = 0; i < t.Length; i++)
            {
                Content.Add(t[i]);
            }

            return(true);
        }
コード例 #18
0
        void ReaderStatusChanged(uint ReaderState, CardBuffer CardAtr)
        {
            /* The ReaderStatusChanged function is called as a delegate (callback) by the SCardReader object    */
            /* within its backgroung thread. Therefore we must use the BeginInvoke syntax to switch back from   */
            /* the context of the background thread to the context of the application's main thread. Overwise   */
            /* we'll get a security violation when trying to access the window's visual components (that belong */
            /* to the application's main thread and can't be safely manipulated by background threads).         */
            if (InvokeRequired)
            {
                this.BeginInvoke(new ReaderStatusChangedInvoker(ReaderStatusChanged), ReaderState, CardAtr);
                return;
            }

            DisplayReaderState(ReaderState, CardAtr);

            if (ReaderState == SCARD.STATE_UNAWARE)
            {
                if (cardChannel != null)
                {
                    cardChannel.Disconnect();
                    cardChannel = null;
                }
                if (Reader != null)
                {
                    Reader.StopMonitor();
                    Reader.Release();
                    Reader = null;
                }
                if (ReaderList != null)
                {
                    ReaderList.Release();
                    ReaderList = null;
                }

                btnReadAgain.Enabled = false;
                btnWrite.Enabled     = false;

                MessageBox.Show(this,
                                "The reader we were working on has been removed from the system. Please click the 'Reader' link to select another reader.",
                                Title,
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation);

                DisplayReaderState(0, null);
                DisplayReaderAbsent();
                return;
            }

            if ((ReaderState & SCARD.STATE_EMPTY) != 0)
            {
                if (cardChannel != null)
                {
                    cardChannel.Disconnect();
                    cardChannel = null;
                }

                btnReadAgain.Enabled = false;
                btnWrite.Enabled     = false;
            }
            else if ((ReaderState & SCARD.STATE_UNAVAILABLE) != 0)
            {
                btnReadAgain.Enabled = false;
                btnWrite.Enabled     = false;
            }
            else if ((ReaderState & SCARD.STATE_MUTE) != 0)
            {
                btnReadAgain.Enabled = false;
                btnWrite.Enabled     = false;
            }
            else if ((ReaderState & SCARD.STATE_INUSE) != 0)
            {
            }
            else if ((ReaderState & SCARD.STATE_PRESENT) != 0)
            {
                if (cardChannel == null)
                {
                    /* New card -> leave edit mode */
                    cardChannel = Reader.GetChannel();

                    DisplayWorking(false);

                    if (cardChannel.Connect())
                    {
                        cardReaderThread = new Thread(ReadCardFirst);
                        cardReaderThread.Start();
                    }
                    else
                    {
                        ClearDisplay();
                        MessageBox.Show(this,
                                        "Failed to connect to the card in the reader. Please verify that you don't have another application running in the background, that tries to access to the smartcards in the same reader.",
                                        Title,
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Exclamation);
                        cardChannel = null;
                    }
                }
            }
        }
コード例 #19
0
        public RtdVCard(byte[] payload) : base("text/x-vCard")
        {
            Trace.WriteLine("Parsing VCard Payload");

            /* First: loop to determine how many lines are present in the VCard	*/
            int i        = 0;
            int Nb_lines = 0;

            while (i < payload.Length)
            {
                if (i + 1 < payload.Length)
                {
                    if (payload[i] == 0x0D && payload[i + 1] == 0x0A)
                    {
                        Nb_lines++;
                        i += 2;
                    }
                    else
                    {
                        i++;
                    }
                }
                else
                {
                    i++;
                }
            }

            /* Second: create an array of strings :                                     */
            /* Each entry corresponds to a line present in the VCard	*/
            string[] lines_array       = new string[Nb_lines];
            int      index             = 0;
            int      begining_position = 0;

            byte[] line;
            i = 0;
            while (i < payload.Length)
            {
                if ((i + 1) < payload.Length)
                {
                    if ((payload[i] == 0x0D) && (payload[i + 1] == 0x0A))
                    {
                        line = new byte[i - begining_position];
                        Array.ConstrainedCopy(payload, begining_position, line, 0, i - begining_position);
                        lines_array[index] = CardBuffer.StringFromBytes(line);
                        index++;
                        i += 2;
                        begining_position = i;
                    }
                    else
                    {
                        i++;
                    }
                }
                else
                {
                    i++;
                }
            }

            /* Third: for each entry in the array of strings							*/
            /* Determine what it represents and populate the VCard Object	*/
            string[] elements;
            char[]   colon = { ':' };
            bool     email_already_found = false;

            for (int j = 0; j < lines_array.Length; j++)
            {
                elements = lines_array[j].Split(colon);

                if (elements[0].IndexOf("FN") != -1)
                {
                    string[] names;
                    char[]   space = { ' ' };
                    names = elements[1].Split(space);
                    if (names.Length > 1)
                    {
                        _first_name  = names[0];
                        _family_name = names[names.Length - 1];
                    }
                }

                if (elements[0].Equals("N"))
                {
                    string[] names;
                    char[]   semicolon = { ';' };
                    names        = elements[1].Split(semicolon);
                    _family_name = names[0];

                    if (names.Length > 0)
                    {
                        _first_name = names[1];
                    }

                    if (names.Length > 1)
                    {
                        _middle_name = names[2];
                    }

                    if (names.Length > 2)
                    {
                        _prefix_name = names[3];
                    }

                    if (names.Length > 3)
                    {
                        _suffix_name = names[4];
                    }
                }

                if (elements[0].IndexOf("NICKNAME") != -1)
                {
                    _nickname = elements[elements.Length - 1];
                }

                if (elements[0].IndexOf("BDAY") != -1)
                {
                    _birthday = elements[elements.Length - 1];
                }

                if (elements[0].IndexOf("ADR") != -1)
                {
                    if (elements[0].IndexOf("work") != -1)
                    {
                        /* Work address																							*/
                        string[] addr_lines;
                        char[]   semicolon = { ';' };
                        addr_lines = elements[elements.Length - 1].Split(semicolon);

                        /* There must be exactly 7 elements, even if some are null	*/
                        /* The first of them, "PO BOX", is ignored								    */
                        if (addr_lines.Length == 7)
                        {
                            if (addr_lines[1].Length > 0)
                            {
                                _pro_Address1 = addr_lines[1];
                            }

                            if (addr_lines[2].Length > 0)
                            {
                                _pro_Address2 = addr_lines[2];
                            }

                            if (addr_lines[3].Length > 0)
                            {
                                _pro_Town = addr_lines[3];
                            }

                            if (addr_lines[4].Length > 0)
                            {
                                _pro_Region_State = addr_lines[4];
                            }

                            if (addr_lines[5].Length > 0)
                            {
                                _pro_Post_Code = addr_lines[5];
                            }

                            if (addr_lines[6].Length > 0)
                            {
                                _pro_Country = addr_lines[6];
                            }
                        }
                    }
                    else
                    {
                        /* Work is not specified	-> "private" tab */
                        string[] addr_lines;
                        char[]   semicolon = { ';' };
                        addr_lines = elements[elements.Length - 1].Split(semicolon);

                        /* There must be exactly 7 elements, even if some are null */
                        /* The first of them : PO BOX, is ignored									 */
                        if (addr_lines.Length == 7)
                        {
                            if (addr_lines[1].Length > 0)
                            {
                                _address1 = addr_lines[1];
                            }

                            if (addr_lines[2].Length > 0)
                            {
                                _address2 = addr_lines[2];
                            }

                            if (addr_lines[3].Length > 0)
                            {
                                _town = addr_lines[3];
                            }

                            if (addr_lines[4].Length > 0)
                            {
                                _region_State = addr_lines[4];
                            }

                            if (addr_lines[5].Length > 0)
                            {
                                _post_Code = addr_lines[5];
                            }

                            if (addr_lines[6].Length > 0)
                            {
                                _country = addr_lines[6];
                            }
                        }
                    }
                }

                if (elements[0].IndexOf("TEL") != -1)
                {
                    if (elements[0].IndexOf("TYPE=") != -1)
                    {
                        if (elements[0].IndexOf("work") != -1)
                        {
                            _business_phone = elements[elements.Length - 1];
                        }

                        if (elements[0].IndexOf("cell") != -1)
                        {
                            _cell_phone = elements[elements.Length - 1];
                        }

                        if (elements[0].IndexOf("home") != -1)
                        {
                            _home_phone = elements[elements.Length - 1];
                        }

                        if (elements[0].IndexOf("pager") != -1)
                        {
                            _pager = elements[elements.Length - 1];
                        }

                        if (elements[0].IndexOf("fax") != -1)
                        {
                            _fax = elements[elements.Length - 1];
                        }
                    }
                    else
                    {
                        /* No TYPE specified => By default : Business phone	*/
                        _business_phone = elements[elements.Length - 1];
                    }
                }

                if (elements[0].IndexOf("EMAIL") != -1)
                {
                    if (!email_already_found)
                    {
                        _email = elements[elements.Length - 1];
                        email_already_found = true;
                    }
                    else
                    {
                        _email_alternative = elements[elements.Length - 1];
                    }
                }

                if (elements[0].IndexOf("TITLE") != -1)
                {
                    _title = elements[elements.Length - 1];
                }

                if (elements[0].IndexOf("ROLE") != -1)
                {
                    _role = elements[elements.Length - 1];
                }

                if (elements[0].IndexOf("ORG") != -1)
                {
                    _company = elements[elements.Length - 1];
                }

                if (elements[0].IndexOf("PHOTO") != -1)
                {
                    /*
                     * string[] spec;
                     * char[] comma = {','};
                     * spec = elements[elements.Length - 1].Split(comma);
                     * _photo = spec[spec.Length - 1];
                     */
                    _photo = elements[elements.Length - 1];
                }
            }
            Trace.WriteLine("VCard Payload successfully parsed");
        }
コード例 #20
0
ファイル: Ndef.cs プロジェクト: elicec/springcard.pcsc.sdk
        public static bool Parse(byte[] buffer, ref int offset, ref Ndef ndef, ref bool terminated)
        {
            if (offset > buffer.Length)
            {
                return(false);
            }

            terminated = false;
            ndef       = null;

            /*  Header */
            if (offset + 1 > buffer.Length)
            {
                Trace.WriteLine("NDEF truncated after 'Header' byte");
                return(false);
            }
            byte header = buffer[offset++];

            if (header == 0)
            {
                Trace.WriteLine("Empty byte?");
                return(false);
            }

            /* Type length		*/
            if (offset + 1 > buffer.Length)
            {
                Trace.WriteLine("NDEF truncated after 'Type Length' byte");
                return(false);
            }
            int type_length = buffer[offset++];

            /* Payload length	*/
            int payload_length = 0;

            if ((header & NDEF_HEADER_SHORT_RECORD) != 0)
            {
                if (offset + 1 > buffer.Length)
                {
                    Trace.WriteLine("NDEF truncated after 'Payload Length' byte");
                    return(false);
                }
                payload_length = buffer[offset++];
            }
            else
            {
                if (offset + 4 > buffer.Length)
                {
                    Trace.WriteLine("NDEF truncated after 'Payload Length' dword");
                    return(false);
                }
                payload_length  = buffer[offset++]; payload_length *= 0x00000100;
                payload_length += buffer[offset++]; payload_length *= 0x00000100;
                payload_length += buffer[offset++]; payload_length *= 0x00000100;
                payload_length += buffer[offset++];
            }

            /*  ID Length			*/
            int id_length = 0;

            if ((header & NDEF_HEADER_ID_LENGTH_PRESENT) != 0)
            {
                if (offset + 1 > buffer.Length)
                {
                    Trace.WriteLine("NDEF truncated after 'ID Length' byte");
                    return(false);
                }
                id_length = buffer[offset++];
            }

            /* Type */
            byte[] type = null;
            if (type_length > 0)
            {
                if (offset + type_length > buffer.Length)
                {
                    Trace.WriteLine("NDEF truncated after 'Type' bytes");
                    return(false);
                }
                type = new byte[type_length];
                for (int i = 0; i < type_length; i++)
                {
                    type[i] = buffer[offset++];
                }
            }

            /* ID */
            byte[] id = null;
            if (id_length > 0)
            {
                if (offset + id_length > buffer.Length)
                {
                    Trace.WriteLine("NDEF truncated after 'ID' bytes");
                    return(false);
                }
                id = new byte[id_length];
                for (int i = 0; i < id_length; i++)
                {
                    id[i] = buffer[offset++];
                }
            }

            /* Payload */
            byte[] payload = null;
            if (payload_length > 0)
            {
                if (offset + payload_length > buffer.Length)
                {
                    Trace.WriteLine("NDEF truncated after 'Payload' bytes");
                    return(false);
                }
                payload = new byte[payload_length];
                for (int i = 0; i < payload_length; i++)
                {
                    payload[i] = buffer[offset++];
                }
            }

            /* OK */
            string type_s = CardBuffer.StringFromBytes(type);

            switch (header & NDEF_HEADER_TNF_MASK)
            {
            case NDEF_HEADER_TNF_EMPTY:
                break;

            case NDEF_HEADER_TNF_NFC_RTD_WKN:
                if (type_s.Equals("Sp"))
                {
                    Trace.WriteLine("Found a SmartPoster");
                    ndef = new RtdSmartPoster(payload);
                }
                else
                if (type_s.Equals("U"))
                {
                    Trace.WriteLine("Found an URI");
                    ndef = new RtdUri(payload);
                }
                else
                if (type_s.Equals("T"))
                {
                    Trace.WriteLine("Found a Text");
                    ndef = new RtdText(payload);
                }
                else
                if (type_s.Equals("act"))
                {
                    Trace.WriteLine("Found an Action");
                    ndef = new RtdSmartPosterAction(payload);
                }
                else
                if (type_s.Equals("s"))
                {
                    Trace.WriteLine("Found a Size");
                    ndef = new RtdSmartPosterTargetSize(payload);
                }
                else
                if (type_s.Equals("t"))
                {
                    Trace.WriteLine("Found a MIME-Type");
                    ndef = new RtdSmartPosterTargetType(payload);
                }
                else
                if (type_s.Equals("Hs"))
                {
                    Trace.WriteLine("Found a Handover Selector");
                    ndef = new RtdHandoverSelector(payload, ref buffer, ref offset);
                }
                else
                if (type_s.Equals("ac"))
                {
                    Trace.WriteLine("Found a Alternative Carrier");
                    ndef = new RtdAlternativeCarrier(payload);
                }
                else
                {
                    Trace.WriteLine("Found an unknown RTD : " + type_s);
                }
                break;

            case NDEF_HEADER_TNF_MEDIA_TYPE:
                if (type_s.ToLower().Equals("text/x-vcard"))
                {
                    Trace.WriteLine("Found a vCard");
                    ndef = new RtdVCard(payload);
                }
                else
                {
                    Trace.WriteLine("Found a MIME Media : " + type_s);
                    ndef = new RtdMedia(type_s, payload);
                }
                break;

            case NDEF_HEADER_TNF_ABSOLUTE_URI:
                if (type_s.Equals("U"))
                {
                    Trace.WriteLine("Found an absolute URI");
                    ndef = new AbsoluteUri(id, payload);
                }
                break;

            case NDEF_HEADER_TNF_NFC_RTD_EXT:
                Trace.WriteLine("Found TNF urn:nfc:ext");
                break;

            case NDEF_HEADER_TNF_UNKNOWN:
                Trace.WriteLine("Found TNF unknown");
                break;

            case NDEF_HEADER_TNF_UNCHANGED:
                Trace.WriteLine("Found TNF unchanged");
                break;

            case NDEF_HEADER_TNF_RESERVED:
                Trace.WriteLine("Found TNF reserved");
                break;

            default:
                return(false);                        // Invalid
            }

            if (ndef == null)
            {
                ndef = new Ndef(header, type, id, payload);
            }

            if (offset >= buffer.Length)
            {
                Trace.WriteLine("Done!");
                terminated = true;
            }

            return(true);
        }
コード例 #21
0
ファイル: MainForm.cs プロジェクト: Sryn/springcard.pcsc.sdk
        void MiATRRegistryClick(object sender, EventArgs e)
        {
            EXImageListViewItem item = (EXImageListViewItem)lvReaders.SelectedItems[0];

            if (!item.SubItems[4].Text.Equals(""))
            {
                IntPtr hContext    = IntPtr.Zero;
                uint   _last_error = SCARD.EstablishContext(SCARD.SCOPE_SYSTEM, IntPtr.Zero, IntPtr.Zero, ref hContext);
                if (_last_error != SCARD.S_SUCCESS)
                {
                    MessageBox.Show("Error: can't establish context");
                    return;
                }

                CardBuffer cardBufAtr = new CardBuffer(item.SubItems[4].Text);
                byte[]     atr        = cardBufAtr.GetBytes();

                byte[] dummy    = new byte[99];
                int    cchCards = -1;              /*	SCARD_AUTOALLOCATE */
                _last_error = SCardListCards(hContext,
                                             atr,
                                             null,
                                             0,
                                             null,
                                             ref cchCards);

                if (_last_error != SCARD.S_SUCCESS)
                {
                    MessageBox.Show("Error: can't list cards");
                    return;
                }

                if (cchCards <= 1)
                {
                    /* Card not found. We need to add it. */
                    string name = "NoMinidriver-" + item.SubItems[4].Text;
                    _last_error = SCardIntroduceCardType(hContext,
                                                         name,
                                                         null,
                                                         null,
                                                         0,
                                                         atr,
                                                         null,
                                                         (uint)atr.Length);

                    if (_last_error != SCARD.S_SUCCESS)
                    {
                        MessageBox.Show("Error: can't introduce card type");
                        return;
                    }

                    _last_error = SCardSetCardTypeProviderName(hContext,
                                                               name,
                                                               2, /*	SCARD_PROVIDER_CSP	*/
                                                               "$DisableSCPnP$");

                    if (_last_error != SCARD.S_SUCCESS)
                    {
                        MessageBox.Show("Error: can't set card type provider name");
                        return;
                    }
                    else
                    {
                        MessageBox.Show("This card will now be recognized by the system");
                    }
                }
                else
                {
                    MessageBox.Show("This card is already recognized by the system");
                }
            }
        }
コード例 #22
0
        void ReaderStatusChanged(uint ReaderState, CardBuffer CardAtr)
        {
            /* The ReaderStatusChanged function is called as a delegate (callback) by the SCardReader object    */
            /* within its backgroung thread. Therefore we must use the BeginInvoke syntax to switch back from   */
            /* the context of the background thread to the context of the application's main thread. Overwise   */
            /* we'll get a security violation when trying to access the window's visual components (that belong */
            /* to the application's main thread and can't be safely manipulated by background threads).         */
            if (InvokeRequired)
            {
                this.BeginInvoke(new ReaderStatusChangedInvoker(ReaderStatusChanged), ReaderState, CardAtr);
                return;
            }

            eReaderStatus.Text = SCARD.ReaderStatusToString(ReaderState);

            if (CardAtr != null)
            {
                eCardAtr.Text = CardAtr.AsString(" ");
            }
            else
            {
                eCardAtr.Text = "";
            }

            if (ReaderState == SCARD.STATE_UNAWARE)
            {
//			  lbReaderStatus.Text = "";

                MessageBox.Show("The reader we were working on has disappeared from the system. This application will terminate now.",
                                "The reader has been removed",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation);

                Application.Exit();
            }
            else
            if ((ReaderState & SCARD.STATE_EMPTY) != 0)
            {
//			  lbReaderStatus.Text = "No card in the reader";
                card_available = false;
            }
            else
            if ((ReaderState & SCARD.STATE_UNAVAILABLE) != 0)
            {
//			  lbReaderStatus.Text = "Reader in use";
                card_available = false;
            }
            else
            if ((ReaderState & SCARD.STATE_MUTE) != 0)
            {
//			  lbReaderStatus.Text = "Card is mute";
                card_available = false;
            }
            else
            if ((ReaderState & SCARD.STATE_INUSE) != 0)
            {
//			  lbReaderStatus.Text = "Card in use";
                card_available = false;
            }
            else
            if ((ReaderState & SCARD.STATE_PRESENT) != 0)
            {
                //lbReaderStatus.Text = "Card ready";
                card_available = true;

                if (auto_write)
                {
                    BtnWriteClick(null, null);
                    auto_write = false;
                }
            }

            ShowStatus();
        }
コード例 #23
0
ファイル: MainForm.cs プロジェクト: Sryn/springcard.pcsc.sdk
        void UpdateReaderState(string ReaderName, uint ReaderState, CardBuffer CardAtr)
        {
            Console.WriteLine(DateTime.Now.ToString(NowFormat));
            Console.WriteLine("\tStatus changed for '" + ReaderName + "'");
            Console.WriteLine("\t\tState: " + SCARD.ReaderStatusToString(ReaderState));
            if (CardAtr != null)
            {
                Console.WriteLine("\t\tATR: " + CardAtr.AsString(" "));
            }

            for (int i = 0; i < lvReaders.Items.Count; i++)
            {
                EXImageListViewItem item = (EXImageListViewItem)lvReaders.Items[i];

                if (item.MyValue.Equals(ReaderName))
                {
                    /* Reader found in the list */
                    /* ------------------------ */

                    lvReaders.BeginUpdate();

                    /* Set status image */
                    int    statusImage;
                    string statusText;

                    if ((ReaderState & SCARD.STATE_PRESENT) != 0)
                    {
                        /* Card is present */
                        if ((ReaderState & SCARD.STATE_INUSE) != 0)
                        {
                            /* Card in use */
                            if ((ReaderState & SCARD.STATE_EXCLUSIVE) != 0)
                            {
                                /* Card in exclusive use */
                                statusText  = "In use (exclusive)";
                                statusImage = StatusImageExclusive;
                            }
                            else
                            {
                                statusText  = "In use (shared)";
                                statusImage = StatusImageInUse;
                            }
                        }
                        else
                        if ((ReaderState & SCARD.STATE_MUTE) != 0)
                        {
                            /* Card is mute */
                            statusText  = "Mute";
                            statusImage = StatusImageMute;
                        }
                        else
                        if ((ReaderState & SCARD.STATE_UNPOWERED) != 0)
                        {
                            /* Card is not powered */
                            statusText  = "Present, not powered";
                            statusImage = StatusImagePresent;
                        }
                        else
                        {
                            /* Card is powered */
                            statusText  = "Present, powered";
                            statusImage = StatusImagePresent;
                        }
                    }
                    else
                    if ((ReaderState & SCARD.STATE_UNAVAILABLE) != 0)
                    {
                        /* Problem */
                        statusText  = "Reserved (direct)";
                        statusImage = StatusImageUnavailable;
                    }
                    else
                    if ((ReaderState & SCARD.STATE_IGNORE) != 0)
                    {
                        /* Problem */
                        statusText  = "Error (ignore)";
                        statusImage = StatusImageError;
                    }
                    else
                    if ((ReaderState & SCARD.STATE_UNKNOWN) != 0)
                    {
                        /* Problem */
                        statusText  = "Error (status unknown)";
                        statusImage = StatusImageUnknown;
                    }
                    else
                    if ((ReaderState & SCARD.STATE_EMPTY) != 0)
                    {
                        /* No card */
                        statusText  = "Absent";
                        statusImage = StatusImageAbsent;
                    }
                    else
                    {
                        /* Problem */
                        statusText  = "Bad status";
                        statusImage = StatusImageError;
                    }

                    EXImageListViewSubItem subitem = (EXImageListViewSubItem)item.SubItems[2];
                    subitem.MyImage       = statusImages.Images[statusImage];
                    item.SubItems[3].Text = statusText;

                    if (CardAtr != null)
                    {
                        item.SubItems[4].Text = CardAtr.AsString("");
                    }
                    else
                    {
                        item.SubItems[4].Text = "";
                    }

                    lvReaders.EndUpdate();
                    break;
                }
                /* NB : we ignore the event in case the reader is not already listed */
            }
        }
コード例 #24
0
 public LLCP_PDU(CardBuffer Buffer)
 {
     _bytes = Buffer.GetBytes();
 }
コード例 #25
0
ファイル: MainForm.cs プロジェクト: Sryn/springcard.pcsc.sdk
        void ReaderStatusChanged(uint ReaderState, CardBuffer CardAtr)
        {
            /* The ReaderStatusChanged function is called as a delegate (callback) by the SCardReader object    */
            /* within its backgroung thread. Therefore we must use the BeginInvoke syntax to switch back from   */
            /* the context of the background thread to the context of the application's main thread. Overwise   */
            /* we'll get a security violation when trying to access the window's visual components (that belong */
            /* to the application's main thread and can't be safely manipulated by background threads).         */
            if (InvokeRequired)
            {
                this.BeginInvoke(new ReaderStatusChangedInvoker(ReaderStatusChanged), ReaderState, CardAtr);
                return;
            }

            string s = SCARD.ReaderStatusToString(ReaderState);

            Trace.WriteLine("ReaderStatusChanged: " + s);
            eReaderStatus.Text = s;

            if (CardAtr != null)
            {
                s             = CardAtr.AsString(" ");
                eCardAtr.Text = s;
                Trace.WriteLine("\t" + s);
            }
            else
            {
                eCardAtr.Text = "";
            }

            if (ReaderState == SCARD.STATE_UNAWARE)
            {
                if (llcp != null)
                {
                    llcp.Stop();
                    llcp = null;
                }

                MessageBox.Show("The reader we were working on has disappeared from the system. This application will terminate now.",
                                "The reader has been removed",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation);

                Application.Exit();
            }
            else if ((ReaderState & SCARD.STATE_UNAVAILABLE) != 0)
            {
                Trace.WriteLine("Card unavailable");
            }
            else if ((ReaderState & SCARD.STATE_MUTE) != 0)
            {
                Trace.WriteLine("Card mute");
            }
            else if ((ReaderState & SCARD.STATE_INUSE) != 0)
            {
                Trace.WriteLine("Card in use");
            }
            else if ((ReaderState & SCARD.STATE_EMPTY) != 0)
            {
                Trace.WriteLine("Card absent");

                if (llcp != null)
                {
                    Trace.WriteLine("*** Target lost ***");

                    llcp.Stop();
                    llcp = null;

                    PerformStatusChange();
                }

                pControl.Enabled = true;
            }
            else if ((ReaderState & SCARD.STATE_PRESENT) != 0)
            {
                Trace.WriteLine("Card present");

                if ((llcp == null) && ((ReaderState & SCARD.STATE_INUSE) == 0))
                {
                    /* Try to work with this card, it may be a LLCP peer */
                    reader.StopMonitor();

                    pControl.Enabled = false;
                    Trace.WriteLine("*** Starting LLCP ***");

                    llcp = new LlcpInitiator(reader);

                    switch (status)
                    {
                    case Status.SendAndRecv_Ready:
                        /* We are both a receiver and a sender */
                        StartReceiver();
                        StartSender();
                        break;

                    case Status.RecvOnly_Ready:
                    case Status.RecvThenSend_RecvReady:
                    case Status.SendThenRecv_RecvReady:
                        /* We are a receiver */
                        StartReceiver();
                        break;

                    case Status.SendOnly_Ready:
                    case Status.RecvThenSend_SendReady:
                    case Status.SendThenRecv_SendReady:
                        /* We are a sender */
                        StartSender();
                        break;

                    default:
                        break;
                    }

                    if (!llcp.Start())
                    {
                        Trace.WriteLine("*** Failed to start LLCP ***");
                        MessageBox.Show("Failed to instantiate LLCP layer on the newly inserted card. This is likely to be caused by another application taking control of the card before us. Please close all other PC/SC-aware applications. It may also be required to instruct Windows to stop probing the card, see the paragraph pcsc_no_minidriver in the Readme of the PC/SC SDK for more informations.", "Communication error");
                        llcp             = null;
                        pControl.Enabled = true;
                    }

                    reader.StartMonitor(new SCardReader.StatusChangeCallback(ReaderStatusChanged));
                }
            }
        }
コード例 #26
0
        public static bool RecognizeAtr(SCardChannel channel)
        {
            CardBuffer atr = channel.CardAtr;

            return(RecognizeAtr(atr));
        }
コード例 #27
0
        /// <summary>
        /// Callback used when the reader's status change
        /// As this method is called from a thread, you can't directly modify the user interface
        /// </summary>
        /// <param name="readerState"></param>
        /// <param name="cardAtr"></param>
        private void readerStatusChanged(uint readerState, CardBuffer cardAtr)
        {
            // When you are in a thread you can't directly modify the user interface
            if (InvokeRequired)
            {
                this.BeginInvoke(new readerStatusChangedInvoker(readerStatusChanged), readerState, cardAtr);

                return;
            }

            lblCardUid.Text  = "";
            lblCardAtr.Text  = "";
            lblCardType.Text = "";
            lblProtocol.Text = "";


            lblMonto.BackColor = Color.FromArgb(240, 240, 240);

            pctColor.BackColor = Color.FromArgb(255, 0, 0);


            //  pctFoto.Image = Properties.Resources.atleta;


            lblStatus.Text = SCARD.ReaderStatusToString(readerState);

            if (cardAtr != null)
            {
                lblCardAtr.Text = cardAtr.AsString(" ");
                channel         = new SCardChannel(reader);


                pctColor.BackColor = Color.FromArgb(121, 174, 235);

                //   pctFoto.Image = Properties.Resources.atleta;
                //    pctFoto.SizeMode = PictureBoxSizeMode.StretchImage;


                lblCedula.Text      = "Cédula: ";
                lblId.Text          = "Identificación: ";
                lblEstatus.Text     = "Cobrado: ";
                lblTotal.Text       = "Total: ";
                lblMonto.Text       = "Retraso: ";
                lblNombreNino.Text  = "";
                lblDeporteNino.Text = "";

                pctFoto.Image = Properties.Resources.atleta;
                pctCara.Image = Properties.Resources.blanco;

                if (!channel.Connect())
                {
                    lblCardUid.Text = "Error, no puede connectar la tarjeta";

                    return;
                }
                CAPDU capdu = new CAPDU(0xFF, 0xCA, 0x00, 0x00);    // Command sent to the reader
                RAPDU rapdu = channel.Transmit(capdu);              // Response sent from card

                if (connectCard())
                {
                    string cardUID = getcardUID();
                    lblCardUid.Text = cardUID;
                    lblUid2.Text    = cardUID;
                    lblST.Text      = "OK";
                    lblST.ForeColor = Color.FromArgb(34, 177, 76);



                    string aux = "Data Source=" + conexion.Fuente + ";Initial Catalog=" + conexion.Catalogo + ";User ID=" + conexion.User + ";Password="******"Select * from datos where brasalete =@zip";
                    try
                    {
                        SqlCommand cmd = new SqlCommand(consulta, conn);
                        cmd.Parameters.AddWithValue("@zip", cardUID);

                        conn.Open();
                        cmd.CommandType = CommandType.Text;
                        SqlDataReader dr = cmd.ExecuteReader();


                        while (dr.Read())
                        {
                            //   pctFoto.Image = Properties.Resources.lala;
                            pctFoto.Image    = new Bitmap(conexion.RutaImg + dr[1].ToString() + ".jpg");
                            pctFoto.SizeMode = PictureBoxSizeMode.StretchImage;

                            lblId.Text      = "Identificación: " + dr[0].ToString();
                            lblCedula.Text  = "Cédula: " + dr[1].ToString();
                            lblTotal.Text   = " Total: B/. " + dr[3].ToString();
                            lblEstatus.Text = "Cobrado:  B/. " + dr[4].ToString() + "  " + "Pendiente: B/. " + dr[5].ToString();

                            lblNombreNino.Text  = dr[0].ToString();
                            lblDeporteNino.Text = dr[2].ToString();

                            string monto = dr[10].ToString();
                            lblMonto.Text = "Retraso: " + monto + "  Meses";
                            switch (monto)
                            {
                            case "1":
                                // celeste
                                lblMonto.ForeColor = Color.FromArgb(121, 174, 235);
                                pctCara.Image      = Properties.Resources.caraFeliz;
                                break;

                            case "2":
                                // amarillo
                                lblMonto.BackColor = Color.FromArgb(255, 247, 0);
                                pctCara.Image      = Properties.Resources.caraTriste;
                                //  pctFoto.
                                break;

                            case "3":
                                // rojo
                                lblMonto.ForeColor = Color.FromArgb(255, 0, 0);
                                pctCara.Image      = Properties.Resources.llorando;
                                break;

                            // rojo
                            default:
                                lblMonto.ForeColor = Color.FromArgb(255, 0, 0);
                                pctCara.Image      = Properties.Resources.blanco;
                                break;
                            }


                            dr.GetString(1);
                            break;
                        }


                        dr.Close();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open)
                        {
                            conn.Close();
                        }
                    }
                }//fin de connect card()
                 //----------------------------------------------------------------



                /*
                 *
                 * if (rapdu.SW != 0x9000)                              // Something failed
                 * {
                 *  lblCardUid.Text = "Get UID APDU fallido!";
                 *  return;
                 * }
                 */
                // Display card's UID formated as an hexadecimal string

                /*
                 * byte[] rapduB = rapdu.data.GetBytes();
                 * string hexadecimalResult = BitConverter.ToString(rapduB);
                 *
                 * lblCardUid.Text = hexadecimalResult.Replace("-", " ");
                 */


                // Card's type
                if (cardAtr.Length >= 19)
                {
                    // Card's protocol
                    int cardProdocol = cardAtr[12];
                    if (protocols.ContainsKey(cardProdocol))
                    {
                        lblProtocol.Text = protocols[cardProdocol];
                    }

                    if (cardAtr[4] == 0x80 && cardAtr[5] == 0x4F && cardAtr[6] == 0x0C && cardAtr[7] == 0xA0 && cardAtr[8] == 0x00 && cardAtr[9] == 0x00 && cardAtr[10] == 0x03 && cardAtr[11] == 0x06)
                    {
                        string pixSs = cardAtr[13].ToString("X2") + cardAtr[14].ToString("X2");
                        lblCardType.Text = "Wired-logic: ";
                        if (cardsNames.ContainsKey(pixSs))
                        {
                            lblCardType.Text += cardsNames[pixSs];
                        }
                    }
                    else
                    {
                        lblCardType.Text = "Desconocido tipo de tarjeta";
                    }
                }
                else
                {
                    lblCardType.Text = "Smartcard";
                }
            }
        }
コード例 #28
0
 public RtdMedia(string MimeType, string TextContent) : base(NDEF_HEADER_TNF_MEDIA_TYPE, MimeType)
 {
     _payload = CardBuffer.BytesFromString(TextContent);
 }
コード例 #29
0
        /// <summary>
        /// Callback used when the reader's status change
        /// As this method is called from a thread, you can't directly modify the user interface
        /// </summary>
        /// <param name="readerState"></param>
        /// <param name="cardAtr"></param>
        private void readerStatusChanged(uint readerState, CardBuffer cardAtr)
        {
            // When you are in a thread you can't directly modify the user interface
            if (InvokeRequired)
            {
                this.BeginInvoke(new readerStatusChangedInvoker(readerStatusChanged), readerState, cardAtr);
                return;
            }

            lblCardUid.Text  = "";
            lblCardAtr.Text  = "";
            lblCardType.Text = "";
            lblProtocol.Text = "";
            lblStatus.Text   = SCARD.ReaderStatusToString(readerState);

            if (cardAtr != null)
            {
                lblCardAtr.Text = cardAtr.AsString(" ");
                channel         = new SCardChannel(reader);
                if (!channel.Connect())
                {
                    lblCardUid.Text = "Error, can't connect to the card";
                    return;
                }
                CAPDU capdu = new CAPDU(0xFF, 0xCA, 0x00, 0x00);    // Command sent to the reader
                RAPDU rapdu = channel.Transmit(capdu);              // Response sent from card
                if (rapdu.SW != 0x9000)                             // Something failed
                {
                    lblCardUid.Text = "Get UID APDU failed!";
                    return;
                }
                // Display card's UID formated as an hexadecimal string
                byte[] rapduB            = rapdu.data.GetBytes();
                string hexadecimalResult = BitConverter.ToString(rapduB);
                lblCardUid.Text = hexadecimalResult.Replace("-", " ");

                // Card's type
                if (cardAtr.Length >= 19)
                {
                    // Card's protocol
                    int cardProdocol = cardAtr[12];
                    if (protocols.ContainsKey(cardProdocol))
                    {
                        lblProtocol.Text = protocols[cardProdocol];
                    }

                    if (cardAtr[4] == 0x80 && cardAtr[5] == 0x4F && cardAtr[6] == 0x0C && cardAtr[7] == 0xA0 && cardAtr[8] == 0x00 && cardAtr[9] == 0x00 && cardAtr[10] == 0x03 && cardAtr[11] == 0x06)
                    {
                        string pixSs = cardAtr[13].ToString("X2") + cardAtr[14].ToString("X2");
                        lblCardType.Text = "Wired-logic: ";
                        if (cardsNames.ContainsKey(pixSs))
                        {
                            lblCardType.Text += cardsNames[pixSs];
                        }
                    }
                    else
                    {
                        lblCardType.Text = "Unknow card type";
                    }
                }
                else
                {
                    lblCardType.Text = "Smartcard";
                }
            }
        }
コード例 #30
0
        void ReaderStatusChanged(uint readerState, CardBuffer cardAtr)
        {
            try
            {
                string msg;

                if (InvokeRequired)
                {
                    this.BeginInvoke(new ReaderStatusChangedInvoker(ReaderStatusChanged), readerState, cardAtr);
                    return;
                }

                SCARD.ReaderStatusToString(readerState);

                if (cardAtr != null)
                {
                    _tagATR = RemoveSpaces(cardAtr.AsString(" "));
                }
                else
                {
                }

                if (readerState == SCARD.STATE_UNAWARE)
                {
                    if (_cardchannel != null)
                    {
                        _cardchannel.Disconnect();
                        _cardchannel = null;
                    }

                    if (!_inLoop)
                    {
                        msg = "The reader we were working with has gone AWOL from the system.";
                        WarnNotify("Warning|" + msg);
                        _inLoop = true;
                    }

                    tmrTagMonitor.Enabled = true;
                    msg = "Reader not Found. Please check Connection.";
                    WarnNotify("Warning|" + msg);
                }
                else if ((readerState & SCARD.STATE_EMPTY) != 0)
                {
                    _tag    = null;
                    _inLoop = false;

                    _studentData = null;
                    InfoNotify("Ready|Please insert another card for Tagging");

                    if (_cardchannel == null)
                    {
                        return;
                    }

                    _cardchannel.Disconnect();
                    _cardchannel = null;
                }
                else if ((readerState & SCARD.STATE_UNAVAILABLE) != 0)
                {
                }
                else if ((readerState & SCARD.STATE_MUTE) != 0)
                {
                }
                else if ((readerState & SCARD.STATE_INUSE) != 0)
                {
                    _inLoop = false;
                }
                else if ((readerState & SCARD.STATE_PRESENT) != 0)
                {
                    _inLoop = false;
                    if (_cardchannel != null)
                    {
                        return;
                    }

                    _cardchannel = new SCardChannel(DeviceManager.DeviceSpec.Nfc);

                    if (_cardchannel.Connect())
                    {
                        var mifare = new MiFareCardProg();
                        _tagUID = RemoveSpaces(mifare.GetUID(DeviceManager.DeviceSpec.Nfc).Trim());

                        _cardthread = new Thread(card_read_proc);
                        _cardthread.Start();
                    }
                    else
                    {
                        msg =
                            "NearField failed to connect to the card in the reader. Check that you don't have another application running in background that tries to work with the smartcards in the same time as NearField";
                        WarnNotify("Warning|" + msg);
                        _cardchannel = null;
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorHandler.TreatError(ex);
            }
        }