Example #1
0
        public Guid PublishUri(Uri uri)
        {
            var key = Guid.NewGuid();

            this.published.Add(key, NdefRecord.CreateUri(uri.AbsoluteUri));

            return(key);
        }
        public NdefRecord CreateMimeRecord(String mimeType, byte[] payload)
        {
            byte[]     mimeBytes  = Encoding.UTF8.GetBytes(mimeType);
            NdefRecord mimeRecord = new NdefRecord(
                NdefRecord.TnfMimeMedia, mimeBytes, new byte[0], payload);

            return(mimeRecord);
        }
        private NdefRecord CreateTextRecord(string payload)
        {
            byte[]     textBytes = Encoding.UTF8.GetBytes(payload);
            NdefRecord record    = new NdefRecord(NdefRecord.TnfWellKnown,
                                                  NdefRecord.RtdText.ToArray(), new byte[0], textBytes);

            return(record);
        }
Example #4
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
                {
                }
            }
        }
Example #5
0
        private NdefRecord GenerateMimeRecord(Dictionary <string, string> values)
        {
            NdefRecord rec = new NdefRecord(NdefRecord.TypeNameFormatType.Mime, Encoding.ASCII.GetBytes(FLAGCARRIER_MIME_TYPE))
            {
                Payload = GenerateCompressedPayload(values)
            };

            return(rec);
        }
Example #6
0
        private string ParseUriRecord(NdefRecord ndefRecord)
        {
            byte[] payload = ndefRecord.GetPayload();

            // Get the Language Code
            int languageCodeLength = payload[0] & 0063;

            return(new String(System.Text.UTF8Encoding.ASCII.GetChars(payload), languageCodeLength + 1, payload.Length - languageCodeLength - 1));
        }
Example #7
0
        private void OnWriteTag(Intent intent, string content)
        {
            if (null != content)
            {
                var tag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;

                if (tag != null)
                {
                    Ndef ndef = Ndef.Get(tag);

                    if (ndef != null && ndef.IsWritable)
                    {
                        var payload     = Encoding.ASCII.GetBytes(content);
                        var mimeBytes   = Encoding.ASCII.GetBytes("text/plain");
                        var record      = new NdefRecord(NdefRecord.TnfWellKnown, mimeBytes, new byte[0], payload);
                        var ndefMessage = new NdefMessage(new[] { record });

                        ndef.Connect();
                        ndef.WriteNdefMessage(ndefMessage);
                        ndef.Close();
                    }
                    else
                    {
                        NdefFormatable ndefFormatable = NdefFormatable.Get(tag);

                        if (ndefFormatable != null)
                        {
                            try
                            {
                                var payload     = Encoding.ASCII.GetBytes(content);
                                var mimeBytes   = Encoding.ASCII.GetBytes("text/plain");
                                var record      = new NdefRecord(NdefRecord.TnfWellKnown, mimeBytes, new byte[0], payload);
                                var ndefMessage = new NdefMessage(new[] { record });

                                ndefFormatable.Connect();
                                ndefFormatable.Format(ndefMessage);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.Message);
                            }
                            finally
                            {
                                try
                                {
                                    ndefFormatable.Close();
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e.Message);
                                }
                            }
                        }
                    }
                }
            }
        }
Example #8
0
        static void Main(string[] args)
        {
            // Dynamically construct some more NDEF records
            var spRecord = new NdefSpRecord
            {
                Uri       = "http://andijakl.github.io/ndef-nfc/",
                NfcAction = NdefSpActRecord.NfcActionType.DoAction
            };

            spRecord.AddTitle(new NdefTextRecord {
                LanguageCode = "en", Text = "NFC Library"
            });
            spRecord.AddTitle(new NdefTextRecord {
                LanguageCode = "de", Text = "NFC Bibliothek"
            });
            NfcRecords.Add("SmartPoster", spRecord);

            // Ensure the path exists
            var tagsDirectory = Path.Combine(Environment.CurrentDirectory, FileDirectory);

            Directory.CreateDirectory(tagsDirectory);

            // Write tag contents to files
            foreach (var curNdefRecord in NfcRecords)
            {
                WriteTagFile(tagsDirectory, curNdefRecord.Key, curNdefRecord.Value);
            }

            // Multi-record file
            var record1 = new NdefUriRecord {
                Uri = "http://www.twitter.com"
            };
            var record2 = new NdefAndroidAppRecord {
                PackageName = "com.twitter.android"
            };
            var twoRecordsMsg = new NdefMessage {
                record1, record2
            };

            WriteTagFile(tagsDirectory, "TwoRecords", twoRecordsMsg);

            var record3 = new NdefRecord
            {
                TypeNameFormat = NdefRecord.TypeNameFormatType.ExternalRtd,
                Type           = Encoding.UTF8.GetBytes("custom.com:myapp")
            };
            var threeRecordsMsg = new NdefMessage {
                record1, record3, record2
            };

            WriteTagFile(tagsDirectory, "ThreeRecords", threeRecordsMsg);

            // Success message on output
            Console.WriteLine("Generated {0} tag files in {1}.", NfcRecords.Count, tagsDirectory);
            Debug.WriteLine("Generated {0} tag files in {1}.", NfcRecords.Count, tagsDirectory);
        }
Example #9
0
        public NdefIcalendarRecord(NdefRecord other)
            : base(other)
        {
            if (!IsRecordType(this))
            {
                throw new NdefException(NdefExceptionMessagesUwp.ExInvalidCopy);
            }

            ConvertIcalendarToAppointment(_payload);
        }
Example #10
0
 private void MessageReceived(ProximityDevice sender, ProximityMessage message)
 {
     Dispatcher.BeginInvoke(() => {
         var buf = DataReader.FromBuffer(message.Data);
         List <NdefRecord> recordList = new List <NdefRecord>();
         NdefRecordUtility.ReadNdefRecord(buf, recordList);
         NdefRecord firstRecord = recordList[0];
         byte[] payload         = firstRecord.Payload;
         GetBadgeData(payload);
     });
 }
Example #11
0
 internal bool IsPoster(NdefRecord record)
 {
     try
     {
         Parse(record);
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Example #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ndefRecord"></param>
        /// <returns></returns>
        private string ParseNdefRecord(NdefRecord ndefRecord)
        {
            byte[] payload = ndefRecord.GetPayload();

            // Get the Language Code
            int languageCodeLength = payload[0] & 0063;

            char[] payloadChars = UTF8Encoding.ASCII.GetChars(payload);
            var    payloadValue = new String(payloadChars, languageCodeLength + 1, payload.Length - languageCodeLength - 1);

            return(payloadValue);
        }
Example #13
0
        /// <summary>
        /// This method is called when an NFC tag is discovered by the application.
        /// </summary>
        /// <param name="intent"></param>
        protected override void OnNewIntent(Intent intent)
        {
            if (_inReadMode)
            {
                _inReadMode = false;
                var tag     = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;
                var rawMsgs = intent.GetParcelableArrayExtra(NfcAdapter.ExtraNdefMessages);

                if (tag == null)
                {
                    return;
                }

                if (NfcAdapter.ExtraTag.Contains("nfc"))
                {
                    HandleNFC(intent, true);
                }

                //added the below lines, can delete if they don't work.
                //NdefRecord payload = ((NdefMessage)rawMsgs[0]).GetRecords()[0];
                //byte[] currentPayloadBytes = payload.GetPayload();

                //String currentPayloadString = System.Text.Encoding.UTF8.GetString(currentPayloadBytes, 0, currentPayloadBytes.Length);
                var tagId = tag.GetId();
                _tagUid = ByteArrayToString(tagId);
                Log.Info(this.Application.PackageName, "Card UID is " + _tagUid);

                //DisplayMessage("Card UID is " + _tagUid + newLine + "Payload is " + "'" + currentPayloadString + "'");
            }
            else if (_inWriteMode)
            {
                _inWriteMode = false;
                var tag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;

                if (tag == null)
                {
                    return;
                }

                // These next few lines will create a payload (consisting of a string)
                // and a mimetype. NFC record are arrays of bytes.
                var payload     = Encoding.ASCII.GetBytes(_writeTextView.Text);
                var nfcRecord   = new NdefRecord(NdefRecord.TnfWellKnown, new byte[0], new byte[0], payload);
                var ndefMessage = new NdefMessage(new[] { nfcRecord });

                if (!TryAndWriteToTag(tag, ndefMessage))
                {
                    // Maybe the write couldn't happen because the tag wasn't formatted?
                    TryAndFormatTagWithMessage(tag, ndefMessage);
                }
            }
        }
        private void Write(object sender, EventArgs e)
        {
            lock (this)
            {
                var label = FindViewById <TextView>(Resource.Id.DataLabel);

                try
                {
                    if (nfcTag == null)
                    {
                        label.Text = "nfc tag is null";
                        return;
                    }

                    var data = DateTime.Now.ToString();

                    /*
                     * var ndefRecord = new NdefRecord(NdefRecord.TnfMimeMedia,
                     *  null,
                     *  new byte[] { },
                     *  Encoding.UTF8.GetBytes(data));
                     */

                    var ndefRecord = NdefRecord.CreateExternal(
                        "Smartisan.Nfc.Smartisan.Nfc", // your domain name
                        "myapp",                       // your type name
                        Encoding.UTF8.GetBytes(data)); // payload


                    var ndef = Ndef.Get(nfcTag);
                    ndef.Connect();
                    ndef.WriteNdefMessage(new NdefMessage(ndefRecord));
                    ndef.Close();

                    label.Text = $"Data:{newLine}{data}";
                }
                catch (Exception ex)
                {
                    label.Text += $"{newLine} Exception: {newLine} {ex.Message} {newLine} {ex.StackTrace}";
                }
                finally
                {
                    if (nfcTag != null)
                    {
                        if (Ndef.Get(nfcTag).IsConnected)
                        {
                            Ndef.Get(nfcTag).Close();
                        }
                    }
                }
            }
        }
Example #15
0
        public override byte[] GetKey(KeyProviderQueryContext ctx)
        {
            byte[] key = null;

            try
            {
                KeePassRFIDConfig rfidConfig = KeePassRFIDConfig.GetFromCurrentSession();
                ChipAction(new Action <Chip>(delegate(Chip chip)
                {
                    if (rfidConfig.KeyType == KeyType.NFC)
                    {
                        // Only tag type 4 supported for now.
                        NFCTagCardService nfcsvc = chip.getService(CardServiceType.CST_NFC_TAG) as NFCTagCardService;
                        if (nfcsvc == null)
                        {
                            throw new KeePassRFIDException(Properties.Resources.UnsupportedNFCTag);
                        }

                        NdefMessage msg = nfcsvc.readNDEF();
                        if (msg.getRecordCount() > 0)
                        {
                            NdefRecordCollection records = msg.getRecords();
                            if (records.Count > 0)
                            {
                                // Always use first record only
                                NdefRecord record = records[0];
                                // Don't care about payload type, use whole payload as the key
                                UCharCollection payload = record.getPayload();
                                if (payload.Count > 0)
                                {
                                    key = payload.ToArray();
                                }
                            }
                        }
                    }
                    else
                    {
                        UCharCollection csn = chip.getChipIdentifier();
                        if (csn.Count > 0)
                        {
                            key = csn.ToArray();
                        }
                    }
                }), rfidConfig);
            }
            catch (KeePassRFIDException ex)
            {
                MessageBox.Show(ex.Message, Properties.Resources.PluginError, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return(key);
        }
Example #16
0
        private bool IsOurRecord(NdefRecord rec)
        {
            if (rec.TypeNameFormat != NdefRecord.TypeNameFormatType.Mime)
            {
                return(false);
            }

            if (Encoding.ASCII.GetString(rec.Type) != FLAGCARRIER_MIME_TYPE)
            {
                return(false);
            }

            return(true);
        }
Example #17
0
        private UriRecord ParseAbsolute(NdefRecord record)
        {
            /*
             *  byte[] payload = record.getPayload();
             *  Uri uri = Uri.parse(new String(payload, Charset.forName("UTF-8")));
             *  return new UriRecord(uri);
             */

            var      payload = record.GetPayload();
            Encoding enc     = Encoding.GetEncoding("UTF-8");
            string   text    = enc.GetString(payload);

            return(new UriRecord(text));
        }
Example #18
0
        /// <summary>
        /// Transforms a <see cref="NFCNdefRecord"/> into an Android <see cref="NdefRecord"/>
        /// </summary>
        /// <param name="record">Object <see cref="NFCNdefRecord"/></param>
        /// <returns>Android <see cref="NdefRecord"/></returns>
        NdefRecord GetAndroidNdefRecord(NFCNdefRecord record)
        {
            if (record == null)
            {
                return(null);
            }

            NdefRecord ndefRecord = null;

            switch (record.TypeFormat)
            {
            case NFCNdefTypeFormat.WellKnown:
                var languageCode = record.LanguageCode;
                if (string.IsNullOrWhiteSpace(languageCode))
                {
                    languageCode = Configuration.DefaultLanguageCode;
                }
                if (languageCode.Length > 5)
                {
                    languageCode = languageCode.Substring(0, 5);                                                //max support 5 chars like en-US or de-AT
                }
                ndefRecord = NdefRecord.CreateTextRecord(languageCode, Encoding.UTF8.GetString(record.Payload));
                //no need to force it to 2 letters only
                //ndefRecord = NdefRecord.CreateTextRecord(languageCode.Substring(0, 2), Encoding.UTF8.GetString(record.Payload));
                break;

            case NFCNdefTypeFormat.Mime:
                ndefRecord = NdefRecord.CreateMime(record.MimeType, record.Payload);
                break;

            case NFCNdefTypeFormat.Uri:
                ndefRecord = NdefRecord.CreateUri(Encoding.UTF8.GetString(record.Payload));
                break;

            case NFCNdefTypeFormat.External:
                ndefRecord = NdefRecord.CreateExternal(record.ExternalDomain, record.ExternalType, record.Payload);
                break;

            case NFCNdefTypeFormat.Empty:
                ndefRecord = GetEmptyNdefRecord();
                break;

            case NFCNdefTypeFormat.Unknown:
            case NFCNdefTypeFormat.Unchanged:
            case NFCNdefTypeFormat.Reserved:
            default:
                break;
            }
            return(ndefRecord);
        }
Example #19
0
 public NdefRecord CreateMimeRecord(String mimeType, byte[] payload)
 {
     try
     {
         byte[]     mimeBytes  = Encoding.UTF8.GetBytes(mimeType);
         NdefRecord mimeRecord = new NdefRecord(
             NdefRecord.TnfMimeMedia, mimeBytes, new byte[0], payload);
         return(mimeRecord);
     }
     catch (Exception exc)
     {
         Helpers.LoggerHelper.LogException(exc);
         return(null);
     }
 }
        public static NfcTagRecord ToNfcTagRecord(NdefRecord ndefRecord)
        {
            if (ndefRecord is NfcUriRecord)
            {
                var nfcUriRecord = ndefRecord as NfcUriRecord;

                if (nfcUriRecord.UriPrefix == NfcUriRecord.Prefix.http ||
                    nfcUriRecord.UriPrefix == NfcUriRecord.Prefix.https ||
                    nfcUriRecord.UriPrefix == NfcUriRecord.Prefix.httpswww ||
                    nfcUriRecord.UriPrefix == NfcUriRecord.Prefix.httpwww)
                {
                    return NfcTagRecord.FromUrl(nfcUriRecord.ToString());
                }
            }
            return null;
        }
Example #21
0
        public UriRecord Parse(NdefRecord record)
        {
            var tnf = record.Tnf;

            if (tnf == NdefRecord.TnfWellKnown)
            {
                return(ParseWellKnown(record));
            }
            else if (tnf == NdefRecord.TnfAbsoluteUri)
            {
                return(ParseAbsolute(record));
            }
            else
            {
                throw new Exception("Unknown tnf");
            }
        }
Example #22
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 #23
0
        /// <summary>
        /// Transforms a <see cref="NFCNdefRecord"/> into an Android <see cref="NdefRecord"/>
        /// </summary>
        /// <param name="record">Object <see cref="NFCNdefRecord"/></param>
        /// <returns>Android <see cref="NdefRecord"/></returns>
        NdefRecord GetAndroidNdefRecord(NFCNdefRecord record)
        {
            if (record == null)
            {
                return(null);
            }

            NdefRecord ndefRecord = null;

            switch (record.TypeFormat)
            {
            case NFCNdefTypeFormat.WellKnown:
                var languageCode = record.LanguageCode;
                if (string.IsNullOrWhiteSpace(languageCode))
                {
                    languageCode = Configuration.DefaultLanguageCode;
                }
                ndefRecord = NdefRecord.CreateTextRecord(languageCode.Substring(0, 2), Encoding.UTF8.GetString(record.Payload));
                break;

            case NFCNdefTypeFormat.Mime:
                ndefRecord = NdefRecord.CreateMime(record.MimeType, record.Payload);
                break;

            case NFCNdefTypeFormat.Uri:
                ndefRecord = NdefRecord.CreateUri(Encoding.UTF8.GetString(record.Payload));
                break;

            case NFCNdefTypeFormat.External:
                ndefRecord = NdefRecord.CreateExternal(record.ExternalDomain, record.ExternalType, record.Payload);
                break;

            case NFCNdefTypeFormat.Empty:
                ndefRecord = GetEmptyNdefRecord();
                break;

            case NFCNdefTypeFormat.Unknown:
            case NFCNdefTypeFormat.Unchanged:
            case NFCNdefTypeFormat.Reserved:
            default:
                break;
            }
            return(ndefRecord);
        }
Example #24
0
        /*
         * Method name: CreateCardContent
         * Purpose: To be able to create the content for the card in the correct form of ShareMyDay:CardType:CardMessage
         */
        public static NdefMessage CreateCardContent()
        {
            switch (_typeSelected)
            {
            case "Leisure Activity":
                _typeSelected = "1";
                break;

            case "Class Activity":
                _typeSelected = "2";
                break;

            case "Class":
                _typeSelected = "3";
                break;

            case "Item":
                _typeSelected = "4";
                break;

            case "Teacher":
                _typeSelected = "5";
                break;

            case "Friend":
                _typeSelected = "6";
                break;

            case "Visitor":
                _typeSelected = "7";
                break;

            case "Admin":
                _typeSelected = "8";
                break;
            }
            var messageBytes = Encoding.UTF8.GetBytes(_typeSelected + ":" + _inputMessage);
            var mimeBytes    = Encoding.UTF8.GetBytes("ShareMyDayTest");

            var ndefRecord  = new NdefRecord(NdefRecord.TnfMimeMedia, mimeBytes, new byte[0], messageBytes);
            var ndefMessage = new NdefMessage(new[] { ndefRecord });

            return(ndefMessage);
        }
Example #25
0
        protected override void OnNewIntent(Intent intent) //When a new NFC tag is discovered
        {
            try
            {
                var tag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;

                IParcelable[] rawMsgs = intent.GetParcelableArrayExtra(NfcAdapter.ExtraNdefMessages);
                if (rawMsgs != null)
                {
                    NdefMessage  message = (NdefMessage)rawMsgs[0];
                    NdefRecord[] records = message.GetRecords();
                    if (records != null)
                    {
                        if (MainPage.currentPage == "Read From Node")       //If current page is read page
                        {
                            ReadNFC.DisplayValues(records[0].GetPayload()); //Encrypt nonce and create reply
                        }
                        else //If current page is write page
                        {
                            Ndef ndef = Ndef.Get(tag);
                            ndef.Connect();

                            byte[] bytes = WriteNFC.CreateRequest();

                            NdefRecord  newRecord  = new NdefRecord(NdefRecord.TnfUnknown, new byte[0], new byte[0], bytes);
                            NdefMessage newMessage = new NdefMessage(new NdefRecord[] { newRecord });
                            ndef.WriteNdefMessage(newMessage);
                            ndef.Close();
                            Toast.MakeText(ApplicationContext, "Write Succesful", ToastLength.Long).Show();
                        }
                    }
                }
                else
                {
                    Toast.MakeText(ApplicationContext, "The Tag did not contain a message.", ToastLength.Long).Show();
                }
            }
            catch
            {
                Toast.MakeText(ApplicationContext, "Something went wrong, please try again.", ToastLength.Long).Show();
            }
        }
Example #26
0
        private void PublishRecord(NdefRecord record, bool writeToTag)
        {
            if (_device == null)
            {
                return;
            }

            // Make sure we're not already publishing another message
            StopPublishingMessage(false);
            // Wrap the NDEF record into an NDEF message
            var message = new NdefMessage {
                record
            };
            // Convert the NDEF message to a byte array
            var msgArray = message.ToByteArray();

            // Publish the NDEF message to a tag or to another device, depending on the writeToTag parameter
            // Save the publication ID so that we can cancel publication later
            _publishingMessageId = _device.PublishBinaryMessage((writeToTag ? "NDEF:WriteTag" : "NDEF"), msgArray.AsBuffer(), MessageWrittenHandler);
        }
        /// <summary>
        ///  Below a code snippet for writing to a discovered tag. This method can be called when a new intent (tag discovered) has been fired.
        /// I'm using the Ndef class to the actual writing of the data to the tag.
        /// The first step is to create the different parts payload, record, and the Ndef message which will be written on the tag.
        /// Don't forget to call the Connect method before writing to the tag, otherwise, an exception will be thrown.
        /// </summary>
        /// <param name="intent">Current intent</param>
        /// <param name="content">Your Message</param>
        public void WriteToTag(Intent intent, string content)
        {
            if (!(intent.GetParcelableExtra(NfcAdapter.ExtraTag) is Tag tag))
            {
                return;
            }
            Ndef ndef = Ndef.Get(tag);

            if (ndef == null || !ndef.IsWritable)
            {
                return;
            }
            var payload     = Encoding.ASCII.GetBytes(content);
            var mimeBytes   = Encoding.ASCII.GetBytes("text/plain");
            var record      = new NdefRecord(NdefRecord.TnfWellKnown, mimeBytes, new byte[0], payload);
            var ndefMessage = new NdefMessage(new[] { record });

            ndef.Connect();
            ndef.WriteNdefMessage(ndefMessage);
            ndef.Close();
        }
Example #28
0
        //NFC EVENTS
        public NdefMessage CreateNdefMessage(NfcEvent evt)
        {
            if (myName == null)
            {
                Identity.LoadUsername(GetExternalFilesDir(null).ToString());
                myName = Identity.Username;
            }
            string datagram = myName + ",";

            foreach (string e in keys)
            {
                datagram += e + "#";
            }
            NdefRecord mimeRec = new NdefRecord(
                NdefRecord.TnfMimeMedia, Encoding.UTF8.GetBytes(Mime),
                new byte[0], Encoding.UTF8.GetBytes(datagram));

            NdefMessage msg = new NdefMessage(new NdefRecord[] { mimeRec });

            return(msg);
        }
Example #29
0
        public NFCMessage NdefFormatable_FormatTag(Tag tag)
        {
            if (!tag.GetTechList().Contains(Tech_NdefFormatable))
            {
                return(NFCMessage.NFC_UN_FORMATABLE_TAG);
            }
            NdefFormatable ndefFormatable = NdefFormatable.Get(tag);

            if (ndefFormatable == null)
            {
                return(NFCMessage.NFC_CANT_FORMAT);
            }
            ndefFormatable.Connect();
            NdefRecord  record  = NdefRecord.CreateMime("text/plain", Encoding.ASCII.GetBytes("New"));
            NdefMessage message = new NdefMessage(new NdefRecord[] { record });

            ndefFormatable.Format(message);
            ndefFormatable.Close();
            OnFormatting_NdefTag?.Invoke();
            return(NFCMessage.NFC_TAG_FORMATED);
        }
Example #30
0
        private void ReadNfcTag(Intent intent)
        {
            // Find first NDEF message
            var parcellableNdefMessages = intent.GetParcelableArrayExtra(NfcAdapter.ExtraNdefMessages);

            NdefMessage ndefMessage = null;

            if (parcellableNdefMessages != null && parcellableNdefMessages.Length > 0)
            {
                ndefMessage = parcellableNdefMessages[0] as NdefMessage;
                LogMessage("NDEF formatted NFC Tag discovered.");
            }
            else
            {
                LogMessage("Error: Tag is not NDEF formatted. This is unexpected.");
                return;
            }

            // Find first record in NDEF message
            NdefRecord ndefRecord  = null;
            var        ndefRecords = ndefMessage.GetRecords();

            if (ndefRecords != null && ndefRecords.Length > 0)
            {
                LogMessage("Using first NDEF record.");
                ndefRecord = ndefRecords[0];
            }
            else
            {
                LogMessage("Error: No records found in NDEF Message.");
                return;
            }

            // Log Uri to output
            LogMessage(String.Format("TAG Uri: {0}\n", ndefRecord.ToUri()));


            //var openUriIntent = new Intent(Android.Content.Intent.ActionView, ndefRecord.ToUri());
            //StartActivity(openUriIntent);
        }
        /**
         *
         * Método faz a gravação de uma nova mensagem no cartão.
         *
         * Essa nova mensagem será códificada usando o padrão UTF-8.
         *
         * @param ndef = Contém as informações do cartão que esta sendo lido.
         * @param mensagem = Mensagem que será gravada no cartão
         *
         * @throws IOException
         * @throws FormatException
         *
         * @return boolean =>  True = Mensagem Gravada / False = Erro ao gravar mensagem
         *
         * */
        public bool GavarMensagemCartao(Ndef ndef, string mensagem)
        {
            bool retorno = false;

            try
            {
                if (ndef != null)
                {
                    ndef.Connect();
                    NdefRecord mimeRecord = null;

                    Java.Lang.String str = new Java.Lang.String(mensagem);

                    mimeRecord = NdefRecord.CreateMime
                                     ("UTF-8", str.GetBytes(Charset.ForName("UTF-8")));

                    ndef.WriteNdefMessage(new NdefMessage(mimeRecord));
                    ndef.Close();
                    retorno = true;
                }
                else
                {
                    retorno = FormataCartao(ndef);
                }
            }
            catch (System.FormatException e)
            {
                throw new System.FormatException(e.Message);
            }
            catch (IOException e)
            {
                throw new IOException(e.Message);
            }
            finally
            {
                this.GravaTempoFinal();
            }

            return(retorno);
        }
Example #32
0
 /// <summary>
 /// Create a Smart Uri record based on the record passed
 /// through the argument.
 /// </summary>
 /// <remarks>
 /// Internalizes and parses the payload of the original record.
 /// The original record can be a Smart Poster or a URI record.
 /// </remarks>
 /// <param name="other">Record to copy into this SmartUri record.</param>
 public NdefSmartUriRecord(NdefRecord other) : base(other)
 {
     // Type compatibility checks done in base class
 }