HackMIT This Weekend!

HackMIT is this weekend, September 16-17.

I’m happy to announce that I’ll be mentoring as one of the local Microsoft MVPs that were invited to help as part of the Microsoft sponsorship of the event. I look forward to building some incredible applications with some of the brightest students coming to Cambridge, and may the best faction win! Keep an eye out for me Sunday morning, and feel free to reach out if you’re attending.

 

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

 

 

Advertisements

Xamarin.Tip – Read All Contacts in Android

To follow the posts made for iOS, let’s talk about reading the device contacts in Xamarin.Android.

Since Xamarin hasn’t been working on the Xamarin.Mobile component for a while, and James Montemagno dropped support for his Contacts Plugin, if you want to access the contact APIs on each platform, you might just have to go at it yourself – or just copy this code!

Android

The first thing we need to do is create our shared model to represent a contact on the device. In this example, we’ll focus on just the name and phone number of a given contact:
PhoneContact.cs

public class PhoneContact
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PhoneNumber { get; set; }
 
    public string Name { get => $"{FirstName} {LastName}"; }
 
}

Now we need to create our service to enable the reading of the contacts on the device. We’ll call it the ContactService.

    public class ContactService_Android
    {
        public IEnumerable<PhoneContact> GetAllContacts()
        {
            var phoneContacts = new List<PhoneContact>();

            using (var phones = Android.App.Application.Context.ContentResolver.Query(ContactsContract.CommonDataKinds.Phone.ContentUri, null, null, null, null))
            {
                if (phones != null)
                {
                    while (phones.MoveToNext())
                    {
                        try
                        {
                            string name = phones.GetString(phones.GetColumnIndex(ContactsContract.Contacts.InterfaceConsts.DisplayName));
                            string phoneNumber = phones.GetString(phones.GetColumnIndex(ContactsContract.CommonDataKinds.Phone.Number));

                            string[] words = name.Split(' ');
                            var contact = new PhoneContact();
                            contact.FirstName = words[0];
                            if (words.Length > 1)
                                contact.LastName = words[1];
                            else
                                contact.LastName = ""; //no last name
                            contact.PhoneNumber = phoneNumber;
                            phoneContacts.Add(contact);
                        }
                        catch (Exception ex)
                        {
                            //something wrong with one contact, may be display name is completely empty, decide what to do
                        }
                    }
                    phones.Close(); 
                }
                // if we get here, we can't access the contacts. Consider throwing an exception to display to the user
            }

            return phoneContacts;
        }
    }

 
In this method, we get access to the Context‘s ContentResolver and query for all contacts’ phone numbers.

We can then iterate over each phone number and read their name and number which is added to the master list of PhoneContacts. This list is what ends up being returned, and we close the query context we opened in the using statement.

There is one more step we need to do in order to access the contacts on the device. In the AndroidManifest.xml we need to add the permission for READ_CONTACTS. This can be added in the XML directly or done in the UI from Visual Studio:
Screen Shot 2017-09-07 at 5.30.01 PM
 
Now that we have access to all the contacts on the device, we can render those in a list through either an Android ListView, RecyclerView, or if in Xamarin.Forms – a Xamarin.Forms.ListView.

Screenshot_1504821136

 Try building some other fun features into your ContactsService or selector!
– Filter the list via search
– Build a more user friendly selector without duplicating contacts
– Gather additional properties for contacts

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Tip – Read All Contacts in iOS 2.0

This is a second post to follow Xamarin.Tip – Read All Contacts in iOS to give a more efficient alternative to interacting with the CNContact API. Check out the change in the ContactService below! Using the EnumerateContacts ensures we get contacts from all groups including non standard groups like those brought from backups or iCloud integrated contacts. It is also a newer API call that has better performance.

Since Xamarin hasn’t been working on the Xamarin.Mobile component for a while, and James Montemagno dropped support for his Contacts Plugin, if you want to access the contact APIs on each platform, you might just have to go at it yourself – or just copy this code!

iOS

Today we’ll look at getting all of the contacts in iOS and mapping them to a local shared model that any platform can ingest.

So let’s first define a simple model for our contact. This can have more models that are shared, but we will focus on the phone number and name for the sake of demonstrating.

PhoneContact.cs


    public class PhoneContact
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string PhoneNumber { get; set; }

        public string Name { get => $"{FirstName} {LastName}"; }

    }

Now let’s create a service in our iOS app project that uses the CNContact API. This will be responsible for getting all of the devices contacts (whether they have come from a back up, added, or are synced through iCloud).

The breakdown of this code can be found below.

ContactService.cs

    public class ContactService
    {
       public IEnumerable<PhoneContact> GetAllContacts()
        {
            var keysTOFetch = new[] { CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.PhoneNumbers };
            NSError error;
            //var containerId = new CNContactStore().DefaultContainerIdentifier;
            // using the container id of null to get all containers
            var contactList = new List<CNContact>();

            using (var store = new CNContactStore())
            {
                var request = new CNContactFetchRequest(keysTOFetch);
                store.EnumerateContacts(request, out error, new CNContactStoreListContactsHandler((CNContact contact, ref bool stop) => contactList.Add(contact)));
                
            }
            var contacts = new List<PhoneContact>();

            foreach (var item in contactList)
            {
                var numbers = item.PhoneNumbers;
                if (numbers != null)
                {
                    foreach (var item2 in numbers)
                    {
                        contacts.Add(new PhoneContact
                        {
                            FirstName = item.GivenName,
                            LastName = item.FamilyName,
                            PhoneNumber = item2.Value.StringValue

                        });
                    }
                }
            }
            return contacts;
        }
    
    }

Let’s breakdown what the code is doing here:

  1. Identify the properties of the contacts you want to grab – see keysToFetch
  2. Instantiate the CNContactStore and get all of the collections which will contain all of the contacts.
  3. Fetch all of the contacts from each container and add them to the master list.
  4. Loop over all of the contact data and add a new PhoneContact
    for each of the phone numbers they have. This could be done with giving a contact an IEnumerable PhoneNumbers rather than just one phone number, but in order to separate each phone number, that’s how we will do it.
  5. Return the formatted list of contacts/phone numbers

We can list this out in a UITableView, or in the case of the screenshot below, in a Xamarin.Forms ListView.

The last thing we need to do is make sure we have the permission to access the user’s contacts! We can do this by updating the info.plist with a Privacy - Contacts Usage Description property.

Screen Shot 2017-08-22 at 10.34.43 AM

Try building some other fun features into your ContactsService or selector!
– Filter the list via search
– Build a more user friendly selector without duplicating contacts
– Gather additional properties for contacts

Simulator Screen Shot Aug 21, 2017, 11.20.32 AM.png

Next we’ll look at building this same type of ContactService for Android in order to be able to gather all of the contacts on the device and follow up with using both of these services in Xamarin.Forms to create a contact picker control!

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Meetup – “Fluxing” Up Your Apps With Alex Dunn

Join us at the Microsoft NERD Center in Cambridge for the September Boston Mobile C# User-group on September 20th!

I’ll personally be speaking about implementing the Flux design pattern in your Xamarin and other .NET applications.

https://www.meetup.com/bostonmobiledev/events/242742363/

Meeting Details

Flux is the design pattern created by Facebook in your .NET apps to build robust and manageable data-driven interfaces. Learn what Flux is, how it differs from other patterns such as MVVM and MVC, and follow along and build your first app with Flux.

About the Presenter

Alex Dunn is a software consultant and architect with a passion for mobile application development and edge technology such as machine learning, AI, IoT, and modern web. He’s a Xamarin MVP and a Microsoft MVP for .NET, and can be found giving Guest Lectures at Xamarin University or organizing Boston’s Mobile C# User-group. Follow Alex and learn how to build beautiful and robust applications.

Twitter: @Suave_Pirate
GitHub: @SuavePirate
Blog: https://alexdunn.org
Flux Resources:

Source code for demo: https://github.com/suavepirate/xamarin.flux
Xamarin University Lecture:
https://university.xamarin.com/guestlectures/architecting-your-app-with-xamarin-facebook-flux
Gone Mobile Podcast:
http://gonemobile.io/blog/e0044.fluxing.up.your.xamarin.apps.with.alex.dunn/

 

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Tip – Read All Contacts in iOS

Since Xamarin hasn’t been working on the Xamarin.Mobile component for a while, and James Montemagno dropped support for his Contacts Plugin, if you want to access the contact APIs on each platform, you might just have to go at it yourself – or just copy this code!

iOS

Today we’ll look at getting all of the contacts in iOS and mapping them to a local shared model that any platform can ingest.

So let’s first define a simple model for our contact. This can have more models that are shared, but we will focus on the phone number and name for the sake of demonstrating.

PhoneContact.cs


    public class PhoneContact
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string PhoneNumber { get; set; }

        public string Name { get => $"{FirstName} {LastName}"; }

    }

Now let’s create a service in our iOS app project that uses the CNContact API. This will be responsible for getting all of the devices contacts (whether they have come from a back up, added, or are synced through iCloud).

The breakdown of this code can be found below.

ContactService.cs

    public class ContactService
    {
        public IEnumerable<PhoneContact> GetAllContacts()
        {
            var keysToFetch = new[] { CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.PhoneNumbers };
            NSError error;
            //var containerId = new CNContactStore().DefaultContainerIdentifier;
            // using the container id of null to get all containers.
            // If you want to get contacts for only a single container type, you can specify that here
            var contactList = new List<CNContact>();

            using (var store = new CNContactStore())
            {
                var allContainers = store.GetContainers(null, out error);
                foreach (var container in allContainers)
                {
                    try
                    {
                        using (var predicate = CNContact.GetPredicateForContactsInContainer(container.Identifier))
                        {
                            var containerResults = store.GetUnifiedContacts(predicate, keysToFetch, out error);
                            contactList.AddRange(containerResults);
                        }
                    }
                    catch
                    {
                        // ignore missed contacts from errors
                    }
                }
            }
            var contacts = new List<PhoneContact>();

            foreach (var item in contactList)
            {
                var numbers = item.PhoneNumbers;
                if (numbers != null)
                {
                    foreach (var item2 in numbers)
                    {
                        contacts.Add(new PhoneContact
                        {
                            FirstName = item.GivenName,
                            LastName = item.FamilyName,
                            PhoneNumber = item2.Value.StringValue

                        });
                    }
                }
            }
            return contacts;
        }
    }

Let’s breakdown what the code is doing here:

  1. Identify the properties of the contacts you want to grab – see keysToFetch
  2. Instantiate the CNContactStore and get all of the collections which will contain all of the contacts.
  3. Fetch all of the contacts from each container and add them to the master list.
  4. Loop over all of the contact data and add a new PhoneContact
    for each of the phone numbers they have. This could be done with giving a contact an IEnumerable PhoneNumbers rather than just one phone number, but in order to separate each phone number, that’s how we will do it.
  5. Return the formatted list of contacts/phone numbers

We can list this out in a UITableView, or in the case of the screenshot below, in a Xamarin.Forms ListView.

The last thing we need to do is make sure we have the permission to access the user’s contacts! We can do this by updating the info.plist with a Privacy - Contacts Usage Description property.

Screen Shot 2017-08-22 at 10.34.43 AM

Try building some other fun features into your ContactsService or selector!
– Filter the list via search
– Build a more user friendly selector without duplicating contacts
– Gather additional properties for contacts

Simulator Screen Shot Aug 21, 2017, 11.20.32 AM.png

Next we’ll look at building this same type of ContactService for Android in order to be able to gather all of the contacts on the device and follow up with using both of these services in Xamarin.Forms to create a contact picker control!

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Meetup – Boston Meetup Today: Xamarin on Azure and Cognitive Services

Join us at Microsoft’s NERD Center to learn about using Azure Cognitive Services in your Xamarin apps! Meet with some of the local Xamarin MVPs and employees while also enjoying some food.

https://www.meetup.com/bostonmobiledev/events/242566795/

Xamarin on Azure and Cognitive Services

Mobile development and cloud technologies are very popular right now. If you are a C# developer and already created your first application with Xamarin, you might be interested in learning some more details about Xamarin and Xamarin Forms. You might also want to use all benefits of Azure in your application or jump right into advanced topics and select one (or a couple) Cognitive Services for your application to integrate with. You will be able to get a flavor of all those tools from this talk. Also final demo will add some visual understanding of the topic.

About the speaker

Veronika Kolesnikova is a web developer at UMass Medical School.

Passionate about backend web development, mainly with Microsoft technologies like C#, .NET, SQL, Azure. Loves to learn new development tools and languages and share the knowledge with the community. Recently started working with Xamarin and cannot wait to provide her insights.
Last year Veronika graduated with MS degree in Information Technology.
In her free time, she likes dancing, traveling and practicing aerial yoga.

 

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.University – Guest Lecture Available for Free!

Xamarin University has now published my second guest lecture on WebRTC and building cross-platform voice/video conferencing apps for free! Check it out here:

 

 

And as always, find the source code on my GitHub here: https://github.com/SuavePirate/Xamarin.WebRTC

 
If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.