Tag Archives: Awesome

Pushing the limits of Hybrid WebView in Xamarin.Forms!

Let’s push the possible limits of Hybrid WebView and build something awesome in Xamarin.Forms! 😀

Remember my last blog post, Building a bi-directional interop bridge with WebView in Xamarin.Forms! which is where I shared about building a bi-directional invoke bridge between Javascript and C# dotnet run time using Hybrid WebView.

So based on that I went on a little journey to push the limits of this Hybrid WebView and built some cool demos with it. So here I am sharing it all with yol! 😉

Pushing the limits!

BTW: This is going to be a continuation of my previous blog post, so better take a look at it first if you haven’t: Building a bi-directional interop bridge with WebView in Xamarin.Forms!

To put it into fancy words,

We built a bi-directional communication bridge, between completely different run times, with possibility of two way execution invoke on demand! Hybrid WebView…

So now, the question is, what can we do to push the limits of our Hybrid WebView? Sounds like something for the imagination to limit!

Behold the awesomeness!

Imagine, being able to load a Web page into you Xamarin.Forms WebView, and being able to access Device features such as Camera, GPS Location, Accelerometer, etc..

Basically we’re going access Device Native features through the WebView and retrieve data directly from C# .NET run time in our Xamarin.Forms app! You will be able to load any HTML content, either from a Web Hosted source or locally generated HTML source, it would work like a charm thanks to the Hybrid WebView!

In order to demonstrate this awesomeness, let’s try out the following feature for the demo implementation…

  • Capture Photos using Device Camera
  • Pick Photos from Device Gallery
  • Get Device Native information
  • Get Device GPS Location data

All those device features and data will be accessed from the Javascript running inside the Hybrid WebView! 😉

Like I mentioned before, we will have two HTML sources for this demo, a web hosted HTML source and a locally generated HTML source to make sure it works for either cases! 😀

Now here’s a bit about what will help us build this awesome demo..

– Bi directional bridge!
Being able to invoke executions directly between the Javascript environment and C# .NET Xamarin.Forms run time, is what is going to help us build this awesomeness!

Javascript <~> Xamarin.Forms (C# .NET)

So you can pass data from the Javascript that’s running inside the Hybrid WebView out into the C# .NET run time, as well as you can pass data directly into the Javascript that’s running inside the Hybrid WebView.

– Multiple parameters…
In my previous blog post I mentioned this at the end where you can extend the same implementation we did for our Hybrid WebView, into supporting multiple parameters, so here I will use this to demonstrate what we’re going to build!

Sneak Peak!

Now here’s some action on the go with this awesomeness… 😉

As usual I’ve hosted this whole demo project up on my github repo:

Code on github: https://github.com/UdaraAlwis/XFHybridWebViewAdvDemo

This is how we do it!

So let’s get right into it, but first let’s make sure some prerequisites.

– Basic Hybrid WebView implementation
Refer to my previous post and check out the implementation of the Hybrid WebView. Building a bi-directional interop bridge with WebView in Xamarin.Forms!

– Xamarin.Essentials set up to access the device native feature
You need to implement Xamarin.Essentials and set up all the device native features and their configuration for the features you wish to use. https://docs.microsoft.com/en-us/xamarin/essentials/

Multiple Parameters support!

Let’s begin with adding support for multiple parameters in our Hybrid WebView as follows…

public class HybridWebView : WebView
{
	private Action<string, string> _action;

	public void RegisterAction(Action<string, string> callback)
	{
		_action = callback;
	}

	public void Cleanup()
	{
		_action = null;
	}

	public void InvokeAction(string param1, string param2)
	{
		if (_action == null || (param1 == null && param2 == null))
		{
			return;
		}

		if (MainThread.IsMainThread)
			_action.Invoke(param1, param2);
		else
			MainThread.BeginInvokeOnMainThread(() => _action.Invoke(param1, param2));
	}
}

Code on github: /XFHybridWebViewAdvDemo/Controls/HybridWebView.cs

As you can see, I have defined Action property with two parameters, along side the setter method of it, RegisterAction() accepts Action instances with two parameters.

InvokeAction() which gets called from each native renderer level now accepts two parameters accordingly. As an addition I have added an enforced UI Thread execution using Xamarin.Essentials.MainThread feature, since we’re going to access IO heavy device features.

Following the same pattern you can add as many number of parameters as you wish! 😉

We need to add support for this in our Javascript implementation as well, so we create a pre defined separator (a pipe separator preferably “|”) that separates parameters in the data object we’re sending from javascript to Hybrid WebView’s Renderer’s script handler.

..
invokexamarinforms('PHOTO|CAMERA')
..

When our Hybrid WebView renderers receive the invoke from Javascript, we need to handle the incoming data object as follows by splitting it up using the separator we defined…

var dataBody = data;
if (dataBody.Contains("|"))
{
	var paramArray = dataBody.Split("|");
	var param1 = paramArray[0];
	var param2 = paramArray[1];
	((HybridWebView)hybridRenderer.Element).InvokeAction(param1, param2);
}
else
{
	((HybridWebView)hybridRenderer.Element).InvokeAction(dataBody, null);
}

Then we pass it on to the InvokeAction() event, for Xamarin.Forms level to handle whichever the Action has subscribed to it. This way you can handle as many parameters as you wish!

Launch invoke from HTML Javascript to C# .NET!

So here’s how we set up the simple implementation to call up the invokeXamarinFormsAction() method that we have defined in our Hybrid WebView platform Renderers. Well there’s not much different from what we implemented in my previous demo, but here we are passing multiple parameters into the javascript method upon the button click.

...

<script>
...
function invokexamarinforms(param){
    try{
        invokeXamarinFormsAction(param);
    }
    catch(err){
        alert(err);
    }
}
</script>

...

<button type="button" 
	onclick="invokexamarinforms('PHOTO|CAMERA')">
	Get from Xamarin.Forms</button>

...

This is something I’ve explained step by step in my previous blog post so I wouldn’t go into details in here. You can define as many onclick actions as you wish with the set of predefined parameters like “PHOTO|CAMERA” and “PHOTO|GALLERY”, even single parameters, “GPS” and “DEVICEINFO”, etc…

Next you need to handle those parameters in C# code to execute the specific action we’re targeting, as simple as a if-else block as follows, or even a switch statement would suffice.

...

private async void ExecuteActionFromJavascript(string param1, string param2)
{
	...	
	if (param1 != null && param1.Equals("PHOTO") && param2.Equals("CAMERA"))
	{
		var result = await _deviceFeaturesHelper.TakePhoto(this);
		if (result != null)
		{
			...
		}
	}
        ...
	else if (param1 != null && param1.Equals("DEVICEINFO"))
	{
		var result = await _deviceFeaturesHelper.GetDeviceData();
		if (result != null)
		{
			...
		}
	}	
	...
}

Based on the requested action we execute it in C#, in this case accessing Camera and Capturing a photo _deviceFeaturesHelper.TakePhoto() or even getting Device Native information _deviceFeaturesHelper.GetDeviceData() as shown above.

Let’s move to the next step of this chain…

Ping back from C# .NET to HTML Javascript!?

Now that we established pathway to call the C# .NET run time from Javascript, we’re able to invoke any action, but how do we get back the result data into the Javascript?

So in my previous blog article Talking to your WebView in Xamarin.Forms! which explains how easy it is to pass data into the Javascript rendered inside the WebView at run time, since our Hybrid WebView is an extension of the default WebView, we can use the same method here…

...
        var result = await _deviceFeaturesHelper.GetDeviceData();
        if (result != null)
        {
             await webViewElement
                   .EvaluateJavaScriptAsync($"setresult('{result}')");
        }
...

So we’re calling up on EvaluateJavaScriptAsync() with the Javascript function name that’s accepting to the results for this specific action. This function needs to be created inside the Javascript before hand, that is rendered inside the Hybrid WebView as follows…

...
<script>
...
	function setresult(value) {
		// - display the value in HTML
		// - send the data to server
	}
</script>
...

Once the data is passed into your Javascript function, You can do whaever you want with the data, be it display in the HTML, or send it up to a web server, your choice! 😉

Calling the Device Native!

Well this is quite simple if you know how to use Xamarin.Essentials to access device native features and other 3rd party plugins to access various features from Xamarin.Forms! But I’ll quickly walk through the code that I’m using in this demo.

I’ve basically created like a little Facade layer which handles all the device native features required as follows, and each method handles a given specific feature such as Camera and GPS features using their respective services of plugin calls…

public class DeviceFeaturesHelper
{
	public async Task<string> TakePhoto(ContentPage pageContext)
	{
		// launch Media Plugin to capture photos from camera
	
		...

		return imageAsBase64String;
	}
	
	public async Task<string> GetDeviceData() 
	{
		// launch Xamarin.Essentials to load device info

		return $"{nameof(DeviceInfo.Model)}: {device}<br />" +
			$"{nameof(DeviceInfo.Manufacturer)}: {manufacturer}<br />" + 
			$"{nameof(DeviceInfo.Name)}: {deviceName}<br />";
	}
}

Code on github: /XFHybridWebViewAdvDemo/DeviceFeaturesHelper.cs

So what you need to keep in mind is that we need to return a value that’s compatible to be displayed inside our WebView, based on HTML, that’s why you see I have modified some of those returned values accordingly, such as Image objects are returned as base64 strings and device information formatted as a text block with <br /> inline.

These methods are called from the Hybrid WebView’s Invoke action that we created before and results are returned to be pushed back into Javascript.

Handling Media Image objects…

Using Media Plugin for Xamarin.Forms, provides you with a MediaFile object which contains the Image object that you acquired either from Camera or Gallery, but how do we convert that into something that’s compatible to be pushed into Javascript-HTML environment?

The solution is,

MediaFile -> byte[] array -> Base64 string

We’re going to convert our MediaFile object into a byte[] array, then convert again into a base64 string, which makes it so much easier to transfer the data into the javascript run time and use that object for any purposes inside javascript itself. Here’s my code snippet for this…

public async Task<string> TakePhoto(ContentPage pageContext)
{
        ...
	var file = await CrossMedia.Current.TakePhotoAsync(...);

	// Convert bytes to base64 content
	var imageAsBase64String = Convert.ToBase64String(ConvertFileToByteArray(file));

	return imageAsBase64String;
}

private byte[] ConvertFileToByteArray(MediaFile imageFile)
{
	// Convert Image to bytes
	byte[] imageAsBytes;
	using (var memoryStream = new MemoryStream())
	{
		imageFile.GetStream().CopyTo(memoryStream);
		imageFile.Dispose();
		imageAsBytes = memoryStream.ToArray();
	}

	return imageAsBytes;
}

This is what you saw in the previous section which I have used in my /DeviceFeaturesHelper.cs
You can use this in the javascript functions as easy as below,

function setresult_takephoto(value) 
{
	document.getElementById("photoCamera_ResultElement").src 
                                             = "data:image/png;base64," + value;
}

Well that’s the entire set up of this awesome demo, so then let’s see it in action…

Fire it up!

Here’s the web page we’re loading: https://testwebpage.htmlsave.com/

Look at em on fire, Android, UWP and iOS side by side…

Code on github: https://github.com/UdaraAlwis/XFHybridWebViewAdvDemo

Conclusion…

This was just me pushing the limits of the Hybrid WebView to build awesome stuff with Xamarin.Forms! This will definitely come in handy whenever you get a scenario you need to implement an existing Web App into a Xamarin.Forms app, and you need to let the user use it as a Mobile App, with being able to access device native features.

Well that concludes it. Hope you find it useful!

Share the love! 😀 Cheers!

Why MVVM is Awesome!

I used to be a code behind event driven loving developer! but since I found MVVM, I never looked back, MVVM all the way!

From Code-behind Event-driven addict to MVVM fanatic…

So for a developer who’s coming from a code behind event based implementation loving developer, I understand, adopting MVVM to your application could be pretty confusing and hectic at the beginning!

Because I know it very well by my own experience, whereas I used to be a stubborn noob developer in the good old days thinking Event Driven WinForms approach is the best way to developer software. Which led me to suffocate massively when the code base got bigger and bigger, having massive hard time debugging, maintaining and even upgrading programs I was coding. Honestly I couldn’t understand the cause for this at the beginning due to my stubborn mindset of praising code-behind even driven programming style.

Step 1:

Then when I got into my career I had to force myself to start using MVVM based implementation. And yes it was super confusing and troublesome to understand.

Step 2:

But trust me after a while, step by step,  you start to see how fun it is, makes you feel like wiring up some electronic circuit to get it to work, how all those components gets wired up each other while still having the modules separately.

Step 3:

And you will notice how easy it is to maintain and extend your code base… 😉

Short and sweet,

MVVM stands for Model View View-Model

and it’s AWESOME!

Here is why?

  • MVVM enable true separation between your User Interface(Views) and Logical Code(ViewModel/ Model)! Yes decoupling is ghuuud!
  • Easily handle events with Commands – ICommand
  • Never underestimate the power of INotifyPropertyChanged
  • Take the best use of Binding (View to ViewModel properties)
  • With ViewModel you can easily manipulate Model’s data as you wish and set them to be bound to any Views as you wish and vice versa. Yes it’s that flexible!
  • Yes, the ultimate portability of your project’s components
  • Testing made super easy as the separation between UI and Code behind logic
  • Extremely ease of maintenance and adding changes to your code base

So there you go, a short and sweet post I made during my free time! 😀

hope it helped anyone or may be inspired someone to make the switch! 😉

Just a moment before the Graduation…. ;)

And the day is finally here, officially

Graduating in BENG(Hons) Software Engineering (Second Class First Division) ! xD

Reminds me of the very humble beginning of this dream, when I decided to drop off from my A/Ls Mathematics stream after 6 months of time waste…

When I decided to chase my dream, my passion for technology and innovation, that desperate need of achieving my goal…

Whereas most of my school friends got rid of me thinking that I’m a loser to skip the time waste of A/Ls and jump start my Undergraduate studies, even though they didn’t even know the meaning of what a “Degree” was back then ! 😛 (Seriously everyone thought, I was doing a computer diploma even though I tried to explain that I’m studying for a degree lol) When they were going for Tuition classes I was going for undergraduate Lectures, which I still remember most of them ignored me even in the buses ! 😀 lol

Well after all the hard work and incredible journey of over 3 years end, while my old school friends are still doing CIMA, SIM and all the typical lame courses you do when you waste your life with A/Ls, and trying to find their way… here I am,

Right after my final exams, I got recruited as

a Software Engineer by one of the top IT companies in Sri Lanka just by the age of 21, earning piles of money each month since then, and living my Dream to the fullest ! ^_^

Never underestimate the power of a passionate crazy Dreamer ! 😉

YES I DID IT ! 😀