Xamarin, no show images in the device but only in the simulator

In my project I have some images to display. The funny thing is I can see images in the simulator but not in a real device.

Simulator

Simulator-Screen Shot

iPhone (real device)

iPhone-Screenshot

Solution

iPhone is case-sensitive and the name of your images must be specified correctly. iOS Simulator probably is not case-sensitive and then it displays images with every name.

Xamarin Forms and FingerPrint (iOS and Android only)

In this post I explain how to use Finger Print in your app. This app is working only in iOS or Android.

Add NuGet

In your solution, you have to add a package called Plugin.Fingerprint.

XamarinForms Fingerprint Nuget

Only for Android, in your Droid project add another package called Plugin.CurrentActivity. Also, you have to add a permission for fingerprint (and one specific for Samsung).

<uses-permission android:name="android.permission.USE_FINGERPRINT" />
<uses-permission 
       android:name="com.samsung.android.providers.context.permission.WRITE_USE_APP_FEATURE_SURVEY" />

Implementation

Now we implement in our PCL project the request for fingerprint. First of all we have to check if a device supports fingerprints. If yes, we show the typical dialog.

XamarinForms Finferprint Dialog

Now I added a button in the XAML and its name is buttonFingerPrint. For it in the code behind, I added a Clicked event. Then In the new function, I'm checking is the device supports fingerprint.

var result = await CrossFingerprint.Current.IsAvailableAsync(true);

The function IsAvailableAsync as true as parameter but it is useful only for iOS to have a code in return. If the device supports fingerprint, I'll show a dialog request with this code:

if (result) {
    var auth = await CrossFingerprint.Current
               .AuthenticateAsync("Authenticate access to fingerprint");
    if (auth.Authenticated) {
        await DisplayAlert("Whoooowhooo!", "Authentication is done!", "Ok");
    }
    else {
        await DisplayAlert("Something wrong", 
                           "There is a problem with your finger", "Ok");
    }
}
else {
    await DisplayAlert("Finger print not available", 
                       "You can't use your finger for using this app", "Ok");
}

Testing on an emulator

iOS

If you test your project in an iOS device, be careful to allow to use Touch ID from Hardware menu with Toggle Enrolled State. When you want to test your virtual finger, select Matching Touch.

XamarinForms Fingerprint iOS Emulator

Android

Let's go to the Android emulator. You need to set up fingerprint under Settings. From your Terminal call (5554 is the default port of an Android emulator but it can be different in your computer)

telnet 127.0.0.1 5554

Then you have to copy an auth token from an hidden file called .emulator_console_auth_token in your profile. In the terminal execute

auth <yourcode>

Now open Settings > Security > Fingerprint and follow the instruction. When you have to recognise your finder, come back to the terminal and type

finger touch 1

Then you can continue with the wizard.

Now you can execute your app. When your app ask your fingerprint, come back to the Terminal and type again

finger touch 1

Android is always easy to use! You find my solution on GitHub.

Happy coding!

Xamarin, Android and starting a service at device boot

In my previous post called Xamarin: how to Start an Application at Device Boot in Android, I explained how you can change your Android Xamarin's project to launch your app at the device boot.

It is a good start but my problem was a bit more complex. I want to create a background service to track the geolocation of a device. I googled a lot to find a solution without a great success. Then I started to implement my code with some tests. Finally, I found a good way and I'm sharing with you it.

Create a Broadcast Receiver

What is a Broadcast Receiver

A broadcast receiver is a component that responds to system-wide broadcast announcements. Many broadcasts originate from the system—for example, a broadcast announcing that the screen has turned off, the battery is low, or a picture was captured. Applications can also initiate broadcasts—for example, to let other applications know that some data has been downloaded to the device and is available for them to use. Although broadcast receivers don't display a user interface, they may create a status bar notification to alert the user when a broadcast event occurs. More commonly, though, a broadcast receiver is just a "gateway" to other components and is intended to do a very minimal amount of work.

How to implement a Broadcast Receiver

I show you now two implementations of it:

  • BootReceiver: this receiver is responsible to do something when a device starts. For that, we have to allow the app to read this event. In your AndroidManifest.xml you must add a permission called RECEIVE_BOOT_COMPLETED.
  • AirplaneModeReceiver: this receiver filters only the broadcast for ActionAirplaneModeChanged.

I start to show you the second one because it is more simple.

	[BroadcastReceiver]
    [IntentFilter(new[] { Android.Content.Intent.ActionAirplaneModeChanged })]
	public class AirplaneModeReceiver : BroadcastReceiver
	{
		private static readonly string TAG = typeof(AirplaneModeReceiver).FullName;

		public override void OnReceive(Context context, Intent intent)
		{
			Log.WriteLine(LogPriority.Debug, TAG, "AirplaneModeReceiver OnReceive Mode " + 
                          isAirplaneModeOn(context));
		}

		private static bool isAirplaneModeOn(Context context)
		{
			var airplane = Android.Provider.Settings.Global.GetInt(context.ContentResolver, 
                           Android.Provider.Settings.Global.AirplaneModeOn);
			return airplane != 0;
		}
	}

Although you can find a lot of posts where people said that you have to declare your broadcast in the AndroidManifest, I discover if I add the broadcast in the AndroidManifest, the broadcast won't work.

This is the first broadcast. Basically when a user taps on AirPlaneMode, this broadcast receives the status with isAirplaneModeOn function and writes this change in the logs.

BootReceiver is more interesting. When a device is booting, this broadcast starts a service to track the position. Also, in my code you find TimeService: I use this service to check if the service is starting properly and the notification is working and updating.

    [BroadcastReceiver]
    [IntentFilter(new[] { Android.Content.Intent.ActionBootCompleted })]
    public class BootReceiver : BroadcastReceiver
    {
        private static readonly string TAG = typeof(BootReceiver).FullName;

        public override void OnReceive(Context context, Intent intent)
        {
            Log.WriteLine(LogPriority.Debug, TAG, "BootReceiver OnReceive");

            Intent i = new Intent(context, typeof(GPSService));
            i.AddFlags(ActivityFlags.NewTask);
            context.StartService(i);
            Log.WriteLine(LogPriority.Debug, TAG, 
                          "BootReceiver OnReceive LocationService started");

			i = new Intent(context, typeof(TimerService));
			i.AddFlags(ActivityFlags.NewTask);
			context.StartService(i);
			Log.WriteLine(LogPriority.Debug, TAG, 
                          "BootReceiver OnReceive TimerService started");
		}
    }

The interesting part of this code is when I start a service. Basically, I define a new Intent with the type of service I want to call, then I start the service with the context.

Although you find a lot of posts on line, the right way to define a service in your AndroidManifest is the following:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="pro.wordbank.app.locationtest">
	<uses-sdk android:minSdkVersion="15" />
	<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
	<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
	<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
	<uses-permission android:name="android.permission.INTERNET" />
	<application android:label="LocationTest">
		<service android:name=".TimerService" />
        <service android:name=".LocationService" />
	</application>
</manifest>

I have publish a complete solution of that on GitHub. Happy coding!

Xamarin: how to Start an Application at Device Bootup in Android

This tutorial will explain to stat an application while the Android device boot-up. For this, we need to  listen to the BOOT_COMPLETED action and react to it.

BOOT_COMPLETED is a Broadcast Action that is broadcast once, after the system has finished booting. You can listen to this action by creating a BroadcastReceiver that then starts your launch Activity when it receives an intent with the BOOT_COMPLETED action.

Add this permission to your manifest

In your Android.Manifest you must add thi permission:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

 

BackgroundTest-AndroidManifest

Then open this file and add the following rows under Application:

    <receiver android:name=".BootReceiver" android:enabled="true" 
              android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
      <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <category android:name="android.intent.category.DEFAULT" />
      </intent-filter>
    </receiver>

In this example, we will create a new BroadcastReceiver called BootReceiver.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

namespace BackgroundTest.Droid.BackgroundServices
{
    public class BootReceiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            Intent i = new Intent(context, typeof(MainActivity));
            i.AddFlags(ActivityFlags.NewTask);
            context.StartActivity(i);
        }
    }
}

Install the application, and then restart the device. You can see the application will start after the device restarts. An implementation of background services starting with Activity, it explains here.

Source code on GitHub.

Happy coding!

Eat Cookies!

What are Cookies?

Cookies are data, stored in small text files, on your computer.

When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user.

Cookies were invented to solve the problem "how to remember information about the user":

  • When a user visits a web page, his name can be stored in a cookie.
  • Next time the user visits the page, the cookie "remembers" his name.

Cookies are saved in name-value pairs like:

username = John Doe

When a browser requests a web page from a server, cookies belonging to the page is added to the request. This way the server gets the necessary data to "remember" information about users.

Function

function deleteCookie(cname) {
    setCookie(name, '', 1);
    document.cookie = name + '=; Expires=Thu, 01 Jan 1970 " + 
                      "00:00:01 GMT; path=/;';
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) === 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires + 
                      "; path=/;";
}

Happy coding!

Bill Gates made these 15 predictions in 1999 — and it's scary how accurate he was

Bill-Gates

After reading ’Business @ the Speed of Thought’, my respect for Bill Gates has increased exponentially. That isn’t to say that I wasn’t a fan of his before. I’ve always been impressed by the strategies that Microsoft carried out in its early days, but that doesn’t come close to how impressed I am now. In this book, published in 1999, Gates outlined how information systems, the Internet, and technology in general would change the way that businesses function. Along the way, he made some incredibly accurate predictions, most of which have since become huge industries: smart phones, smart homes, social networks, and an array of other uses for the Internet-a few of which have yet to be developed.

Gates presents a few key elements for a good information system. While we have to keep in mind that the book was written in the late 90’s, many of these questions are still hardly answered by today’s technology, and present opportunities for new businesses.

Predictions

  1. Automated price comparison services will be developed, allowing people to see prices across multiple websites, making it effortless to find the cheapest product for all industries.
  2. People will carry around small devices that allow them to constantly stay in touch and do electronic business from wherever they are. They will be able to check the news, see flights they have booked, get information from financial markets, and do just about anything else on these devices.
  3. People will pay their bills, take care of their finances, and communicate with their doctors over the Internet.
  4. “Personal companions” will be developed. They will connect and sync all your devices in a smart way, whether they are at home or in the office, and allow them to exchange data. The device will check your email or notifications, and present the information that you need. When you go to the store, you can tell it what recipes you want to prepare, and it will generate a list of ingredients that you need to pick up. It will inform all the devices that you use of your purchases and schedule, allowing them to automatically adjust to what you’re doing.
  5. Constant video feeds of your house will become common, which inform you when somebody visits while you are not home.
  6. Private websites for your friends and family will be common, allowing you to chat and plan for events.
  7. Software that knows when you’ve booked a trip and uses that information to suggest activities at the local destination. It suggests activities, discounts, offers, and cheaper prices for all the things that you want to take part in.
  8. While watching a sports competition on television, services will allow you to discuss what is going on live, and enter contest where you vote on who you think will win.
  9. Devices will have smart advertising. They will know your purchasing trends, and will display advertisements that are tailored toward your preferences.
  10. Television broadcast will include links to relevant websites and content that complement what you are watching.
  11. Residents of cities and countries will be able to have Internet-based discussions concerning issues that affect them, such as local politics, city planning or safety.
  12. Online communities will not be influenced by your location, but rather, your interest.
  13. Project managers looking to put a team together will be able to go online, describe the project, and receive recommendations for available people who would fit their requirements.
  14. Similarly, people looking for work will be able to find employment opportunities online by declaring their interest, needs, and specialized skills.
  15. Companies will be able to bid on jobs, whether they are looking for a construction project, a movie production, or an advertising campaign. This will be efficient for both big companies that want to outsource work that they don’t usually face, businesses looking for new clients, and corporations that don’t have a go-to provider for the said service.

The original post is here.

C# and multicultural IsDate() and ToDate()

C# does not provide IsDate() function. Sometimes in your developer environment region settings are different from the live environment. In my case, I don’t know what region settings there are in my company servers.

For this reason, I created a function to check is a string is a date in a culture and to convert a string to a date.

/// 
/// Determines whether the specified text is date.
/// 
/// The text.
/// 
/// true if the specified text is date; 
/// otherwise, false.
/// 
public static bool IsDate(this string text)
{
    if (!string.IsNullOrEmpty(text))
    {
        DateTime result = DateTime.MinValue;
        foreach (CultureInfo cultureInfo in 
                 CultureInfo.GetCultures(CultureTypes.AllCultures))
        {
            try
            {
                if (DateTime.TryParse(text, cultureInfo, 
                                      DateTimeStyles.None, 
                                      out result))
                    return true;
            }
            catch (Exception ex) { }
        }
    }

    return false;
}

/// 
/// To the date.
/// 
/// The text.
/// System.Nullable<DateTime>.
public static DateTime? ToDate(this string text)
{
    if (!string.IsNullOrEmpty(text))
    {
        DateTime result = DateTime.MinValue;
        foreach (CultureInfo cultureInfo in 
                 CultureInfo.GetCultures(CultureTypes.AllCultures))
        {
            try
            {
                if (DateTime.TryParse(text, cultureInfo, 
                                      DateTimeStyles.None, 
                                      out result))
                    return result;
            }
            catch (Exception ex) { }
        }
    }

    return null;
}

Happy coding!

Show/Hide Hidden Files on macOS

Show/Hide Hidden Files the Long Way

The long way to show hidden Mac OS X files is as follows:

  • Open Terminal found in Finder > Applications > Utilities
  • In Terminal, paste the following:

    defaults write com.apple.finder AppleShowAllFiles YES
    
  • Press return
  • Restart your Mac

This will show all hidden files. To hide them again, follow the same steps but replace the Terminal command with:

defaults write com.apple.finder AppleShowAllFiles NO

It’s not the longest set of instructions or the biggest command to commit to memory but if you’re doing this a lot, it’s worth spending a few minutes now to save yourself a lot more time in the future.

Device name in Xamarin

Using Device Information Plugin for Xamarin and Windows, you have access to same information for a device:

  • GenerateAppId: used to generate a unique Id for your app.
  • Id: this is the device specific Id
  • Device Model: get the model of the device
  • Version: get the version of the Operating System

If you want the device name, it's not in this list. Then for that we can create our functions.

IDevice interface

First of all we have to create an interface, I call it IDevice.

using System;
namespace myApp.Interfaces
{
    public interface IDevice
    {
        string DeviceName();
    }
}

The GetDeviceName() method returns the name of the device. You will need to implement this method in iOS and Android.

iOS dependency

Then in iOS project, I add a new dependence like:

using System;
using myApp.iOS;
using myApp.Interfaces;

[assembly: Xamarin.Forms.Dependency(typeof(Device_iOS))]
namespace myApp.iOS
{
    public class Device_iOS: IDevice
    {
        public string GetDeviceName() {
            return UIKit.UIDevice.CurrentDevice.Name;
        }
    }
}

To get the name of the device in iOS, you use the UIDevice class in the UIKit Framework.

Android

For Android, I add the following code to the project:

using System;
using Android.Bluetooth;
using myApp.Droid;
using myApp.Interfaces;
using Xamarin.Forms;

[assembly: Dependency(typeof(Device_Droid))]
namespace myApp.Droid.Dependencies
{
    public class Device_Droid : IDevice
    {
        /// 
        /// Get device the name.
        /// 
        /// The name.
        public string DeviceName()
        {
			BluetoothAdapter myDevice = 
                BluetoothAdapter.DefaultAdapter;
			return myDevice.Name;
        }
    }
}

Getting the device name is a little tricky in Android, which has no public API for that purpose. You can get it from the BluetoothAdapter class; however, to use the BluetoothAdapter class, you need to add the Bluetooth permission in the Android project.

Android Bluetooth

Call dependency

After that I have to add in my main project a call to the dependency.

var platform = DependencyService.Get<IDevice> ();
string name = platform.GetDeviceName();

Happy coding!

Microsoft says iOS and Android support doesn’t mean Windows Phone is dead

Is-Windows-Phone-dead

In an interview with Business Insider, Microsoft’s Joe Belfiore spoke briefly about Microsoft’s recent announcements made at Build such as the Windows 10 Fall Creators Update but also took the time to comfort those worried about the small presence of Windows phones at the event and Microsoft’s growing focus on iOS and Android devices.

“We’re going to continue to support Windows phone,” Belfiore said before adding that, “Windows is a platform that drives the experience on a whole range of devices. We live in a highly diverse world.”

With the significantly higher number of users on iOS and Android compared to Windows 10 Mobile, it’s understandable that Microsoft would want to offer their services and products to those using those ecosystems. This often frustrates Windows phone users though as it can appear that Microsoft favors offering support for other companies’ mobile devices over their own. And for the most part, recently anyway, this has been fairly true.

It’s been a while since Microsoft released their own Windows phone device (they’ve been relying on other companies to manufacture phones) but the Windows 10 Mobile operating system continues to get updates (though admittedly not as big as the Windows 10 updates) as do many Windows phone apps. There’s also a growing number of rumors and statements that suggest that Microsoft could be planning a “Surface Phone” which could radically redefine what a smartphone looks like and is used for.

Advertsing

125X125_06

Planet Xamarin

Planet Xamarin

Calendar

<<  November 2017  >>
MonTueWedThuFriSatSun
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

Month List