Example #1
0
        void HandleNewTag(object sender, NfcTag e)
        {
            var                       contentRead        = Encoding.ASCII.GetString(e.NdefMessage[0].Payload);
            string                    serialNumber       = BitConverter.ToString(e.Id);
            var                       r                  = new CrudApi(App.btoken);
            Uri                       restUri            = new Uri(Constants.RestURLAddAttendance);
            string                    NFCContentUploaded = Guid.NewGuid().ToString();
            AddAttendanceBody         body               = new AddAttendanceBody(serialNumber, contentRead, NFCContentUploaded);
            AddAttendanceResponseBody responseBody       = null;

            try
            {
                var spRecord = new NdefTextRecord
                {
                    Payload = Encoding.ASCII.GetBytes(NFCContentUploaded)
                };
                var msg = new NdefMessage {
                    spRecord
                };
                device.WriteTag(msg);
                responseBody = Task.Run(async() =>
                                        { return(await r.PostAsync <AddAttendanceBody, AddAttendanceResponseBody>(restUri, body)); }).Result;
                string text = responseBody.EmployeeInfo + " succesfully added attendance no." + responseBody.ID + " on point " + System.Environment.NewLine + responseBody.TagInfo;
                ShowSuccess(text);
            }
            catch (Exception excp)
            {
                ShowFail("An error occurred.");
                DependencyService.Get <IAudio>().PlayMp3File("door.mp3");
                return;
            }
            Device.StartTimer(System.TimeSpan.FromSeconds(5), () => { ShowBasic(); return(true); });
            return;
        }
Example #2
0
 /* <summary>
  * void parse_record
  * Constructs NDEF record from given byte array. Parsing fails if the NDEF tag is not valid.
  * </summary>
  *
  * <remarks>
  * If you know that NDEF tag is legit all you have to worry about is passing the right chunk of
  * bytes to the function. NDEF tag starts with "D1" byte and ends IN "FE" byte.
  * </remarks>
  *
  * //TODO: expand for all types of NDEF records
  */
 static void parse_record(NdefMessage ndefMessage)
 {
     foreach (NdefRecord record in ndefMessage)
     {
         Debug.WriteLine("Record type: " + Encoding.UTF8.GetString(record.Type, 0, record.Type.Length));
         // Check the type of each record - handling a Smart Poster, URI and Text record in this example
         var specializedType = record.CheckSpecializedType(false);
         if (specializedType == typeof(NdefSpRecord))
         {
             // Convert and extract Smart Poster info
             var spRecord = new NdefSpRecord(record);
             Debug.WriteLine("URI: " + spRecord.Uri);
             Debug.WriteLine("Titles: " + spRecord.TitleCount());
             Debug.WriteLine("1. Title: " + spRecord.Titles[0].Text);
             Debug.WriteLine("Action set: " + spRecord.ActionInUse());
             // You can also check the action (if in use by the record),
             //mime type and size of the linked content.
         }
         else if (specializedType == typeof(NdefUriRecord))
         {
             // Convert and extract URI info
             var uriRecord = new NdefUriRecord(record);
             Debug.WriteLine("URI: " + uriRecord.Uri);
         }
         else if (specializedType == typeof(NdefTextRecord))
         {
             // Convert and extract Text record info
             var textRecord = new NdefTextRecord(record);
             Debug.WriteLine("Text: " + textRecord.Text);
             Debug.WriteLine("Language code: " + textRecord.LanguageCode);
             var textEncoding = (textRecord.TextEncoding == NdefTextRecord.TextEncodingType.Utf8 ? "UTF-8" : "UTF-16");
             Debug.WriteLine("Encoding: " + textEncoding);
         }
     }
 }
Example #3
0
        private async void DoWriteTag()
        {
            WritingTag = true;
            Result     = "";

            NdefLibrary.Ndef.NdefMessage message = new NdefMessage();
            NdefTextRecord record = new NdefTextRecord();

            record.LanguageCode = "en";
            record.TextEncoding = NdefTextRecord.TextEncodingType.Utf8;
            record.Text         = Message;
            message.Add(record);

            var result = await _writeTask.WriteTag(message);

            if (result.DidSucceed)
            {
                Result = "Wrote Message to tag with ID " + result.NFCTag.Id;
            }
            else
            {
                switch (result.ReasonForFailure)

                {
                case FailureReasons.TagReadOnly:
                    Result = "The tag was read only";
                    break;

                case FailureReasons.TagTooSmall:
                    Result = "The tag was too small for this message";

                    break;

                case FailureReasons.ErrorDuringWrite:
                    Result = "An error occured whislt trying to write the tag";

                    break;

                case FailureReasons.UnableToFormatTag:
                    Result = "The tag was not formatted. Please format it first";

                    break;

                case FailureReasons.Unkown:
                    Result = "An unkown error occured";

                    break;

                case FailureReasons.TagLostDuringWrite:
                    Result = "The tag was removed whilst it was been written to";

                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            WritingTag = false;
        }
Example #4
0
        private void InvokeKeyboardFeature(ResponseFrame frame, Exception e)
        {
            if (CheckForErrorsOrTimeout(frame, e))
            {
                return;
            }
            else
            {
                byte[] data = frame.Data;

                byte[] temp = new byte[data.Length - data[1] - 2];

                if (temp.Length > 0)
                {
                    Array.Copy(data, 2 + data[1], temp, 0, temp.Length);

                    NdefMessage message = NdefMessage.FromByteArray(temp);

                    int numRecords = message.Count;
                    int recordNum  = 1;

                    Action EnterKeystrokes = () =>
                    {
                        foreach (NdefRecord record in message)
                        {
                            string type = Encoding.UTF8.GetString(record.Type);
                            if (type.Equals("T"))
                            {
                                NdefTextRecord textRecord = new NdefTextRecord(record);
                                System.Windows.Forms.SendKeys.SendWait(textRecord.Text);
                                if (keyboardModeLineBreak)
                                {
                                    System.Windows.Forms.SendKeys.SendWait("{ENTER}");
                                }
                                if (keyboardModeTab)
                                {
                                    System.Windows.Forms.SendKeys.SendWait("{TAB}");
                                }
                                if (keyboardModeTabLineBreakLast)
                                {
                                    if (recordNum == numRecords)
                                    {
                                        System.Windows.Forms.SendKeys.SendWait("{ENTER}");
                                    }
                                    else
                                    {
                                        System.Windows.Forms.SendKeys.SendWait("{TAB}");
                                    }
                                }

                                recordNum++;
                            }
                        }
                    };

                    Dispatcher.BeginInvoke(EnterKeystrokes);
                }
            }
        }
Example #5
0
        private void OnMessageReceived(ProximityDevice sender, ProximityMessage message)
        {
            var stopwatch = (Stopwatch)null;

            if (Debug)
            {
                stopwatch = new Stopwatch();
                stopwatch.Start();
            }

            var rawMessage = message.Data.ToArray();

            NdefMessage ndefMessage;

            try
            {
                ndefMessage = NdefMessage.FromByteArray(rawMessage);
            }
            catch (NdefException e)
            {
                var exceptionArgs = new DeviceStatusChangedEventArgs()
                {
                    DeviceStatus = StatusEnum.DeviceArrived
                };
                if (Debug)
                {
                    stopwatch.Stop();
                    exceptionArgs.ExecutionTime = stopwatch.Elapsed;
                }
                OnDeviceStatusChanged(this, exceptionArgs);
                return;
            }

            var args = new MessageArrivedEventArgs()
            {
                DeviceStatus = StatusEnum.MessageReceived
            };

            foreach (NdefRecord record in ndefMessage)
            {
                if (NdefTextRecord.IsRecordType(record))
                {
                    NdefTextRecord textRecord = new NdefTextRecord(record);
                    args.Message = textRecord.Text;
                    break;
                }
            }

            if (Debug)
            {
                stopwatch.Stop();
                args.ExecutionTime = stopwatch.Elapsed;
                args.MethodName    = "TagReader.OnMessageReceived";
            }

            OnDeviceStatusChanged(this, args);
            OnMessageArrived(this, args);
        }
Example #6
0
        private void btnReadAll_Click(object sender, EventArgs e)
        {
            if (!connActive)
            {
                return;
            }

            string tmpStr = string.Empty;
            int    startBlock = 4, endBlock = 0, dataLength = 0, dataAllLength;
            int    dataPageIndex = 0;

            byte[] recvData = new byte[6];
            recvData = ReadDataFromCard(startBlock, 4);

            dataLength    = recvData[1];
            dataAllLength = dataLength + 3;

            if (dataLength > 0)
            {
                byte[] effectiveData = new byte[dataLength];

                effectiveData[0] = recvData[2];
                effectiveData[1] = recvData[3];

                endBlock = dataAllLength % 4 == 0 ? dataAllLength / 4 + startBlock : dataAllLength / 4 + startBlock + 1;

                for (int iBlock = startBlock + 1; iBlock < endBlock; iBlock++)
                {
                    recvData = ReadDataFromCard(iBlock, 4);

                    for (int iBit = 0; iBit < 4; iBit++)
                    {
                        if ((dataPageIndex * 4 + iBit + 2) < effectiveData.Length)
                        {
                            effectiveData[dataPageIndex * 4 + iBit + 2] = recvData[iBit];
                        }
                    }
                    dataPageIndex++;
                }

                try
                {
                    NdefMessage message = NdefMessage.FromByteArray(effectiveData);
                    NdefRecord  record  = message[0];

                    if (record.CheckSpecializedType(false) == typeof(NdefTextRecord))
                    {
                        //Convert and extract Smart Poster info
                        var textRecord = new NdefTextRecord(record);

                        WriteLog(3, 0, textRecord.Text);
                    }
                }
                catch
                {
                }
            }
        }
 //Čitanje Tag-a sa NFC-a koda koji kasnije prebacivamo u applikaciju koji nam služi
 //za izmjenu rezerviranog u posuđeno u bazi podataka publikacije
 private void readNDEFMEssage(NdefMessage message)
 {
     foreach (NdefRecord record in message)
     {
         if (record.CheckSpecializedType(false) == typeof(NdefTextRecord))
         {
             var spRecord = new NdefTextRecord(record);
             convertedMessage = int.Parse(spRecord.Text);
         }
     }
 }
Example #8
0
        public static string readNDEFPlainText(NdefMessage message)
        {
            if (message == null)
            {
                return("Tag is empty");
            }

            NdefTextRecord record = new NdefTextRecord(message.ElementAtOrDefault(0));

            return(record.Text);
        }
Example #9
0
        public static NdefMessage makeTextNDEFRecord(string NDEFPayload)
        {
            var ndefRecord = new NdefTextRecord()
            {
                Text = NDEFPayload
            };

            NdefMessage ndefMessage = new NdefMessage();

            ndefMessage.Add(ndefRecord);
            return(ndefMessage);
        }
Example #10
0
        //
        // Write Multi Ndef Tab
        //

        private void WriteMultNdef(object send, RoutedEventArgs e)
        {
            NdefMessage message = new NdefMessage();

            foreach (Row row in table)
            {
                if (row.Selected.Equals("Text"))
                {
                    NdefTextRecord temp = new NdefTextRecord()
                    {
                        TextEncoding = NdefTextRecord.TextEncodingType.Utf8,
                        LanguageCode = "en",
                        Text         = row.Content ?? ""
                    };
                    message.Add(temp);
                }
                else
                {
                    message.Add(new NdefUriRecord()
                    {
                        Uri = row.Content ?? ""
                    });
                }
            }

            ShowPendingStatus("Waiting for tap");

            Command  cmd           = new WriteCustomNdef((byte)timeout.Value, (bool)lockCheckBox.IsChecked, message);
            Callback repeatCommand = null;
            bool     repeat        = (bool)repeatMultiNdefWrite.IsChecked;
            Action   sendCommand   = () => tappy.SendCommand(cmd, ResponseCallback + repeatCommand);

            repeatCommand = (ResponseFrame frame, Exception exc) =>
            {
                if (repeat)
                {
                    if (CheckForErrorsOrTimeout(frame, exc))
                    {
                        return;
                    }
                    Thread.Sleep(1000);
                    ShowPendingStatus("Waiting for tap");
                    Dispatcher.BeginInvoke(sendCommand);
                }
            };

            tappy.SendCommand(cmd, ResponseCallback + repeatCommand);
        }
Example #11
0
        private async void messageReceivedHandler(ProximityDevice device, ProximityMessage message)
        {
            var rawMsg = message.Data.ToArray();

            var ndefMessage = NdefMessage.FromByteArray(rawMsg);

            foreach (NdefRecord record in ndefMessage)
            {
                if (record.CheckSpecializedType(false) == typeof(NdefTextRecord))
                {
                    var spRecord    = new NdefTextRecord(record);
                    var receivedOTP = spRecord.Text.Replace("YubiCryptOTP=", string.Empty);
                    await FillOTPCodeInput(receivedOTP);
                }
            }
        }
Example #12
0
        public static string getNdefFromByteArray(byte[] readData)
        {
            //Create Ndef message
            string      phone   = String.Empty;
            NdefMessage message = NdefMessage.FromByteArray(readData);

            //Loop through the records
            foreach (NdefRecord record in message)
            {
                if (record.CheckSpecializedType(false) == typeof(NdefTextRecord))
                {
                    var textRecord = new NdefTextRecord(record);
                    phone = textRecord.Text;
                }
            }
            return(phone);
        }
Example #13
0
        public MessageViewModel(NdefLibrary.Ndef.NdefRecord message)
        {
            Type type = message.CheckSpecializedType(true);

            Type = type.Name;
            Info = "Feel free to add this mapping to the message view model";
            if (type == typeof(NdefLibrary.Ndef.NdefTextRecord))
            {
                var text = new NdefTextRecord(message);
                Info = string.Format("The message on the tag is \"{0}\". The language is \"{1}\"", text.Text,
                                     text.LanguageCode);
            }
            if (type == typeof(NdefLibrary.Ndef.NdefUriRecord))
            {
                var text = new NdefUriRecord(message);
                Info = string.Format("The URI on the tag is \"{0}\"", text.Uri);
            }
        }
Example #14
0
        public static String ProcessNFCRecord(NdefRecord record)
        {
            //Define the tag content we want to return.
            String tagContent = null;

            //Make sure we have a record.
            if (record != null)
            {
                //Check if the record is a URL.
                if (record.CheckSpecializedType(true) == typeof(NdefUriRecord))
                {
                    //The content is a URL.
                    tagContent = new NdefUriRecord(record).Uri;
                }
                else if (record.CheckSpecializedType(true) == typeof(NdefMailtoRecord))
                {
                    //The content is a mailto record.
                    tagContent = new NdefMailtoRecord(record).Uri;
                }
                else if (record.CheckSpecializedType(true) == typeof(NdefTelRecord))
                {
                    //The content is a tel record.
                    tagContent = new NdefTelRecord(record).Uri;
                }
                else if (record.CheckSpecializedType(true) == typeof(NdefSmsRecord))
                {
                    //The content is a sms record.
                    tagContent = new NdefSmsRecord(record).Uri;
                }
                else if (record.CheckSpecializedType(true) == typeof(NdefTextRecord))
                {
                    //The content is a text record.
                    tagContent = new NdefTextRecord(record).Text;
                }
                else
                {
                    //Try and force a pure text conversion.
                    tagContent = Encoding.UTF8.GetString(record.Payload);
                }
            }

            //Return the tag content.
            return(tagContent);
        }
Example #15
0
        public ObservableCollection <string> ReadNdefMessage(NdefMessage message)
        {
            ObservableCollection <string> collection = new ObservableCollection <string>();

            if (message == null)
            {
                return(collection);
            }

            foreach (NdefRecord record in message)
            {
                if (record.CheckSpecializedType(false) == typeof(NdefTextRecord))
                {
                    var textRecord = new NdefTextRecord(record);
                    collection.Add(textRecord.Text);
                }
            }
            return(collection);
        }
Example #16
0
        // We have received a new NFC message, for now just see what it is.
        // TODO: send it to BLE device
        private void messagedReceived(ProximityDevice device, ProximityMessage m)
        {
            uint x = m.Data.Length;

            byte[] b = new byte[x];
            b = m.Data.ToArray();

            NdefMessage ndefMessage = NdefMessage.FromByteArray(b);

            foreach (NdefRecord record in ndefMessage)
            {
                if (record.CheckSpecializedType(false) == typeof(NdefTextRecord))
                {
                    var textRecord = new NdefTextRecord(record);
                    Debug.WriteLine("\nTEXT: " + textRecord.Text);
                    NFCText  = textRecord.Text;
                    bNFCText = true;
                }
            }
        }
Example #17
0
        //-------------------------------------------------------------------------odczytaj wiadomosc NDEF
        private void ReadMsg(ProximityDevice sender, ProximityMessage msg)
        {
            var rawMsg      = msg.Data.ToArray();
            var ndefMessage = NdefMessage.FromByteArray(rawMsg);

            if (ndefMessage[0].CheckSpecializedType(false) == typeof(NdefTextRecord))
            {
                var firstRecord = new NdefTextRecord(ndefMessage[0]);
                if (firstRecord.Text.Equals("no8g-Sj5i-i8aw6"))
                {
                    List <String> connectionData = new List <String>();
                    var           secondRecord   = new NdefTextRecord(ndefMessage[1]);
                    var           thirdRecord    = new NdefTextRecord(ndefMessage[2]);
                    var           fourthRecord   = new NdefTextRecord(ndefMessage[3]);
                    connectionData.Add(secondRecord.Text);
                    connectionData.Add(thirdRecord.Text);
                    connectionData.Add(fourthRecord.Text);
                    Receiving(connectionData);
                }
            }
        }
Example #18
0
        //-------------------------------------------------------------------------wiadomosc NDEF
        private NdefMessage mNdefMessage()
        {
            var validateRecord = new NdefTextRecord {
                Text = "ngi8aw6", LanguageCode = "en"
            };
            var deviceNameRecord = new NdefTextRecord {
                Text = deviceName, LanguageCode = "en"
            };
            var fileNameRecord = new NdefTextRecord {
                Text = file.Name, LanguageCode = "en"
            };
            var fileSizeRecord = new NdefTextRecord {
                Text = fileSize.ToString(), LanguageCode = "en"
            };
            var androidAppRecord = new NdefAndroidAppRecord {
                PackageName = "com.nfcbluetoothapp.nfcbluetoothapp"
            };

            return(new NdefMessage {
                validateRecord, deviceNameRecord, fileNameRecord,
                fileSizeRecord, androidAppRecord
            });
        }
Example #19
0
        private void AddNdefContent(ResponseFrame frame, Exception e)
        {
            if (CheckForErrorsOrTimeout(frame, e))
            {
                return;
            }

            byte[] data = frame.Data;

            byte[] temp = new byte[data.Length - data[1] - 2];

            if (temp.Length > 0)
            {
                Array.Copy(data, 2 + data[1], temp, 0, temp.Length);

                NdefMessage message = NdefMessage.FromByteArray(temp);

                Action update = () =>
                {
                    foreach (NdefRecord record in message)
                    {
                        ndefData.AppendText("Ndef Record:\n\n");

                        if (record.TypeNameFormat == NdefRecord.TypeNameFormatType.Empty)
                        {
                            ndefData.AppendText("Empty NDEF Record");
                        }
                        else
                        {
                            string type = Encoding.UTF8.GetString(record.Type);
                            ndefData.AppendText($"TNF: {record.TypeNameFormat.ToString()} ({(byte)record.TypeNameFormat})\n");
                            ndefData.AppendText($"Type: {type}\n");

                            if (record.Id != null)
                            {
                                ndefData.AppendText($"Type: {BitConverter.ToString(record.Id)}\n");
                            }

                            if (type.Equals("U"))
                            {
                                NdefUriRecord uriRecord = new NdefUriRecord(record);
                                ndefData.AppendText($"Payload: {uriRecord.Uri}\n");
                            }
                            else if (type.Equals("T"))
                            {
                                NdefTextRecord textRecord = new NdefTextRecord(record);
                                ndefData.AppendText($"Encoding: {textRecord.TextEncoding.ToString()}\n");
                                ndefData.AppendText($"Language: {textRecord.LanguageCode}\n");
                                ndefData.AppendText($"Payload: {textRecord.Text}\n");
                            }
                            else if (type.Contains("text"))
                            {
                                ndefData.AppendText($"Payload: {Encoding.UTF8.GetString(record.Payload)}\n");
                            }
                            else
                            {
                                ndefData.AppendText($"Payload: {BitConverter.ToString(record.Payload)}");
                            }

                            ndefData.AppendText($"----------\n");
                        }
                    }
                };

                Dispatcher.BeginInvoke(update);
            }

            ShowSuccessStatus();
        }
Example #20
0
        private void nfcService_MessageReceivedCompleted(ProximityMessage message)
        {
            if (message.MessageType == "WriteableTag")
            {
                Int32 size = System.BitConverter.ToInt32(message.Data.ToArray(), 0);
                tagSize = size;
                LogMessage(AppResources.NfcWriteableTagSize + " " + size + " bytes", NfcLogItem.INFO_ICON);
            }
            else if (message.MessageType == "WindowsMime")
            {
                var buffer   = message.Data.ToArray();
                int mimesize = 0;
                for (mimesize = 0; mimesize < 256 && buffer[mimesize] != 0; ++mimesize)
                {
                }
                ;
                var    mimeType = Encoding.UTF8.GetString(buffer, 0, mimesize);
                string extra    = AppResources.NdefRecordMimeType + ": " + mimeType;
                LogMessage(AppResources.NdefMessageRecordType + ": WindowsMime", NfcLogItem.INFO_ICON, extra);
                return;
            }
            else if (message.MessageType == "NDEF:Unknown")
            {
                LogMessage(AppResources.NdefMessageRecordType + ": " + AppResources.NdefUnknown, NfcLogItem.INFO_ICON);
                return;
            }
            else if (message.MessageType == "NDEF")
            {
                var rawMsg      = message.Data.ToArray();
                var ndefMessage = NdefMessage.FromByteArray(rawMsg);

                // Loop over all records contained in the NDEF message
                string messageInformation = "";
                foreach (NdefRecord record in ndefMessage)
                {
                    string extra = "";
                    messageInformation = AppResources.NdefMessageRecordType + ": " + Encoding.UTF8.GetString(record.Type, 0, record.Type.Length);
                    //if the record is a Smart Poster
                    if (record.CheckSpecializedType(false) == typeof(NdefSpRecord))
                    {
                        // Convert and extract Smart Poster info
                        var spRecord = new NdefSpRecord(record);
                        extra  = AppResources.NdefSpUri + ": " + spRecord.Uri;
                        extra += "\n" + AppResources.NdefSpTitles + ": " + spRecord.TitleCount();
                        extra += "\n" + AppResources.NdefSpTitle + ": " + spRecord.Titles[0].Text;
                        if (spRecord.ActionInUse())
                        {
                            extra += "\n" + AppResources.NdefSpAction + ": " + spRecord.NfcAction;
                        }
                        LogMessage(messageInformation, NfcLogItem.INFO_ICON, extra);
                    }
                    if (record.CheckSpecializedType(false) == typeof(NdefUriRecord))
                    {
                        var uriRecord = new NdefUriRecord(record);
                        extra = AppResources.NdefSpUri + ": " + uriRecord.Uri;
                        LogMessage(messageInformation, NfcLogItem.INFO_ICON, extra);
                    }
                    if (record.CheckSpecializedType(false) == typeof(NdefTextRecord))
                    {
                        var textRecord = new NdefTextRecord(record);
                        extra  = AppResources.NdefTextRecordText + ": " + textRecord.Text;
                        extra += "\n" + AppResources.NdefTextRecordLanguage + ": " + textRecord.LanguageCode;
                        LogMessage(messageInformation, NfcLogItem.INFO_ICON, extra);
                    }
                    if (record.CheckSpecializedType(false) == typeof(NdefLaunchAppRecord))
                    {
                        var launchAppRecord = new NdefLaunchAppRecord(record);
                        foreach (KeyValuePair <string, string> entry in launchAppRecord.PlatformIds)
                        {
                            extra += AppResources.NdefLaunchAppRecordPlatform + ": " + entry.Key + "\n";
                            extra += AppResources.NdefLaunchAppRecordId + ": " + entry.Value + "\n";
                        }
                        extra = extra.TrimEnd('\n');
                        LogMessage(messageInformation, NfcLogItem.INFO_ICON, extra);
                    }
                    if (record.CheckSpecializedType(false) == typeof(NdefAndroidAppRecord))
                    {
                        var androidRecord = new NdefAndroidAppRecord(record);
                        extra = AppResources.NdefAAR + ": " + androidRecord.PackageName;
                        LogMessage(messageInformation, NfcLogItem.INFO_ICON, extra);
                    }
                }
                return;
            }
        }
Example #21
0
        private void WriteDataIntoCard(string data)
        {
            if (!connActive)
            {
                return;
            }

            NdefTextRecord textRecord = new NdefTextRecord()
            {
                Text = data, TextEncoding = NdefTextRecord.TextEncodingType.Utf8
            };
            NdefRecord  record  = new NdefRecord(textRecord);
            NdefMessage message = new NdefMessage {
                record
            };

            byte[] bytes = message.ToByteArray();

            int startBlockNum = 4, totalDataLength = bytes.Length + 3;
            int totalBlock = (totalDataLength % 4 == 0 ? (totalDataLength / 4) : (totalDataLength / 4 + 1));

            byte[] totalData     = new byte[totalBlock * 4];
            int    dataPageIndex = 0;

            totalData[0] = 0x03;
            totalData[1] = (byte)bytes.Length;

            for (int i = 0; i < bytes.Length; i++)
            {
                totalData[i + 2] = bytes[i];
            }
            totalData[totalData[1] + 2] = 0xFE;

            for (int iBlock = startBlockNum; iBlock < totalBlock + startBlockNum; iBlock++)
            {
                ClearBuffers();
                SendBuff[0] = 0xFF;         // CLA
                SendBuff[1] = 0xD6;         // INS
                SendBuff[2] = 0x00;         // P1
                SendBuff[3] = (byte)iBlock; // P2: Starting Block No.
                SendBuff[4] = 0x04;         // P3 : Data length

                for (int idx = 0; idx < 4; idx++)
                {
                    SendBuff[idx + 5] = totalData[(dataPageIndex * 4) + idx];
                }
                SendLen = 9;
                RecvLen = 0x02;

                retCode = SendAPDU(2);

                string tmpStr = string.Empty;
                if (retCode == ModWinsCard.SCARD_S_SUCCESS)
                {
                    tmpStr = "";
                    for (int idx = 0; idx <= RecvLen - 1; idx++)
                    {
                        tmpStr = tmpStr + string.Format("{0:X2}", RecvBuff[idx]);
                    }
                }
                if (tmpStr.Trim() == "9000")
                {
                }
                else
                {
                    WriteLog(4, 0, "Write block error!>>" + tmpStr.Trim());
                }

                dataPageIndex++;
            }
        }
        public void KeyboardWedge(ResponseFrame frame, Exception e)
        {
            DetectSingleNdef repeatRead  = new DetectSingleNdef(0, DetectTagSetting.Type2Type4AandMifare);
            bool             textEntered = false;

            if (CheckForErrorsOrTimeout(frame, e))
            {
                tappy.SendCommand(repeatRead, InvokeKeyboardFeature);
                return;
            }
            else if (frame.CompareCommandFamilies(new byte[] { 0x00, 0x01 }) && frame.ResponseCode == 0x02)
            {
                try
                {
                    byte[] data = frame.Data;
                    byte[] buf  = new byte[data.Length - data[1] - 2];

                    if (buf.Length > 0)
                    {
                        Array.Copy(data, 2 + data[1], buf, 0, buf.Length);

                        NdefMessage message = NdefMessage.FromByteArray(buf);

                        int numRecords = message.Count;
                        int recordNum  = 1;

                        foreach (NdefRecord record in message)
                        {
                            string type = Encoding.UTF8.GetString(record.Type);
                            textEntered = false;
                            if (record.TypeNameFormat == NdefRecord.TypeNameFormatType.NfcRtd && type.Equals("T") && recordTypes.Contains(RecordType.TEXT))
                            {
                                NdefTextRecord textRecord = new NdefTextRecord(record);
                                System.Windows.Forms.SendKeys.SendWait(textRecord.Text);
                                textEntered = true;
                            }
                            else if ((record.TypeNameFormat == NdefRecord.TypeNameFormatType.NfcRtd && type.Equals("U") && recordTypes.Contains(RecordType.URI)) ||
                                     (record.TypeNameFormat == NdefRecord.TypeNameFormatType.Uri && recordTypes.Contains(RecordType.URI)))
                            {
                                NdefUriRecord uriRecord = new NdefUriRecord(record);
                                System.Windows.Forms.SendKeys.SendWait(uriRecord.Uri);
                                textEntered = true;
                            }
                            else if ((record.TypeNameFormat == NdefRecord.TypeNameFormatType.ExternalRtd && recordTypes.Contains(RecordType.EXTERNAL)) ||
                                     (record.TypeNameFormat == NdefRecord.TypeNameFormatType.Mime && recordTypes.Contains(RecordType.MIME)))
                            {
                                System.Windows.Forms.SendKeys.SendWait(Encoding.UTF8.GetString(record.Payload));
                                textEntered = true;
                            }

                            if (textEntered == true && formModeActive == true)
                            {
                                if (recordNum == numRecords)
                                {
                                    System.Windows.Forms.SendKeys.SendWait("{ENTER}");
                                }
                                else
                                {
                                    System.Windows.Forms.SendKeys.SendWait("{TAB}");
                                }
                            }
                            else if (textEntered == true)
                            {
                                if (controlCharacters.Contains(ControlCharacter.CRLF))
                                {
                                    System.Windows.Forms.SendKeys.SendWait("{ENTER}");
                                }
                                if (controlCharacters.Contains(ControlCharacter.TAB))
                                {
                                    System.Windows.Forms.SendKeys.SendWait("{TAB}");
                                }
                            }

                            recordNum++;
                        }

                        if (textEntered)
                        {
                            Thread.Sleep(scanStaggerMs);
                        }
                    }
                    tappy.SendCommand(repeatRead, InvokeKeyboardFeature);
                    return;
                }
                catch
                {
                    Console.WriteLine("Error Parsing NDEF Response From Tappy");
                }
            }
            else
            {
                Console.WriteLine("Invalid TCMP Response From Tappy (i.e not the command family and response code expected)");
            }
        }