This project is read-only.
 

How to record an NFC tag?

Let’s start a new Windows Phone solution in the Visual Studio and let’s add a new reference in it, the Ndef Library. In order to add this new reference to your Visual Studio solution, we may use the NuGet (Packages Manager) tool; for such, we must open the manager and search for NDEF in the online search field and then click on install.



As it’s added, let’s started our development. On the initial page code behind, let’s add the proximity API, and then create three variables for usage within the code; one variable instancing the Proximity Device that we are going to use for initializing NF and use the system standard and two long-type variables in order to store the Subscribe ID and the message Id.

using Windows.Networking.Proximity;
using NdefLibrary.Ndef;
using System.Text;
using System.Runtime.InteropServices.WindowsRuntime;


private ProximityDevice device;
private long subscribeMessageId = -1;
private long publishingMessageId;


We’ll initialize the subscribeMessageId variable with the value -1 to use it as validation in the NFCBegin method (which is shown below), when we’re reading a tag, the service can’t be available for the reading of other tags, then avoiding a double tap, or the reading of different values. Following the validation of the subscribeMessageId value validation in the method, the variable receives a new value and returns the variable to -1 at the end of the Message Client Received Handler method.

public void NFCBegin()
{
     if (subscribeMessageId == -1)
     {
           subscribeMessageId = _device.SubscribeForMessage("NDEF", 
	   MessageReceivedHandler);
     }
}


The handler will be responsible for discovering the type of message sent and, according to the treatment type, the specialized Type variable will receive the Ndef Record type sent, being this variable used as a parameter of the treatment validation. The validated types have been:
  • NdefMailtoRecord – Content for E-mail sending
  • NdefUriRecord – URL to be opened in the Browser
  • NdefSpRecord – Smart Poster Content
  • NdefLaunchAppRecord – Automatic initialization of an application
  • NdefTextRecord – Content in the text form

private void MessageReceivedHandler(ProximityDevice sender, ProximityMessage message)
        {
            var rawMsg = message.Data.ToArray();
            var ndefMessage = NdefMessage.FromByteArray(rawMsg);
            var tagContents = new StringBuilder();

            foreach (NdefRecord record in ndefMessage)
            {
                if (record.Id != null && record.Id.Length > 0)
                {
                    // Show the content of the Record ID
		   // Make your treatment with the value


                }
                if (record.Type != null && record.Type.Length > 0)
                {
                    // Show the content of the Record Type
		   // Make your treatment with the value

                }

                // Check the record type sent
                var specializedType = record.CheckSpecializedType(true);

                if (specializedType == typeof(NdefMailtoRecord))
                {
                    
                    var mailtoRecord = new NdefMailtoRecord(record);
                // Make your treatment for received information of email
                }
                else if (specializedType == typeof(NdefUriRecord))
                {

                    var uriRecord = new NdefUriRecord(record);
                    // Make your treatment for received information of Uri                }
                else if (specializedType == typeof(NdefSpRecord))
                {
                    
                    var spRecord = new NdefSpRecord(record);
                    // Make your treatment for received information of Smart Poster received
              
                }
                else if (specializedType == typeof (NdefLaunchAppRecord))
                {
                    
                    var launchAppRecord = new NdefLaunchAppRecord(record);
                    // Make your treatment for received information of App               
 		   } else if (specializedType == typeof (NdefTextRecord))
                {
                    
                    var launchAppRecord = new NdefTextRecord(record);
                    // Make your treatment for received information of Text               
 		   }

                else
                {
                    // Other invalid type in this example
                }

            subscribeMessageId 	= -1;
            }
}


Agora vamos adicionar a chamada do método NFCBegin no construtor e inicializar a variável de device com o valor padrão do sistema.

device = ProximityDevice.GetDefault();
NFCBegin();


Now, let’s add a call of the NFCBegin method in the builder and initialize the _device variable with the system standard value.

private void BtnLaunchApp (object sender, System.Windows.RoutedEventArgs e)
        {
            var record = new NdefLaunchAppRecord {Arguments = "Hello World"};
            record.AddPlatformAppId("WindowsPhone", "ID da App no WMAppManifest.xml");
            PublishRecord(record, true);
        }

private void BtnMailTo (object sender, System.Windows.RoutedEventArgs e)
        {
            var record = new NdefMailtoRecord
                             {
                                 Address = "email para qual quer enviar",
                                 Subject = "assunto do email",
                                 Body = "texto do email..."
                             };
            PublishRecord(record, true);
        }

private void BtnUri (object sender, System.Windows.RoutedEventArgs e)
        {
            var record = new NdefUriRecord { Uri = "http://www.seusite.com/" };
            PublishRecord(record, false);
        }

private void BtnText (object sender, System.Windows.RoutedEventArgs e)
        {
            var record = new NdefTextRecord
            {
                Text = content,
                LanguageCode = CultureInfo.CurrentCulture.TwoLetterISOLanguageName
            };

            PublishRecord(record, true);
        }

private void PublishRecord(NdefRecord record, bool writeToTag)
        {
            if (_device == null) return;
            StopPublishingMessage(false);

            var message = new NdefMessage { record };

            var msgArray = message.ToByteArray();
            publishingMessageId = _device.PublishBinaryMessage((writeToTag ? "NDEF:WriteTag" : "NDEF"), msgArray.AsBuffer(), MessageWrittenHandler);
        }

private void MessageWrittenHandler(ProximityDevice sender, long messageid)
        {
            StopPublishingMessage(false);
        }


Through these four methods, we’re covering the tag writing possibilities using the NDEF. The PublishRecord method plays the role of actually recording the information in the tag, it receives by parameter the message to be recorded and a Boolean type validating if it’s to be recorded. The BtnLaunchApp method records in the application a call to open a specific application sending an argument to be treated at the initialization of the application in the OnNavigatedTo method.

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            // Check if app was launched via LaunchApp tag
            if (NavigationContext.QueryString.ContainsKey("ms_nfp_launchargs"))
            {
                // Treat in the app what to do with the argument
            }
        }


In the BtnMailTo method, an email will be generated to the addressee with the subject and text recorded in the tag. In the BtnUri method, a URL will be recorded in order to be opened in the system standard application, usually a Browser. In the BtnText method, a string will be recorded, which must be treated at the receipt of the very application. The MessageWrittenHandler method verifies if there is any message being published at the time and stops the publication if it’s true.

We can realize that by means of a few code lines we can create an application for writing and reading tags in the Windows Phone.

Last edited Aug 6, 2014 at 10:40 PM by brmontei, version 4