Sunday, July 21, 2013

Windows Phone Tip: Using Schemes to Launch Settings Pages

Due to security reasons, your Windows Phone application is not allowed to modify some of the device’s settings directly. For example, you might want to programmatically turn on the airplane mode on the device. However, this is not allowed without the user’s explicit permission. The only way to turn on airplane mode is for the user to navigate to the Settings’s Airplane Mode page and turn it on manually.

In your application, instead of asking the user to navigate to the Settings page, you can directly bring them to the page, programmatically.

To launch the various Settings pages, you can use the Launcher class with the LaunchUriAsync() method. As you are launching the pages asynchronously, you need to wrap these calls in a async method, like this:

        private async void LaunchSettings(int mode)
        {
            switch (mode)
            {
                case 0: await Launcher.LaunchUriAsync(
                    new Uri("ms-settings-airplanemode:"));
                    break;
                case 1: await Launcher.LaunchUriAsync(
                    new Uri("ms-settings-bluetooth:"));
                    break;
                case 2: await Launcher.LaunchUriAsync(
                    new Uri("ms-settings-cellular:"));
                    break;
                case 3: await Launcher.LaunchUriAsync(
                    new Uri("ms-settings-wifi:"));
                    break;
                case 4: await Launcher.LaunchUriAsync(
                    new Uri("ms-settings-location:"));
                    break;
                case 5: await Launcher.LaunchUriAsync(
                    new Uri("ms-settings-emailandaccounts:"));
                    break;
                case 6: await Launcher.LaunchUriAsync(
                    new Uri("ms-settings-lock:"));
                    break;
            }
        }


The following figure shows the Airplane Mode settings page:

Friday, July 19, 2013

Xamarin.iOS Tip - Copy File in Bundle to Documents Folder

Very often, you need to attach resources to your application so that you can use them during runtime. For example, you might have an empty database created during development time that you want to use to store the locations coordinates collected when the user is using your application. In order to use that database, when the application is first run on the device, you need to copy it from the application bundle onto the application’s Documents folder.

The following method allows you to specify a file to copy from the application bundle onto the application’s Documents folder:

        private void CopyFileInBundleToDocumentsFolder(
        String filename)
        {
            //---path to Documents folder---
            var documentsFolderPath =
                Environment.GetFolderPath(
                    Environment.SpecialFolder.MyDocuments);

            //---destination path for file in the Documents
            // folder---
            var destinationPath =
                Path.Combine(documentsFolderPath, filename);

            //---path of source file---
            var sourcePath = 
                Path.Combine(NSBundle.MainBundle.BundlePath,
                filename);

            //---print for verfications---
            Console.WriteLine(destinationPath);
            Console.WriteLine(sourcePath);

            try {
                //---copy only if file does not exist---
                if (!File.Exists(destinationPath))
                {
                    File.Copy(sourcePath, destinationPath);
                }  else {
                    Console.WriteLine("File already exists");
                }
            }  catch (Exception e) {
                Console.WriteLine(e.Message);
            }
        }

You typically call this method when the application is first launched:

        public override bool FinishedLaunching (
        UIApplication app, NSDictionary options)
        {
            window = new UIWindow
                (UIScreen.MainScreen.Bounds);
           
            viewController = new
                BundledResourcesViewController ();
            window.RootViewController = viewController;
            window.MakeKeyAndVisible ();

            //---copy file in bundle to documents folder---
            CopyFileInBundleToDocumentsFolder("MyDB.sql");

            return true;

        }

Windows Phone Tip: Checking Network Availability

If you are writing networked applications, it is always important to be able to know if the device has network connectivity. In addition, it is also very useful to know if the device is connected to the WiFi, or the cellular data network. If the device is connected to the cellular data network, you could limit the amount of data transferred as this could cost impose additional cost on the user.  

All the code in this tip and tricks uses the following namespaces, so ensure that you import them into your page:

using Windows.Networking.Connectivity;
using System.Diagnostics;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using Microsoft.Phone.Net.NetworkInformation;
using Windows.System.Threading;
using System.Threading.Tasks;

To know if there is network connectivity on your device, use the GetIsNetworkAvailable() method from the NetworkInterface class:

    if (NetworkInterface.GetIsNetworkAvailable()){

    }

This method returns a boolean value indicating if there is any form of network connectivity on your device.

To know what kind of connectivity you have, you can access the NetworkInterfaceType property of the NetworkInterface class:

        private NetworkInterfaceType GetNetworkInterfaceType()
        {
            //---this is a blocking call---
            var interfaceType =
                NetworkInterface.NetworkInterfaceType;
            return interfaceType;
        }

However, do take note that the NetworkInterfaceType property is a blocking call – it typically takes about a couple of seconds to return you the network type. Hence, be sure not to call it directly. Instead, you should put it into a method and call it asynchronously using the async and await keywords:

        private async void CheckNetworkType()
        {
            //---call the GetNetworkInterfaceType() method
            // asynchronously---
            var interfaceType = await
                Task.Run(() =>
                    GetNetworkInterfaceType()
                );
        }

You can check the type of connectivity you have by comparing the interface type with the enumerations in the NetworkInterfaceType:

        private async void CheckNetworkType()
        {
            //---call the GetNetworkInterfaceType() method
            // asynchronously---
            var interfaceType = await
                Task.Run(() =>
                    GetNetworkInterfaceType()
                );

            if (interfaceType ==
            NetworkInterfaceType.Wireless80211)
            {
                Debug.WriteLine("Wireless");
                GetMyIPAddress();
                GetMyPublicIPAddress();
            }
            else if (interfaceType ==
            NetworkInterfaceType.MobileBroadbandGsm ||
            interfaceType ==
            NetworkInterfaceType.MobileBroadbandCdma)
            {
                Debug.WriteLine("Cellular network");
                GetMyIPAddress();               
            }
            else if (interfaceType ==
            NetworkInterfaceType.None)
            {
                Debug.WriteLine("None");
            }
        }

You can get your IP address by using the following method:

        public void GetMyIPAddress()
        {
            var hostNames = NetworkInformation.GetHostNames();
            foreach (var hostName in hostNames)
            {
                if (hostName.IPInformation != null)
                {
                    string ipAddress = hostName.DisplayName;
                    Debug.WriteLine("IP address: " +
                        ipAddress);
                }
            }
        }

If you are connected to a WiFi, it is often that your IP address is a local one – one that that the router assigns to you using DHCP. If you want to know the IP address that your service provider assigns to your router, you can use a JSON service located at  http://ip.jsontest.com/. This service will return you the IP address that is assigned to your router by your service provider.

To use this service, first define a class called Json_Result:

    [DataContract]
    public class Json_Result
    {
        [DataMember(Name = "ip")]
        public string IP { get; set; }
    }

You can call the JSON service using the WebClient class, like the following code snippet:

        private void GetMyPublicIPAddress()
        {
            //---find my public ip address---
            WebClient client = new WebClient();
            client.OpenReadCompleted +=
                client_OpenReadCompleted;
            client.OpenReadAsync(new
                Uri("http://ip.jsontest.com/"),
                UriKind.Absolute);
            //---returning result is
            //    {"ip":"xxx.xxx.xxx.xxx"}---
        }

        void client_OpenReadCompleted(object sender,
        OpenReadCompletedEventArgs e)
        {
            var serializer = new
                DataContractJsonSerializer(
                    typeof(Json_Result));
            Json_Result ipResult =
                (Json_Result)serializer.ReadObject(e.Result);           
            Debug.WriteLine("My public IP address: " +
                ipResult.IP);
        }

The above code snippet is also useful in helping you determine if you have actual Internet access. Having network connectivity does not mean you have Internet connectivity - hence if the above code is able to fetch your IP address, it means that you have Internet connectivity.

Finally, if you want to programmatically monitor for changes to network connectivity on your device, you can set an event handler for the NetworkAvailabilityChanged event:

//---monitor for changes in network availability---            DeviceNetworkInformation.NetworkAvailabilityChanged +=
    DeviceNetworkInformation_NetworkAvailabilityChanged;

void DeviceNetworkInformation_NetworkAvailabilityChanged(
object sender, NetworkNotificationEventArgs e)
{
    CheckNetworkType();
}

Full Code Listing

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using MyIPAddress.Resources;

using Windows.Networking.Connectivity;
using System.Diagnostics;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using Microsoft.Phone.Net.NetworkInformation;
using Windows.System.Threading;
using System.Threading.Tasks;

namespace MyIPAddress
{
    [DataContract]
    public class Json_Result
    {
        [DataMember(Name = "ip")]
        public string IP { get; set; }
    }

    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            //---monitor for changes in network
            // availability---                         DeviceNetworkInformation.NetworkAvailabilityChanged +=            DeviceNetworkInformation_NetworkAvailabilityChanged;

            if (NetworkInterface.GetIsNetworkAvailable())
            {
                CheckNetworkType();
            }
            else
            {
                Debug.WriteLine("No network available");
            }                  
        }

        private async void CheckNetworkType()
        {
            //---call the GetNetworkInterfaceType() method
            // asynchronously---
            var interfaceType = await
                Task.Run(() =>
                    GetNetworkInterfaceType()
                );

            if (interfaceType ==
            NetworkInterfaceType.Wireless80211)
            {
                Debug.WriteLine("Wireless");
                GetMyIPAddress();
                GetMyPublicIPAddress();
            }
            else if (interfaceType ==
            NetworkInterfaceType.MobileBroadbandGsm ||
            interfaceType ==
            NetworkInterfaceType.MobileBroadbandCdma)
            {
                Debug.WriteLine("Cellular network");
                GetMyIPAddress();               
            }
            else if (interfaceType ==
            NetworkInterfaceType.None)
            {
                Debug.WriteLine("None");
            }
        }

        void       
        DeviceNetworkInformation_NetworkAvailabilityChanged(
        object sender, NetworkNotificationEventArgs e)
        {
            CheckNetworkType();
        }

        private NetworkInterfaceType GetNetworkInterfaceType()
        {
            //---this is a blocking call---
            var interfaceType =
                NetworkInterface.NetworkInterfaceType;
            return interfaceType;
        }
       
        private void GetMyPublicIPAddress()
        {
            //---find my public ip address---
            WebClient client = new WebClient();
            client.OpenReadCompleted +=
                client_OpenReadCompleted;
            client.OpenReadAsync(new
                Uri("http://ip.jsontest.com/"),
                UriKind.Absolute);
            //---returning result is
            //    {"ip":"xxx.xxx.xxx.xxx"}---
        }

        public void GetMyIPAddress()
        {
            var hostNames = NetworkInformation.GetHostNames();
            foreach (var hostName in hostNames)
            {
                if (hostName.IPInformation != null)
                {
                    string ipAddress = hostName.DisplayName;
                    Debug.WriteLine("IP address: " +
                        ipAddress);
                }
            }
        }
       
        void client_OpenReadCompleted(object sender,
        OpenReadCompletedEventArgs e)
        {
            var serializer = new
                DataContractJsonSerializer(
                    typeof(Json_Result));
            Json_Result ipResult =
                (Json_Result)serializer.ReadObject(e.Result);           
            Debug.WriteLine("My public IP address: " +
                ipResult.IP);
        }
    }

}

Sunday, July 14, 2013

Windows Phone Tip: Getting the Device GUID

Sometime you may want to uniquely identify a Windows Phone, such as when you are implementing push notifications. The best way to identify a unique Windows Phone is through its device GUID.

The following code snippet shows how to obtain the GUID of a Windows Phone device:

using Microsoft.Phone.Info;

    public static byte[] DeviceId()
    {
        object uniqueId;
        if (DeviceExtendedProperties.TryGetValue(
        "DeviceUniqueId", out uniqueId))
        {
            return (byte[])uniqueId;
        }
        return null;
    }
    ...
    ...

    byte[] guid = DeviceId();           
    MessageBox.Show("Device GUID - " +

        Convert.ToBase64String(guid));

For the code above to work, you need to check the ID_CAP_IDENTITY_DEVICE setting in your WMAppManifest.xml file.

Friday, July 12, 2013

Windows Phone Tip: Updating the UI from an Asynchronous Thread

One of the most common tasks you need to perform in a Windows Phone application is updating the UI from a separate thread. For example, you may be download some content asynchronously using a WebClient class and when the operation is completed, you want to update the UI with the content that was downloaded. Updating the UI directly from an asynchronous thread is not allowed, as UI controls are not thread-safe.  

The easiest way to update the UI from an asynchronous thread is to use the Dispatcher class. To determine if you can update an UI directly, you can use the CheckAccess() method. If this method returns a true, it means you can directly update the UI. Else, you have to use the BeginInvoke() method of the Dispatcher class to update the UI in a thread-safe manner. The following code snippet makes this clear:

    if (Dispatcher.CheckAccess() == false)
    {
        //---you have to update the UI through the
        // BeginInvoke() method---
        Dispatcher.BeginInvoke(() =>
            txtStatus.Text = "Something happened..."
        );
    }
    else
    {
        //---you can update the UI directly---
        txtStatus.Text = "Something happened..."
    }

If you have more than one statement to perform in the BeginInvoke() method, you can group them into a method and call it like this:


        private void UpdateUI(String text)
        {
            txtStatus.Text = text;
            btnLogin.Content = text;
        }
        ...
        ...

            Dispatcher.BeginInvoke(() =>
                UpdateUI("Something happened...")

            );

Thursday, July 11, 2013

Windows Phone Tip: Check if App is Running on Emulator

There are times where you want to check if your app is running on the emulator. For example, Bluetooth functionality can only be tested on a real device. Hence, in your code you could check to see if the app is running on an emulator. If it is, then terminate the app.

The following code snippet checks for the current device type. If it is running on an emulator, terminate the app:

//---check if your app is running on the emulator---
if (Microsoft.Devices.Environment.DeviceType ==
    Microsoft.Devices.DeviceType.Emulator)
{
    MessageBox.Show("Running on emulator!");
    //---terminate the app---
    App.Current.Terminate();
}

Course Highlight - Windows Phone 8


While Microsoft may not be winning the smartphone platform war today, it is slowly making inroads into the various markets previously dominated by iPhone and Android. Today's biggest news - Russia's largest wireless carrier has just dropped support for iPhone in favor of Windows Phone.

Inline image 1
In the smartphone war, apps play a pivotal role in determining the success or failure of a platform. While the quantity and quality of the apps in the Windows Phone Store are still no match to its competitors, it is slowly but surely attracting top app makers into making apps for it. Just this week, Viber has updated its Windows Phone app that is specifically designed for Windows Phone devices

Good News for Windows Phone Developers (or wannabe)!
For a limited time, the annual subscription fee for a Windows Phone Dev Center account has been reduced to $19 USD (or the equivalent in your local currency). Taxes, VAT, and other fees are excluded from this offer. This offer is valid beginning 6/26/2013 12:00 AM PST and ending 8/27/2013 12:00 AM PST in countries where the Windows Phone Dev Center registration is available (see Regional info). See the official terms of this offer for more details.

In Singapore, the reduced fee is now S$30. Go and register now!

Confirmed Windows Phone 8 Programming Courses This Month
In July, we have two confirmed courses for Windows Phone 8 development - Foundation of Windows Phone 8 Programming, and Advanced Windows Phone 8 Programming. In Sep, we have a brand new course on Windows Phone 8 NFC Programming. So, brush the dust off your Windows laptop and start your engine! 

Inline image 1

In the Foundation course, you will learn the basics of writing Windows Phone app - User Interfaces, choosers and launchers, states of an application, location-based services, file storage, web services, databases, maps, and more. 

In the Advanced course, you will dive deeper into the more advanced areas of Windows Phone programming - background agents, Bluetooth and sockets programming, security, push notifications, and more.

Windows Phone Challenge - Lumia 920 and Lumia 925
Microsoft Singapore and Nokia Singapore are teaming up for the next Windows Phone Challenge! All you need to do is to implement one (or more) of the challenges posted here and you will be able to win some cool Nokia Lumia devices. The challenges are applications based very much on the local (Singapore) context. This is a great idea for student projects and is a good time to put your knowledge to the test.

Inline image 2

Tuesday, July 02, 2013

NEW COURSES FOR JUL TO SEP 2013


Inline image 1
NEW COURSES FOR JUL TO SEP 2013

Get Your Hands on the Raspberry Pi!

Inline image 2

New course on Raspberry Pi! We are launching a new course on Raspberry Pi on the 23 Sep 2013! In this course, you will learn how to get started with Raspberry Pi and how to get started with Python programming. No Raspberry Pi? No worries, we will be providing them and best of all, you get to keep it after the course!

The Upcoming Platform - Windows Phone 8

Inline image 3

While Windows Phone 8 faces an uphill battle against Android and iOS, it is slowly but surely coming up strongly. With Nokia rolling out new devices and injecting vibrancy into the platform, developers are now warming up to the platform. One key advantage of the platform is that there is a huge gap to fill in the area of apps. As the saying goes, the early bird catches the worm. 

In July, we have 2 confirmed course for Windows Phone 8 development - Foundation of Windows Phone 8 Programming, and Advanced Windows Phone 8 Programming. In Sep, we have a brand new course on Windows Phone 8 NFC Programming. So, brush the dust off your Windows laptop and start your engine! 

Develop iOS and Android Apps using C# and Xamarin!

Inline image 4

One of the challenges in developing mobile apps is the need to learn a new programming language. If you want to develop iOS apps, you need to learn Objective-C; if you want to develop Android apps, you need to learn Java. Why can't you use a language that you are already familiar, such as C#? 

Now you can!

Using the Xamarin Studio, you can now create compelling Android and iOS (iPhone and iPad) apps using C#. Best of all, you can share your application logic  between the two platforms. And when you are ready, you can easily port your application to Windows Phone 8 (using Visual Studio)! And did we mention that your app developed will be a native app and a first-class citizen on the platform?

In 14-16 Aug and 25-27 Sep, we have the 3-day course on using Xamarin to build iOS and Android apps. This course covers both iOS and Android development. As such you need to bring along your own Mac, as the testing needs to be done on the iPhone Simulator, which requires a Mac.

Xamarin for iOS
For those of you who wants to focus only on a single platform, we have a 2-day course on using Xamarin to build iOS apps on the 17-18 Aug. Note that this is a weekend course and you also need to bring along your own Mac. 

Xamarin for Android
If you want to focus on Android, there is another 2-day course on using Xamarin to build Android apps on the 24-25 Aug. This is also a weekend class and for this course you can bring along either a Mac or Windows laptop 

Industry Adoption of Xamarin

Still not convinced that Xamarin is industrial-strength? What about checking out some of the apps listed below:

* JustEnough Mobile - http://xamarin.com/apps#justenough

Here is the list of apps developed using Xamarin - http://xamarin.com/apps/all.

Develop for the Android Market!

Inline image 5

In the most recent number of market researches, it was shown that the Android platform is almost neck and neck with the iOS platform. With new Android devices released almost every week, consumers are never short of options when it comes to Android devices. And that means that developers have a burgeoning market to develop for. In this Android Specialist track, you have a wide range of courses to choose from, depending on your current skill set and your appetite for learning more. 

Start with the Foundation of Android Programming course on the 16-17 Sep 2013 to get a solid foundation. 

For those of you who are interested in emerging technologies, come join us in the Developing NFC (Near Field Communication) Android Apps course on the 23 Aug 2013 or 18 Sep 2013. This course will show you how to write apps that read and write to NFC tags. You will also learn how to transmit data between two Android devices using a new feature known as Android Beam. 

Then, when you are ready for more action, continue with the Advanced Android - Network Programming on the 19 Sep 2013, where you will learn more advanced topics like networking, push notifications, etc. If you want to build location based services (LBS), then continue with the Advanced Android - LBS Programming on the 20 Sep 2013, where you will learn how to build LBS apps using Google Maps. 

Develop for the iOS AppStore!

Inline image 6

Not to be outdone by the rapid onslaught of Android, Apple is not taking things lying down. 

The Foundation of iOS Programming course on the 3-4 Aug 2013 and 9-10 Sep 2013 covers all the fundamental topics in iOS programming. You will be given a crash course in Objective-C - the language for iOS development, as well as learn how to write compelling iPhone applications. Once you are geared up with the basics, continue with the iOS Storyboard Programming course on the 26 Aug 2013, where you will learn how to easily create UI flows for your iOS apps. 

The Advanced iOS - LBS Programming course on the 27 Aug 2013 shows you how to develop LBS apps using Apple Maps and Google Maps.

For those of you interested in networking, the Advanced iOS - Network Programming course on the 28 Aug 2013 and 11 Sep 2013covers topics such as push notifications, web services, Bluetooth programming, and more. 

Finally, the Programming iCloud course on the 30 Aug 2013 will show you how to synchronize your data to the cloud using the new iCloud feature announced in iOS 6. 

Course Schedule at a Glance

Please refer to http://www.learn2develop.net for the latest updates in the schedule. 

Courses
Jul 2013
Aug 2013
Sep 2013
Oct 2013
iOS/iPhone/iPad




S$997/pax
1-2 Jul 2013
(Mon-Tue)
3-4 Aug 2013
(Sat-Sun)
9-10 Sep 2013
(Mon-Tue)

S$997/pax
4-5 Jul 2013
(Thu-Fri)



S$599/pax

30 Aug 2013
(Fri)


S$599/pax

28 Aug 2013
(Wed)
11 Sep 2013
(Wed)

S$599/pax

27 Aug 2013
(Tue)







Android




S$997/pax


16-17 Sep 2013
(Mon-Tue)

S$599/pax


19 Sep 2013
(Thu)

S$599/pax


20 Sep 2013
(Fri)

S$599/pax

23 Aug 2013
(Fri)
18 Sep 2013
(Wed)






Xamarin




S$1,495/pax

14-16 Aug 2013
(Wed-Fri)
25-27 Sep 2013
(Wed-Fri)

S$997/pax

17-18 Aug 2013
(Sat-Sun)


S$997/pax

24-25 Aug 2013
(Sat-Sun)







Windows Phone




S$997/pax
23-24 Jul 2013
(Tue-Wed)
CONFIRMED



S$997/pax
25-26 Jul 2013
(Thu-Fri)
CONFIRMED



WNP301 - Advanced Windows Phone – Developing NFC Apps
S$599/pax


3 Sep 2013
(Tue)






Web Development




WEB102 – Web Development using HTML5, CSS, and JavaScript



12-13 Sep 2013
(Thu-Fri)

WEB103 – Learning PHP and MySQL


5-6 Sep 2013
(Thu-Fri)






Hardware




S$599/pax


23 Sep 2013
(Mon)