Category Archives: Achievements

So I took up on TravelMonkey, the Xamarin + Cognitive Services Challenge!

Let me share my little adrenaline filled panic adventure into earning some awesome Xamarin Swag! from the Xamarin + Cognitive Challenge hosted by Microsoft, the TravelMonkey Challenge! 😀

Well it’s come to 2020, in the middle of a pandemic, a lock down, and it’s been a while since I took up on an actual challenge outside my work and personal coding experiments! Then I suddenly came across this little challenge posted by Microsoft, TravelMonkey – the Cognitive Services + Xamarin Combo Challenge! (https://devblogs.microsoft.com/xamarin/cognitive-services-xamarin-challenge/)

Backstory…

As usual, the first thing I checked, what’s in it for me, you know what I mean! 😉 YES! they had promised some awesome Microsoft swag! Xamarin t-shirts, monkeys, and stickers!?! Say no more, I was in! 😀 well at least I thought to myself… their Submission deadline was April 30, 2020 11:59 PM PDT!

The days went by, one by one, without even any second thoughts, yeah I’d do it tomorrow, or day after or some time… I’ll get it done!

Then suddenly, it was 29th April, the Friday night, oh shoot! tomorrow’s the deadline for submission of the awesome TravelMonkey challenge! Yeah well I could say it was my own procrastination that got me in that situation, I had waited till the last day!

Procrastination is bad!

Just like in that GTA San Andreas scene, in my head I was like, “Ah sh*t, here we go again!” it was literally a moment of panic, and I was the fence about giving it up. But then it was Friday night, the day I usually watch a good night movie and fall asleep to wake up very late on Saturday! 😦

But then again, it was middle of a pandemic lock down, and I haven’t really had this kind of a fun challenge in a while, so I thought of pulling an all nighter and getting it done! at least something worth while before the next 24 hours ended… 😮

At this point, I didn’t have a plan of what I’m going to be building or expand up on, so I thought of simply exploring the current implementation and figure out where are the points in which I could improve as for the challenge. Once again, it was a bad idea to start working on it, at a time when it was less than 24 hours before the submission! lol 😀

Sneak Peek!

But at the end, here the beauty I ended up building…

I know right.. gorgeous!

Yeah well behind all that eye-candy glamour there was a painful sleepless all-nighter experience, waiting to be unraveled…

Getting started…

So first, I forked the github repo from https://github.com/jfversluis/TravelMonkey into my own github repo: https://github.com/UdaraAlwis/TravelMonkey and set up the Azure Cognitive services in Free tier with the following,

  • Azure Computer Vision
  • Bing Translation
  • Bing Image Search

Then I got the API keys and hooked up into the Xamarin Mobile app project.

New Featurettes!

This is a travel related app! even though it is fictional. lol So I wanted to think of it as being used by smart Monkeys like us, who would love to see beautiful scenic photos of the top travel destinations in the world.

Why stop there? I should allow the users to search for a destination and view the top scenic photos of that destination, as a little cherry on top! 😉

Also how about letting the user translate any text into any language they choose? That would definitely come in handy for any traveller!

Bing Image Search FTW!

So I picked up the most visited destinations by international tourist arrivals data from Wikipedia, https://en.wikipedia.org/wiki/World_Tourism_rankings and hooked it up into the Bing Search Service to load images of those destinations. Each destination would be taken up with 10 images and we would randomize through them in the Home page carousel.

var client = new ImageSearchClient(
new Microsoft.Azure.CognitiveServices.Search.
ImageSearch.ApiKeyServiceClientCredentials(ApiKeys.BingImageSearch));

var imageResult = await client.Images.
SearchAsync(
	$"{destination} attractions", 
	minWidth: 500, 
	minHeight: 500, 
	imageType: "Photo", 
	license: "Public", 
	count: 10, 
	maxHeight: 1200, 
	maxWidth: 1200);

See how I modified the Bing Image search query there, {destination} attractions where as it would be executed as “France attractions”, “Thailand attractions”, and etc. So just like that I refined the search terms for scenic tourist photos from Bing Images.

Destination scenic Gallery!

I decided to add a travel destination Gallery page, consisting of scenic travel photos from Bing. User would be able to pick a destination from a presented list of countries in the Home page itself, and then navigate to its Gallery page to view the top 10 most scenic photos from Bing.

Here I did a little trick to load a list of countries in C# by tapping into CultureInfo object provided by .NET framework, pretty handy!

private static List<string> GetCountries()
{
	List<string> countryList = new List<string>();

	var getCultureInfo = CultureInfo.GetCultures(CultureTypes.SpecificCultures);

	foreach (var getCulture in getCultureInfo)
	{
		var regionInfo = new RegionInfo(getCulture.LCID);
		if (!countryList.Contains(regionInfo.EnglishName))
		{
			countryList.Add(regionInfo.EnglishName);
		}
	}

	return countryList;
}

This would return the list of countries in the world which I will be presenting to the user to choose from! I will use the Bing Image Search that I had already modified to load the scenic travel images set on the go.

Bing Translation FTW!

So I thought of adding some improvements to the Translation features, where currently they had a pre-set of languages they would translate to given the input text. I wanted to make it completely dynamic, by getting the list of languages available in Bing Translation service, and letting the user pick the languages they want to translate to.

Here’s how I got the list of supported languages Bing Translation,

public async Task<List<AvailableLanguage>> GetLanguageList() 
{
	string endpoint = ApiKeys.TranslationsEndpoint;
	string route = "/languages?api-version=3.0";

	using (var client = new HttpClient())
	using (var request = new HttpRequestMessage())
	{
		...
		request.RequestUri = new Uri(endpoint + route);
		// Send request, get response
		var response = client.SendAsync(request).Result;
		...
	}

	List<AvailableLanguage> availableLanguages = new List<AvailableLanguage>();
	foreach (var item in translationStatsResult.Translation)
	{ ... }
	return availableLanguages;
}

Once I got the available languages list, I would present them to the user to pick from for translating their input text. But during the app’s first time launch I would randomly pick 5 languages and show the translations.

So here’s how I extended the Translation service call with the dynamic request language list,

public async Task<List<AvailableTranslation>> 
TranslateText(string inputText, List<AvailableLanguage> listOfLanguages)
{
	// build the translate url chunk
	string requiredTranslationsString = "";
	foreach (var item in listOfLanguages)
	{
		requiredTranslationsString = requiredTranslationsString + $"&to={item.Key}";
	}
	
	...
	request.RequestUri = new Uri(ApiKeys.TranslationsEndpoint + "/translate?api-version=3.0" + requiredTranslationsString);
	... 
	
	translations.Add( new AvailableTranslation()
	{
		InputLanguage = bestResult.DetectedLanguage.Language,
		InputText = inputText,
		TranslatedLanguageKey = t.To,
		TranslatedLanguageText = t.Text,
		TranslatedLanguageName = MockDataStore.Languages.FirstOrDefault(x => x.Key == t.To).Name,
	});
	
	return translations;
}

I’m dumping them all into a list of AvailableTranslation objects which I will be unpacking in the UI for displaying the results of the input text translation.

Caching a bit of data!

Now this is something I had kept till the last minute, hence I couldn’t complete it as I expected, but I still managed to store some data in the app memory during run time to reduce repetitive duplicate queries to Bing services, which will also help me reduce the free tier quota usage.

I managed to store the list of destination scenic image result data and translation text in memory as a simple static singleton data object.

Emoji Support 😀

It would be nice to have some Emoji support for our text labels in the app, I thought. So I added it with the following nice little snippet I came across, https://github.com/egbakou/EmojisInXamarinForms

So with that nice little snippet I could insert emojis into a text and bind them to any Label element in Xamarin.Forms, nice and easy!

Title = 
$"Something went wrong 
{new Emoji(0x1F615).ToString()} 
Here is a cat instead!"

It will display the given emoji natively to the run time platform hence we’re using unicode representation of that emoji! 😉

No more icon files!

I really don’t like using physical image files for representing icons, so I got rid of them and introduced full Font Awesome based icons to the entire app. Setting it up in Xamarin.Forms is pretty easy now!

[assembly: ExportFont("fa-regular.otf", Alias = "FontAwesomeRegular")]
[assembly: ExportFont("fa-solid.otf", Alias = "FontAwesomeSolid")]

Like this label that shows a little globe icon using Font Awesome!

<Label
	Margin="0,0,12,0"
	FontFamily="FontAwesomeSolid"
	FontSize="20"
	Text=""
	TextColor="Gray"
	VerticalOptions="Center" />

Yeah Font Awesome is pretty handy!

https://montemagno.com/xamarin-forms-custom-fonts-everywhere/
https://dev.to/codingcoach/using-font-awesome-in-xamarinforms–3mh

Fix Android Status bar…

I know its annoying to deal with Android Status bar styling, and most of the time devs don’t even bother fixing it accordingly to their app theme. They end up leaving the ugly blue color bar at the top of the app.

But I wanted to make it right. May be I am too much of a perfectionist! 😛

<resources>
    <style name="MainTheme.Base"
			parent="Theme.AppCompat.Light.DarkActionBar">
        ...
        <item name="colorPrimary">#bfbfbf</item>
		...
        <item name="colorPrimaryDark">#d9d9d9</item>
        ...
        <item name="colorAccent">#808080</item>
		...
    </style>
</resources>

So I updated the Android Status bar styling values accordingly to my intended color scheme for the app.

PancakeView is yummy!

Yo this right here is a gem, such an awesome element to have in your app, provides loads of features and customization. https://github.com/sthewissen/Xamarin.Forms.PancakeView

It’s super simple to use, where I’ve used it as a container for many elements to provide a beautiful Shadow effect.

<yummy:PancakeView
	Margin="7"
	BackgroundColor="White"
	CornerRadius="20,0,0,40"
	HasShadow="True">
	<Grid Margin="0">
		<Image Aspect="AspectFill" Source="{Binding ImageUrl}" />
	</Grid>
</yummy:PancakeView>

I’ve used this beauty across the entire app in all pages to give a gorgeous gradient effect of Page background as shown below…

<yummy:PancakeView
	BackgroundGradientAngle="40"
	BackgroundGradientEndColor="White"
	BackgroundGradientStartColor="#d9d9d9">
	<Grid>
	...
	</Grid>
</yummy:PancakeView>

I’m so glad I came across this awesome nugget thanks to this challenge! 😀

Beautify XAML…

One thing I noticed in the original project was that the XAML wasn’t properly formatted and it was inconsistent with different tabs and spacing.

I would recommend using any XAML formatting tool in Visual Studio like XAMLStyler which automatically formats your XAML properly while you code. Something nice to have I assume. 😉

Let me make it prettier…

On top of my head, I did not like the UI, not at all. Not blaming the original devs, who’s done a great job putting it together, but I wanted to re-skin it my way, and sprinkle a bit of eye-candy awesomeness… 😉

One thing I love for sure, is building sleek, responsive, minimalistic and yummy looking Mobile App UIs. So that’s what I did. 😀 I decided to implement a minimalistic unified-white color based gradient-ized sleek UI, which called for a whole bunch of restructures in the UI.

So I changed all the color schemes they used and replace them with a white and dark-gray based gradient style in almost all the elements across the app.

Let’s look at those one by one…

Gradient-zing!

Who doesn’t love some good old gradient effects, at least when its well done!

Thanks to the PancakeView we can now easily add this effect to Xamarin.Forms elements, which I have used extensively in my UI design changes as well…

Here’s one example where I modified the AddPicture page with my new color scheme.

Splash it up!

One of the first things I wanted to get rid of was the original splash screen, I did not like it at all, and it was honestly scaring to see a cute little monkey exploding in a high speed animation on the screen. lol

So I change the whole splash screen animation into a smooth zoom-in and fade-out effect as shows in the code below…

private async Task AnimateTransition()
{
	...
	await Task.Delay(1000);

	// Scaling up smoothly upto 5x and Fading out as the next page comes up.
	var explodeImageTask = Task.WhenAll(
		Content.ScaleTo(5, 300, Easing.CubicOut),
		Content.FadeTo(0, 300, Easing.CubicInOut));
	...	
}

Once it completes we navigate to the MainPage. Now that animation was much pleasing to look at…

I felt like that cute little monkey got some justice! lol

Home page!

So like I mentioned before I laid out a full layout design restructure and one of the main pages was the Home page.

  • Getting rid of confusing layout
  • Focusing on the travel photo background
  • Getting rid of the empty space
  • Making sure content properly fills the page

This is a travel related app, so it should be focused on giving such experience for the user so I decided to maximize on the scenic travel photos in the home page, thus resizing the Image element to take up to 70% of the page space.

Also I’ve added navigation for the user to click on the destination name to and to be navigated to that travel destination’s scenic travel photo gallery page.

Look at that beauty eh! 😉

The user picture grid at the bottom, while giving it a fixed height, I managed to fix a whole bunch of alignment issues inside the template container as well.

I added a new element above the translation text element for the user, to select a destination where they would like to view, and navigate to that page from home page itself.

Woot! woot!

Next’s let’s see that beauty in action…

Travel Destination Page…

So from the home page once User selects a travel destination to view, then they get navigated to this gorgeous page filled with scenic travel photos of that destination, pulled from Bing Image Search results…

It gets even better, here’s what you see when you select Italy…

Truly gorgeous… Well I’ve used Pancake View here for the full page background for the gradient effect and shadow effect for the Image containers.

<DataTemplate>
	<yummy:PancakeView
		... >
		<Grid Margin="0">
			<Image Aspect="AspectFill" Source="{Binding ImageUrl}" />
		</Grid>
	</yummy:PancakeView>
</DataTemplate>

Bingo!

Translation revamped!

So as I mentioned before I’ve implemented a new feature extending Bing Translation, allowing the user to pick the languages they want to have their input text translated into.

Here’s the new Page I implemented for it, where I load the list of languages for the user to choose from. I love how Bing translation actually provides the native word for the languages in their own language. 🙂 pretty neat eh!

Once the user selects the languages, I will be saving that in the memory as user preferences. Then next time User enters any text for translation, I would be showing them the list of translations according to their preferred languages. 😀

Now ain’t that handy! 😉

Last minute Pull requested!

Yes, literally last minute! So after all that panic filled sleepless all-nighter effort, I manged to finish up some good looking app with cool features added, and trust me when I say, I literally submitted the Pull Request at the very last minute, exactly at 11:58 PM on April 30, 2020 PDT. Just one minute before the deadline! 😀

Here’s my Pull Request on github: https://github.com/jfversluis/TravelMonkey/pull/25

That was such an adventure, I think this was the first time I stayed up all night for coding, after many years since graduation! 😀

Here’s the repo in my github: https://github.com/UdaraAlwis/TravelMonkey

Well I could have done a much better job, in terms of features, code refactoring and standards, if I hadn’t procrastinated till last minute. I wouldn’t blame someone, if they looked at the code and complained, hence its not the cleanest considering my usual quality standards! but I would consider it was a satisfying completion, given the whole last minute stress and staying up a whole night! 😛

We got Swag!

So as they promised we got them swags yo! 😀

But but… later I got even a better news,

Well at the end all the participants got $25 gift codes to spend at .NET Foundation store! 😀 yaay! 😍

Oh well.. what an adventure! Thank you Microsoft! ❤️

Conclusion

This was such an awesome opportunity, and I’m glad I pulled through somehow even if it was last minute effort! It was actually fun! Learned another lesson not to procrastinate stuff like these till last minute, at least not till 24 hours prior to submission deadline. lol

Sharing a bit of Azure bits, it was surprisingly easy to integrate all these kinds of cool features with Azure Cognitive Services without having to deal with any complicated computing. If it was few years back I would have to deal with all these language translation and image processing stuff all by myself.

So glad I found the new PancakeView thanks to this challenge, it was quite handful, specially in crafting those beautiful gradient and shadow effects.

Finally I should send special thanks to Microsoft and @jfversluis @codemillmatt for this awesome opportunity!

Share the love! 😀 Cheers yol!

Me Tech Talking at Xamarin Dev Days 2017, Singapore…

Here’s all about my tech talk at Xamarin Dev Days Singapore 2017, under the session, Cross Platform Native UI with Xamarin.Forms…

So on 4th of November Xamarin Dev Days Singapore 2017, concluded with a massive success, with a full house attendance, and as of me I happened be a presenter there.

a full house turn up at Xamarin Dev Days Singapore 2017…

Hosted by Microsoft with the support of Xamariners and SyncFusion, it was a full day community event.

As of myself, Udara Alwis, I was presenting my tech talk session on Cross Platform Native UI with Xamarin.Forms, where talked all about Xamarin.Forms and building cross platform apps with fully native look and feels, while being able to access platform specific features easily, and the latest updates and features of Xamarin.Forms.

udara alwis presenting tech talk xamarin dev days singapore 2017
oh! that’s me, presenting my tech talk…

Along side with an in detailed Live Demo of how Xamarin.Forms runs natively on Android, iOS and Windows with all the native look and feels.

Here are the event details if anyone’s keep on tito, Xamarin Dev Days event Link: on tito. Also if anyone’s looking for the Event photos, its all hosted in the Xamariners Facebook page and Meetup event page: on Meetup 

So I’m about to share some of the stuff I presented at my talk there, although I will not be diving into every single detail I talked about there, only be focusing on the key points.

Cross Platform Native UI with Xamarin.Forms…

So as we all aware, Xamarin.Forms is all about allowing developers to build native UIs for Android, iOS and Windows from single shared C# code base, while maintaining full native look and feels as well as native features.

In the beginning we had native Xamarin, which is the C# and dot net wrapper around the native platforms, where you had to manually develop the UI layer for each specific platform, but still allowing the shared business logic.

Then came Xamarin.Forms, the new abstraction layer that sits on top of the native platforms and abstracts up all the common properties and behaviors to a single abstraction layer, allowing you to develop the UI in one single code base and deploy directly into native platforms, along with the shared business logic. 😉

Windows vs Xamarin.Forms Development…

Here I did something pretty special that is to compare the UI Controls in Windows Dev Environment, and Xamarin.Forms Dev Environment. This helped most of developers who comes from Windows Development background to easily familiarize themselves for Xamarin.Forms development.

As of the MVVM Architect savvy fellas, do not worry Xamarin.Forms supports full binding out of the box, just like you had in Windows Development.

Eco System and Community…

It had been an incredible rise of the community around Xamarin since the Open-Source initiation by Microsoft, with some incredible statistics. 😮

Some of the Latest and Greatest in Xamarin.Forms…

In this section I dived into some of the latest updates of Xamarin.Forms.

Native View Declarations..

Now you can declare Platform Specific Elements inside your Xamarin.Forms pages, yes that’s correct even from XAML directly. 😀

Page Embedding…

Page Embedding has been one of my favorites, being able to embed Xamarin.Forms Elements in your Xamarin Native code. A great way to adopt Xamarin.Forms elements into your existing Xamarin Native applications. 😉

New Performance Updates…

Yes the Engineers in Xamarin has been busy with improving the performance of Xamarin.Forms lately, which is pretty impressive…

Layout Compression…

So whenever you create user interface in your mobile app, it forms some kind of a hierarchy of the Layouts and Control Elements. And you know for a fact the more higher the hierarchy the more performance is consumed by the Layout Renderer.
So its the same case here in Xamarin Forms, specially here it adds some extra layers in between the UI elements to do its Native Magic.

As you can see above the Xamarin.Forms Layout has 12 Elements in the UI, but in reality at run time it increases up to 19 Elements in the UI.

That’s why they’re introducing this new performance enhancement feature called Layout Compression. So what this new feature does it is remove the unnecessary nesting of the hierarchy and compress it as much as possible.

There you can see above as a result of the new feature how the Layout Hierarchy is flatted and compressed down to 16 Elements.

Fast Renderers…

Yes that literally means speeding up the Rendering process of a given Element at runtime. As we know in Xamarin.Forms, each UI Element has a Renderer attached to it, that handles all the native mapping with Xamarin.Forms layer. This Renderer layer also contributes to the unnecessary UI hierarchy for the Layout Renderer.

That is why with this new Fast Renderers feature they’re merging the Element and its Native Renderer into one single Element, causing the whole UI Layout Hierarchy to compress down itself even further.

As a result you can see above example, the 12 Elements hierarchy we had in Xamarin.Forms has compressed down to 10 Elements at run time, resulting in massive performance improvement.

New Backends…

So Xamarin.Forms is all about Cross Platform application development, that’s why they’re now expanding their horizons into some new platforms, allowing you to write you code in Xamarin.Forms in a single code base and deploy to the new platforms right away, without having to write any native code line at all… 😉

  • Tizen : yaay! Samsung devices…
  • WPF: Oh yeah! beautiful WPF, here we come…
  • GTK#: Ubuntu? or whatever your Linux flavor… 😉
  • MacOS: Woot! Woot! MacOS apps…
More…

And with a lot more awesomeness…

All of it on github…

That’s right, I’ve hosted all of the slideshow and the full demo code up in my github: https://github.com/UdaraAlwis/XamarinDevDays-2017-Singapore-Udara

Finally thanks everyone who attended Xamarin Dev Days Singapore 2017 and contributed to make it a success. 😀

Cheers!

So I gave a Tech Talk on SkiaSharp with Xamarin.Forms…

A little back story…

Few months back our company was asked to do a graphics application, so we decided to take a look into graphics rendering libraries available for Xamarin.Forms, given the limited time, we thought of going for SkiaSharp over other alternatives, which we had very little knowledge of how to work with.

But to our surprise we managed to build an incredible app with beautiful interactive graphics and animations completely using SkiaSharp with Xamarin.Forms. So I thought of sharing my experience with the fellow dev community. 😀

Opportunity…

So few weeks back (18th June, 2017), I had the opportunity to give a tech talk-hands on demos, at Singapore Mobile .Net Developers  meetup, under the topic “2D Graphics Rendering in Xamarin.Forms with SkiaSharp”!

udara alwis presentation skiasharp xamarin microsoft

So I’m about to share some of the stuff I presented at this meetup, although I will not be diving into every single detail I talked about there, only be focusing on the key points (mostly on the hands on demo bits). If you’re interested in learning SkiaSharp for Xamarin.Forms, go ahead to the the incredible documentation provided by Xamarin: https://developer.xamarin.com/skiasharp/

Here’s the short recap of the presentation I did over there! 😉

2D Graphics Rendering in Xamarin.Forms with SkiaSharp!

So let’s get started off with the Slideshow Presentation…

And you may grab the live hands on demo code I did at the presentation from my github repo: https://github.com/UdaraAlwis/XFSkiaSharpDemo

Now let’s recap…

Behold the incredible 2D Rendering Engine for Xamarin and Xamarin.Forms, SkiaSharp!

An open source project originally developed by Google(Thank you <3), from C++ language, by the name Skia. It is used across a huge variety of Google’s products, including web graphics rendering and so on. This is a Immediate mode 2D vector graphics rendering system, this framework allows you to do 2D graphics, handling and manipulating image resources and text and a lot of cool stuff. 😀

So SkiaSharp is the C# and DotNet wrapper of Skia framework allowing us to use it right on top of Xamarin, a mono based open source project, where you could add your own contribution to it via: github.com/mono/SkiaSharp!

SkiaSharp for Xamarin.Forms comes with the SKCanvasView that inherits from Xamarin.Forms.View which allows you to use it as just another View in your PCL code, and you don’t have to handle any native implementation, everything is accomplished right in your PCL code. 😉

SkiaSharp basics Demo..

For setting up SkiaSharp, open your nuget manager and install “SkiaSharp.Views.Forms” across your Xamarin.Forms solution, including PCL and platform specific projects.

Add the SKCanvasView to your page as you wish.

<ContentPage
    x:Class="XFSkiaSharpDemo.MainPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:forms="clr-namespace:SkiaSharp.Views.Forms;assembly=SkiaSharp.Views.Forms"
    xmlns:local="clr-namespace:XFSkiaSharpDemo">

    <forms:SKCanvasView x:Name="SkCanvasView" PaintSurface="SkCanvasView_OnPaintSurface" />

</ContentPage>

 

Notice the PaintSurface event, the most important execution point you need to handle in order to render your graphics on the SKCanvas. Every time you need to do any kind of a drawing or rendering of 2D graphics on your Canvas, you need to do it in this event, this method is first invoked when the Page appears on the screen, and then if the orientation changes or you could even manually invoke it by calling InvalidateSurface() of your SkCanvasView.

Let’s do that…

public partial class
	MainPage : ContentPage
{
	...

	private void SkCanvasView_OnPaintSurface
		(object sender, SKPaintSurfaceEventArgs e)
	{
		// Init skcanvas
		SKImageInfo skImageInfo = e.Info;
		SKSurface skSurface = e.Surface;
		SKCanvas skCanvas = skSurface.Canvas;

		// clear the canvas surface
		skCanvas.Clear(SKColors.SkyBlue);

		// retrieve the canvas info
		var skCanvasWidth = skImageInfo.Width;
		var skCanvasheight = skImageInfo.Height;
	}
}

 

This event provides you with all the required properties and values to execute your 2D rendering, such as the SKCanvas instance, which is the actual canvas you’re going to do the 2D drawing on, SKImageInfo instance which provides you with details such as actual Width and Height by pixels and so on.

The Clear() method call, clears up the canvas surface and prepare it for rendering new content, by passing it a SKColor object, you can paint it with that color.

2D Graphics with SkiaSharp..

The SKCanvasView is actually a placeholder for the SKCanvas which you can access in the PainSurface() event.

There’s many ways to draw or render stuff on our Canvas, but SkiaSharp also provides us predefined methods that allows us to draw simple types of shapes such as Circles, Lines and Texts, etc.

So usually when you are to do some complex drawings you would be using a combination of all those drawing methods at a given rendering cycle.

Transform Operations…

SkiaSharp allows you to do all kinds of Translations, Scaling, Rotating and even Skewing on the Canvas.

Usually on the Canvas, the X,Y coordinate system starts from the top left most corner and Y axis increments vertically and X axis increments horizontally.

So lets see how we could manipulate this in our favor and do some basic Translation and Scaling on the Canvas.

private void SkCanvasView_OnPaintSurface
	(object sender, SKPaintSurfaceEventArgs e)
{
	...
	
	// move canvas's X,Y to center of screen
	skCanvas.Translate((float)skCanvasWidth / 2,
				(float)skCanvasheight / 2);

	// set the pixel scale of the canvas
	skCanvas.Scale(skCanvasWidth / 200f);
}

 

There we are Translating the Canvas’s X,Y coordinate system to be started off of the center of the screen, and then Scaling the Canvas to the ratio of 200 pixels according to the actual canvas Width.

SKPaint object..

SKPaint object is one of the most important element in SkiaSharp, it holds the configuration for any given type of 2D rendering, so you’ll be storing your drawing configuration in that object, such as Color, Style, Stroke Width/Height, Anti Alias and so on.

SKPaint skPaint = new SKPaint()
{
	Style = SKPaintStyle.Fill,
	IsAntialias = true,
	Color = SKColors.Blue,
};

 

There’s how you instantiate a SKPaint object which you’ll using to render your 2D graphics, it’s got all kinds of drawing properties and configurations you can play around with. 🙂

Draw a simple Circle (Filled and Non-Filled)

Let’s get our hands dirty with some actual 2D drawing eh! 😉

// Drawing a Circle
using (SKPaint skPaint = new SKPaint())
{
	skPaint.Style = SKPaintStyle.Fill;
	skPaint.IsAntialias = true;
	skPaint.Color = SKColors.Blue;
	skPaint.StrokeWidth = 10;

	skCanvas.DrawCircle(0, 0, 50, skPaint);
}

...

// Drawing a Circle Stroke
using (SKPaint skPaint = new SKPaint())
{
	skPaint.Style = SKPaintStyle.Stroke;
	skPaint.IsAntialias = true;
	skPaint.Color = SKColors.Red;
	skPaint.StrokeWidth = 10;

	skCanvas.DrawCircle(0, 0, 70, skPaint);
}	

 

We shall be using the DrawCircle() whilst passing in the Circle’s center XY position and desired radius for it. To define whether its a Filled or Non-Filled circle we’ll be using Style property in our SKPaint configuration.

 

Look how simple and beautiful eh 😉

Since SkiaSharp support pure Xamarin.Forms you can straight away run all your native projects without any hassle of handling native code.

To learn more about drawing on the Canvas you can check out the official Documentation: https://developer.xamarin.com/guides/cross-platform/drawing/

Handling User Interactions…

When it comes to most Xamarin.Forms components, they do not have touch handlers, however the SKCanvasView comes default with a Touch event handler, Touch and a boolean property to enable or disable Touch Events, EnableTouchEvents.

You can straightaway use that even and property to handle touch events on the SKCanvas.

<forms:SKCanvasView x:Name="SkCanvasView" 
		EnableTouchEvents="True" 
		Touch="SkCanvasView_Touch"
		PaintSurface="SkCanvasView_OnPaintSurface" />

 

You can subscribe to it and look for the type of touch event and handle it.

private void SkCanvasView_Touch(
object sender, SKTouchEventArgs e)
{
	if (e.ActionType == 
		SkiaSharp.Views.Forms.SKTouchAction.Pressed)
	{
		_lastTouchPoint = e.Location;
		e.Handled = true;
	}

	_lastTouchPoint = e.Location;

	// update the Canvas as you wish
	SkCanvasView.InvalidateSurface();
}

 

As you can see it gives you the Touch point location. You can get a hold of the event and the touch point and you want to do some drawing on the SKCanvasView, then you could call the InvalidateSurface().

private SKPoint _lastTouchPoint = new SKPoint();
private void SkCanvasView_OnPaintSurface
(object sender, SKPaintSurfaceEventArgs e)
{
	...
	
	using (SKPaint paintTouchPoint = new SKPaint())
	{
		paintTouchPoint.Style = SKPaintStyle.Fill;
		paintTouchPoint.Color = SKColors.Red;
		skCanvas.DrawCircle(
			_lastTouchPoint.X,
			_lastTouchPoint.Y,
			50, paintTouchPoint); // 45
	}
}

 

Here it is in action… pretty simple eh! 😉

  

But this touch handler is very primitive, as in if you want to handle multiple concurrent touch points, or special gesture touches, pan, or zoom and so on, then you need to implement a more advanced low level touch handler, something described as here:

https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/effects/touch-tracking/

That way you could simply attach the above TouchEffect just as a normal effect and see the complex touch events in action.

<Grid>
	<skia:SKCanvasView x:Name="SkCanvasView"
		PaintSurface="SkCanvasView_OnPaintSurface" />
		
	<Grid.Effects>
		<tt:TouchEffect Capture="True"
			TouchAction="OnTouchEffectAction" />
	</Grid.Effects>
</Grid>

 

There you go! 😀

Bitmap Image Handling….

Images are pretty crucial when it comes to  2D Graphics, it gives more of added advantage over your design idea.

As of Xamarin.Forms, the conventional the conventional way of loading an image is, either as an Embedded Resource or Platform Specific Resource.

So in SkiaSharp for Xamarin.Forms, provides you SKBitmap or SKImage for handling your image resources. You have few options to load an image, from a data stream, file path and so on.

The most common way in the sense of Xamarin.Forms architecture, you have the option of loading your Images directly from PCL as Embedded Resources, and then convert it to a SKBitmap or SKImage.

string resourceID = "XFSkiaSharpDemo.Resources.xamarinmonkey.png";
Assembly assembly = GetType().GetTypeInfo().Assembly;

SKBitmap skBitmap;

using (Stream stream 
		= assembly.GetManifestResourceStream(resourceID))
using (SKManagedStream skStream
		= new SKManagedStream(stream))
{
	skBitmap = SKBitmap.Decode(skStream);
}

skCanvas.DrawBitmap(skBitmap, 
	SKRect.Create(-50, -50, 100, 100), null);

 

There you have it, we are using the DrawBitmap() method for drawing the image on canvas.

 

But if you have a Xamarin.Forms ImageSource at hand and you need to use in SKCanvas, then you have convert it a Stream object and convert it to SKBitmap, which you could use to manipulate or draw using SkiaSharp on the Canvas. 😉

Image Filters..

Thanks to SkiaSharp you don’t have to manually implement image filters at all, since it packs a pretty cool set of Image Filters out of the box. 😀

Here’s a small sample of a blur image filter implementation…

// built-it blur image Filter
var filter = SKImageFilter.CreateBlur(5, 5);
var skPaint = new SKPaint();
skPaint.ImageFilter = filter;

skCanvas.DrawBitmap(skBitmap, 
	SKRect.Create(-50, -50, 100, 100), null);

 

SKImageFilters is the class that provides the built in filters. 🙂 You attach that object to a SKPaint configuration and draw the Bitmap with it!

 

Keep in mind, there’s a lot more default Image Filters you could play around with! 😉

*drum beat*! 😀

Rendering Animations…

Although Xamarin.Forms packs some pretty decent set of Animations out of the box, we don’t much control over the animation for customization.

But using something like a 2D Rendering Engine, we could create whatever the animation or customization as we wish. SkiaSharp of course is a great option, but that being said, there’s no direct Animation handling available. Because it’s simply a 2D vector rendering engine.

So this means if you want to render some continuous animation with SkiaSharp, you need to handle every single frame of it manually from your code.

So by actual implementation there’s few ways to do this, but the actual underlying idea is to repeatedly render a given set of values on the Canvas, preferably triggered by a continuous timer of sorts.

Stopwatch stopwatch = new Stopwatch();
bool pageIsActive;
float t;
const double cycleTime = 1000; // in milliseconds

private void InitAnimation()
{
	pageIsActive = true;
	stopwatch.Start();

	Device.StartTimer(TimeSpan.FromMilliseconds(33), () =>
	{
		// calculate t for current 
		// tick with regards to cycletime
		t = (float)(stopwatch.Elapsed.TotalMilliseconds
					% cycleTime / cycleTime);
		// invoke redraw on canvas
		SkCanvasView.InvalidateSurface();

		if (!pageIsActive)
		{
			stopwatch.Stop();
		}
		return pageIsActive;
	});
}

 

The above shows you you could create a simple continuous pulse generator relative to milliseconds and execute a continuous animation. In simple terms the Timer is running each 33 milliseconds, calculates a value (t) based on the total elapsed milliseconds on the stopwatch, relative to the cycle time (controls the speed of animation) and repeats. Then calls the SKCanvas redraw. Make sure to call this method on PageAppearing() to start the timer and set the pageIsActive = false on PageDisappearing() to the timer stops.

private void SkCanvasView_OnPaintSurface
	(object sender, SKPaintSurfaceEventArgs e)
{
	... 
	
	// calculate circle radius for this cycle
	float radius = 70 * t;

	// Drawing a Circle Stroke
	using (SKPaint skPaint = new SKPaint())
	{
		skPaint.Style = SKPaintStyle.Stroke;
		skPaint.IsAntialias = true;
		skPaint.Color = SKColors.Red;
		skPaint.StrokeWidth = 10;

		skCanvas.DrawCircle(0, 0, radius, skPaint);
	}
}

 

There as you can see we are drawing the Circle at the given rendering cycle with relative to the generate “t” value at the Timer. So the Circle’s radius will keep on varying from 0 – 70, thus creating the animation effect.

 

Now keep in mind there’s nothing to worry about the rendering performance, since SkaiSharp is a rendering engine. 🙂 You can configure the animation even more faster as you wish, it wouldn’t make much effect on app’s performance! 😉

More Awesome Stuff…

If you want to learn more, check out Xamarin official documentation: https://developer.xamarin.com/guides/skiasharp/

If you need to check out sample code and demos : https://developer.xamarin.com/SkiaSharpFormsDemos/

This presentation’s demo on github…

That’s right, you can get the full demo code I’ve showcased in the presentation up in my github: https://github.com/UdaraAlwis/XFSkiaSharpDemo

I haven’t shared all the demo code I’ve presented in this blog post, but you call find all of the demo code from my git repo above! 🙂

Conclusion…

Yep that’s pretty much it, just get out of here and build something awesome with SkiaSharp! 😉

Share the love! 😀

Cheers!
– Udara Alwis

Yaay! I became a Xamarin Certified Mobile Developer! :D

So finally on 9th of June 2017, I became a Xamarin Certified Mobile Developer. So here’s my experience of the whole Xamarin University, Certification Exam, and some tips and tricks that might help you! 🙂

Well I’ve been using Xamarin Platform for over 2 and half years now, but I never really thought of getting the official Xamarin Certification until recently my boss encouraged me to and financially supported it.

Down the memory lane of my Mobile Development enthusiasm…

So here’s a little sharing of memories down the memory lane and some tips for getting the Xamarin Certification.

I first started off developing mobile apps on Android platform, given my love for Java programming back in the early days. So I self learned Android App Development back in the middle of 1st year of my college using online tutorials and documentation.

Then at the end of 1st year, I was introduced to Windows Phone App development, which I got completely hooked on it, and then Windows Store App Development and so on, where I ended up publishing over 20+ apps to the Microsoft App Store during the next few years.

Next lucky enough I got a mobile developer opportunity at a medium size local company where it was for Xamarin Mobile Development back in 2014 December. 😀

Learning the whole Xamarin Platform by myself, I ended up completing a full fledged mobile app for that project in that company using Xamarin Forms.

Finally in 2015 December, got an overseas opportunity in Singapore for a Xamarin Mobile Developer position, which is where I ended up mastering the Xamarin Platform, Xamarin Android/iOS native development, hacking to push boundaries of the platform and so on and finally living my dream of being a Mobile App Developer. 😀

And that is where I’m currently working at June 2017, enjoying everyday of it while diving in the goodness of Xamarin Mobile Development. 😉


Xamarin University Training and Certification Preparation…

I was lucky enough my company sponsored me for Xamarin University Subscription. Otherwise its about 1000 USD for 1 year subscription or there a new monthly subscription plan with a very reasonable pricing.

Once you have the subscription you get full access for all the incredible learning materials and live lecture sessions in Xamarin University.

Is it worth it?

Now although at this point I already had like 2 years of Xamarin Mobile developement experience, I must admit that I learned way more and strengthened my knowledge on Xamarin top to bottom thanks to Xamarin University. So if you ask me if it’s worth it? at least for the Knowledge? DEFINITELY YES!

Mandatory Sessions

There’s a mandatory list of sessions that you have to complete before taking the exam, you could completely them either by attending the live lecture sessions or taking self-learn sessions (if available). Yes, some of those mandatory sessions doesn’t have the ‘self-learn’ option yet, so you have to attend to a live lecture session and get your attendance marked for it. 🙂

Instructors?

Mark my words, the instructors in Xamarin University are top-notch, and industry experts with a lot of knowledge and experience, there’s no doubt about them. You can ask anything from them regarding the session, even while the session is going on, they are very helpful and friendly, not to mention their great teaching skills. 🙂

Memorizing vs Understanding!

Do not MEMORIZE! just UNDERSTAND the content! The sessions are structured in a way that it helps you to actually understand the content with step by step exercises. I’ve never taken a single note on any of the sessions, nor tried to memorize stuff(although I’m not very good at it either), just followed through sessions and focused well during them. That’s all it takes!

Anything else?

You can take any live lecture session as many times as you wish, until you feel comfortable with the topic. There’s also many extra sessions you could attend to improve your knowledge in Azure, UI Test, Xamarin Android, Xamarin iOS. It’s good to keep in mind that the exam mandatory sessions are mainly about Xamarin Forms cross platform related topics, so you don’t have to worry if you don’t have much in-depth knowledge about native mobile development. 🙂

They also provide you a Study-Guide check-list to go through to make sure you’re prepared for what’s actually required: https://university.xamarin.com/content/certification#study-guide

Once you’ve completed the mandatory sessions, then you become eligible to sit for the certification exam!


Certification Examination!

So the Certificate Exam is a 3 hours, MCQ exam (Multiple Choice Question) which has 150 questions, and you should score over 80% in order to pass the exam.

The questions scope…

The questions are going to be completely based on the mandatory sessions in Xamarin University. Heavily focused on the Xamarin.Forms cross platform related topics. Personally I did not get any questions that are out of the scope.

So how were the questions…

If you’ve got a solid knowledge on the mandatory sessions, then you have nothing to worry about. Not keep this in mind, about 40% of the questions are straight and easy, but the rest are not going to be hard, but tricky, meaning it’s going to be little bit twisted, so you need to pay good attention to the details in each question before you pick the answer. 😉

Understand the content in the sessions, not memorize!

Basically you won’t be able to make it through the exam if you’re just trying to ‘memorize’ everything in your head, you need to have a ‘good understanding’ of the session content, in order to answer the tricky 60% of the questions.

After the exam?

Once you finish the exam, you get the results immediately. 😉 Then its time to PARRTTAAYYY!!! 😀

Xamarin University and Certification benefits!

First of all the incredible amount of knowledge and experience you gain in the whole process of Xamairn University and the Certification is priceless.

Not to mention the global recognition as Xamarin Certified Mobile Developer, having the official certificate directly validates you as someone who actually knows your way around Xamarin-stuff. Although it does not prove you as an ‘expert’, which is totally dependent on your personal industry experience.

Access to Xamarin DevConnect portal, to showcase your portfolio and connect with fellow developers.

There are few other awesome benefits you get according to Xamarin official site as follows. Certification is valid for 1 year from the date you have passed the exam. Certifications can be verified on our public Xamarin Certified Developers page.

Receive a badge, fun Xamarin swag, and an invitation to join the official Xamarin Certified Developers community on LinkedIn.

Cool, so what do I get to show off?

Except for the massive amount of knowledge and experience I gained from the Xamarin University Sessions and Training, here are some other show-off stuff I got after being certified.

So brace yourselves for some self promotional bragging! 😛

Xamarin Certified Developer Verification Online:

https://university.xamarin.com/certification?q=Udara@xamariners.com#verify

You get a link that can be shared online for the verification of your Certification status. This is the source you could include in your LinkedIn or personal portfolio for the verification.

Xamarin University Profile Badge: 

Once you get the certification, your Xamarin University profile gets updated as such.

Xamarin Certified Developer Certification (soft copy): 

You actually get a PDF version of your certification (here is a screenshot of it).

Bunch of Xamarin Certified Developer badge Images (HD):

Then you get a whole bunch of Certified Mobile Developer badges in low, mid and high resolution for you to share on any of your websites or portfolios. 🙂

Xamarin DevConnect Profile:

You get access to Xamarin DevConnect, the official Xamarin Certified Developer portal from Xamarin, where you can publish your portfolio, connect with fellow certified developers from all over the world, and open up yourself for new opportunities.

https://devconnect.xamarin.com/profile/389


Well that’s it all I got for now… 😀

Although some claim that you get kind of a Xamarin souvenir trophy and a goodie bag by mail, but I’m yet to get any of that. lol. *fingers cross* 😛

So If anyone needs any help or clarifications regarding Xamarin Certification, I’m more than happy to help, drop me a mail or comment down in the post. 🙂

To get started:  https://www.xamarin.com/university

Good luck everyone with your Xamarin Certification! 🙂

Cheers!

The three awesome tools by Xamarin! Workbooks|Profiler|Inspector

Last Friday (20th January, 2017) I did a tech talk at Singapore Mobile .Net Developers  meetup, under the topic “The three Awesome tools by Xamarin – Workbooks/Inspector/Profiler”!

So this blog post is a recap of the stuff I talked about! 😉

First of all here are the slides.

Here we go, the recap…

The three awesome tools by Xamarin

slide1

Last few months Xamarin has been busy releasing a lot of new updates and tools for us Developers, specially since the acquisition by Microsoft, they have been exponentially improving their platform and eco-system. 😀

So today I thought of picking up three awesome tool that has been released by Xamarin last few months, which are going to be extremely useful for Xamarin Mobile Development.

slide3

So to start off with…

Xamarin Workbooks!

slide4

Why do we need Xamarin Workbooks you asked? 😮

slide5

Now Imagine you’re someone who’s trying to learn Xamarin Mobile development or may be even C# dot net development? 😀

Could be someone trying to teach someone Xamarin or dot net or may be you’re trying to demo some awesome piece of code you implemented at a presentation, along with some documentation? 😉

Or simply you’re just trying out an experimenting some piece of code before you do some actual implementation in your actual project code?

Now in all of these stations, you have to open up your IDE, open up the documentations or presentations may be and most annoyingly you have to continuously switch in between them at all times. Not to mention having to recompile and run your code at the same time you switch back and forth. 😮

Oh well what a hassle is that?

To get rid of all that hassle, we have Xamarin Workbooks now! 😉

slide6

A perfect blend of documentation and code and immediate live preview results.

Xamarin Workbooks, is a prefect solution for experimenting with Xamarin and dot net code implementations and even as a learning tool for exploring code snippets and various kinds of implementations in Xamarin and dot net.

Perfect for creating teaching guides with a sweet side by side integration of code and documentation. Whenever you create or open up a Workbook, it creates a Sandbox environment for you to do your stuff, so you could accomplish your documentation aspect and coding aspect in one single place. 😉

slide7

So workbooks packs a bunch of awesome features, such as full fledged code editor with Roslyn IntelliSense, which has similar syntax coloring just like in Visual Studio. It has in-line compiler diagnostics support as well.

Attached with a rich text editor for you to add side by side code and documentation on the go. You could also easily search and add nuget packages as you go, just like you would do in Visual Studio, and instantly preview the results in console, or any mobile emulators as you have chosen.

You can easily save an share your workbooks with anyone and they could open it up and try out as they wish.

slide12

So Xamarin Workbooks supports dot net console/WPF implementations, Xamarin Android/iOS mobile development and even Xamarin Mac development scenarios. How cool is that eh! 😉

Xamarin Profiler!

slide14

Why do we need Xamarin Profiler you asked? 😮

slide15

Now as mobile developers we need to make sure we are giving a smooth intuitive user experience for our beloved users. So in order to do that, we need to make sure our app is fully optimized for the memory usage, process usage and various resource usage without causing any excessive lags or crashes.

And even some times during the development we come across these mysterious crashes without even hitting any debug points where we need more than just the debug logs to figure out what’s causing those mysterious crashes. 😮

Another aspect is that as mobile developers we need to always focus on the over flow of the resource usage in our application at run time so that we could do the necessary improvements in our code to reduce any excessive resource usage.

Something very important to keep in mind is that when we are dealing with Xamarin Mobile Development, we have to deal with both the Xamarin dot net environment and the Native environment at run time. In that case the available native profilers we have for android and ios can not help to analyze our xamarin dot net environment. So we need something better than just native profilers for our Xamarin Mobile applications.

As a solution for all those scenarios, we have Xamarin Profiler now! 😉

slide16

Xamarin Profiler is a tool that seamlessly integrated with your Xamarin Application, collects and displays information to analyze your application at run time.

This can easily be used for finding memory leaks, resolving performance issues, monitoring resource usage at the run time, and more over to polish up your mobile app before delivering to your users.

Fun fact, is that this tool is actually based on the Mono log profiler which is a command line profiler that they previously used to analyze Mono run time applications. So what they have done is, they’ve added a bunch of improvements to it and added this intuitive UI on top of it deliver this analytical information for us developers! 😀

slide17

So there are three key features or as they call them “instruments” that’s packed along with Xamarin Profiler. 😀

Allocations instrument is used for analyzing  the memory usage of your application at any given point of time at the run time.

Time Profiler instrument is used for tracking app performance, whereas it allows you to see which function took the longest to finish its execution.

Then we have the Cycles instrument, which provides you details with memory cycles occurred at the run time. May be I should explain it a bit further…

Memory Cycles: When you’re dealing with Xamarin Mobile applications, we have this environment of managed dot net environment and the un-managed native environment, sometimes due to our bad code a bunch of objects in the memory creates references to them selves in a circular manner, which could happen inside the dot net environment or most of the time in between the dot net and the un-managed environment. So in situations like that, the Garbage collector finds it hard to break through those circular references and release those objects, which results in those objects presisting in memory and the memory usage is only going to get increased. 🙂

So thanks to Xamarin Inspector we could easily identify those memory cycles and do the necessary changes in our code to eliminate them 😉

slide18

It also packs up these additional features allowing us to further drill down into details to analyze our application run time.

Xamarin Inspector!

slide20

Why do we need Xamarin Profiler you asked? 😮

slide21

As Mobile Developers we need to make sure we deliver a beautiful pixel perfect design for our end users, and specially according to my UX lead he’s going to haunt me in my nightmares if I don’t deliver a pixel perfect UI implementation. 😀

So we always have to do the tiny changes in padding or the height or the width or may be a tiny hex value in the color and so on, whereas every time we do a change we need to recompile the project and run.

And then even if you get the app to run, you still have to go navigate to the page that you just made the changes to, which takes a lot of time.

Now I’m aware of the existence of Xamarin Forms Previewer, but if you had already tried it out, we are well aware there’s a whole bunch of bugs and issues with it when it comes to complex UI designs, which has a whole bunch of custom renderers.

So for a solution to all the above scenarios, Xamarin has given us this awesome tool, Xamarin Inspector! 😀

slide22

An awesome tool that allows you to debug and analyze or modify your application UI at run time without having to recompile your code. 😉

Something really cool about this tool is that it gives this awesome exploded 3D layers view of your application UI. Which makes it very easy to analyze the rendered layers and get rid of any extra layers to improve performance.

slide23

Xamarin Inspector has two main features, first is the REPL access. REPL stands for Read, Evaluate, Print and Loop, which allows you to inject code to your application in real time.

Then the Visual Inspector allows you to interact with your UI hierarchy in real time in an intuitive 3D view.

So that you could make necessary changes to your UI in real time and see it instantly rendered on your emulator. 😉

Something very important to keep in mind is that, with the latest update for this tool, they are providing you direct Xamarin Forms support, so no longer you have to deal with the native-rendered properties, you could easily make changes to your Xamarin Forms properties on the fly.

Conclusion

slide25

Yep that’s it fellas! now get out there and build something awesome with Xamarin! 😀

Cheers!

-Udara Alwis, out! 😛

So I gave a Tech Talk at Dot Net Developers Meetup, Singapore hosted by Microsoft…

Yeei! 😀 I got an awesome opportunity present a tech talk at Dot Net Developers Meetup in Singapore which was hosted by Microsoft. This happened to be my first ever Presentation on Xamarin, and yeah it was totally awesome. A great enthusiastic crowd and everything went pretty well.. 🙂

Thank you so much for the Organizers and Microsoft for this incredible opportunity, and I’m truly humbled by it.

There I spoke about Xamarin and Xamarin Forms, Xamarin UI Rendering process, Overriding this process through Custom Renderers, and important facts to keep in mind when implementing Custom Renderers in Xamarin Forms.

So I thought of putting out a small article on the Summary of this tech talk on my blog. 😀

Xamarin Forms Custom Renderers for the Rescue…

Here’s the slideshow I used during this talk…

Xamarin is…

Xamarin is truly a great platform. It let’s you create mobile applications using C# dot net having full Native Performance as well as Looks and Feels of each Native Platform.

Xamarin Forms Custom Renderers for the Rescue.004

As you can see in the diagram, thanks to Xamarin now we can maintain the same code base across all three mobile platforms, having the individual native UI implementation, which allows us to maintain up to about 70% percent shared codebase. So yeah its all Great.

Xamarin Forms is…

Xamarin Forms, in one single word, is awesome! Its more like the cross platform extension of Xamarin this is the component which brings to life of the concept, Write once, Run Everywhere, and not Suck allowing us to share the UI code layer among three platforms. So you no longer need to implement the UI separately for each platform.

Xamarin Forms Custom Renderers for the Rescue.005

Xamarin and Xamarin Forms ?

Some people are confused about these differentiation between Xamarin and Xamarin Forms, let me put it this way…

Xamarin Forms Custom Renderers for the Rescue.006

Xamarin Forms is more like the true cross platform extention of Xamarin. Where as Xamarin Forms provides us a unified UI Layer which has all the common UI controls (Layouts, Labels, TextBoxes, Buttons, etc…) of all three mobile platforms, with almost every single common property of those controls.

Still Confused ? Let me explain…

Xamarin Forms Custom Renderers for the Rescue.007

In your left hand side you can see the Native Xamarin architecture where you share the back-end code base, but you have to implement the UI separately for each platoform, allowing us to share upto 70-80% of code base.

Where as in Xamarin Forms you can share almost upto 100% of the code base across all three platforms with the Shared UI Layer.

A little Story about a fresh Xamarin Forms developer…

There’s this developer who started developing an application with Xamarin forms, where he’s given all the UI sketches and so on.

Xamarin Forms Custom Renderers for the Rescue.008

So he start off with default nice and simple controls in Xamarin Forms and manages to implement the basic UI design of the app. Then he slowly gets into complex UI designs implementations…

So he starts going through all the available properties in these Xamarin Forms Controls, and begins to wonder where are all the properties that he needs to be using in order to customize the app accordingly to the complex design.

So he looks up and down, here and there, wondering where did all the properties go?

Oh boy, he’s in trouble, isn’t he… He realise Xamarin Forms UI controls has limited set of properties for customization, and its very hard to do complex customization in these controls.

Any Solutions ?

Any solutions ? Well he could always go back to native development, but its late for it now, and it’ll put him through a lot of trouble for sure, having to implement in three platforms.

Now that’s where Xamarin Forms Custom Renderers comes in for the rescue, let me explain.

Xamarin Forms Custom Renderers for the Rescue.010

Xamarin Forms UI Rendering process…

Each and every UI Control in Xamarin Forms has it’s own Native Renderer which renders and maps its Properties and Behaviours to the Native Control level.

So yeah behold the Magic of Xamarin Forms, this happens accordingly to the Native Platforms. This is why we get the Native look and feel and performance with Xamarin Forms.

Xamarin Forms Custom Renderers for the Rescue.011

Take a look at the Diagram here it shows how the default texbox UI Control of Xamarin Forms, which is called “Entry” control gets rendered down to the Native level through the Renderers. Now focus down through the iOS rendering, where the Entry control gets rendered down to the native UITextField control. And on Android and Windows Phone, EditText and UserControl respectively.

Overriding this Rendering Process ?

Xamarin has allowed us to access this Rendering process, which in return allows us to Override this default process and use it for our own requirements.

Xamarin Forms Custom Renderers for the Rescue.012

So by accessing this process we can customize all kinds of properties and behaviours of the Xamarin Forms controls, in each platform according to our needs.

Xamarin Forms Custom Renderers…

So in order to access this rendering process we need to create Custom Renderers of our own by sub classing the base Renderers Xamarin provides. Thereby it allows us to access and modify the native level properties and behaviours of the Xamarin Forms Controls.

Xamarin Forms Custom Renderers for the Rescue.013

Take a look at the Diagram above, that’s how Custom Renderers gets involved in the Rendering process, where as the Xamarin Forms Entry control goes through the Custom Renderer and down to the base renderer, where we control and modify its properties and behaviours in our Custom Renderer as we need.

How to create Xamarin Forms Custom Renderers ?

Just 3 simple steps…

  1. First you create a Custom Control by subclassing the default Xamarin Forms Control that you need to create a Custom Renderer for.
  2. Second you consume that subclassed Custom Control in your Xamarin Forms application.
  3. Thirdly and finally, you implement the Custom Renderer in the Native levels project.

Yeah how hard could it be, just three simple steps! 😉

Here’s a Simple Custom Renderer Demo on the house…

Check out the live demo Custom Renderer I implemented during this presentation on my Github from below, https://github.com/UdaraAlwis/XFCircleCornersButtonControlDemo

Important facts to consider WHEN implementing Custom Renderers…

So here are some important facts to keep in mind when you implement Custom Renderers in Xamarin Forms, so that you get a good understanding about how to implement a custom renderer and what to keep in mind…

1. Always Export your Custom Renderers…

Whenever you create a custom renderer you need to Export it and register it, otherwise Xamarin would not recognise your Custom Renderer and it will go ahead with the default base class Renderer for your Custom Control.

Capture

2. Overriding the OnElementChanged Method…

Whenever a Custom Renderer is being execute, the first method it fires is the OnElementChanged() method.

This method gets called when the Rendering process starts for the custom control, which allows us the opportunity to to tap into the native properties and behaviours and modify them as we wish by overriding this method.

Also something to keep in mind this method consumes an important parameter, ElementChangedEventArgs which contains two important Properties.

  1. The OldElement property represents the Xamarin Forms level Control this renderer was attached to (previously attached to) and
  2. The NewElement property represents the Xamarin Forms level Control this renderer is currently attached to, its more of a reference.

So if you are using any Event Handlers in your Custom Renderer, you have to keep an eye out for these two properties in order to Subscribe and Unsubscribe accordingly to prevent memory leaks.

Capture1

3. Control vs Element Property…

If you think about it, Custom Renderer is more like a middle guy, in between Xamarin Forms level Control and the Native level Control, where as it’s got hooks for both levels.

So those hooks are represented by these two important properties, Control and Element.

Element property, it holds a reference to the Xamarin.Forms control that’s being rendered, so you could use this property to access anything on the Xamarin Forms level of the custom control, such as Text, WidthRequest, HeightRequest and so on.

Control property holds a reference to the Native Control being used of the Custom Control. So using this property you can straight away add your native customisations and behaviours to the Rendering Control.

3. Overriding the whole Native Control ?

What if you want to get rid of the default Native Control associated with your Custom Renderer ? Create your own Native Control and use it for your Custom Control ?

As an example You need to have a TextBox with an underneath shadow, in iOS you can’t do this with the default native UITextView, so one way to do it is by adding another UIView along with the UITextView, where as you merge two native views together to form one View.

So for instances like that, you could use the SetNativeControl() method, and pass in your custom native view, which will get rid of the default native view and override it with your custom native view.

But you have to keep in mind something very important, hence you are flushing away the default native control, you have to handle all the Behaviours (Events) of your own Native Control manually by yourself and map it back and forth with the Xamarin Forms level.

4. Creating your own Base Renderer…

For every Xamarin Forms Control, there is a Base Renderer, that maps it to the Native Level and we use those Base Renderers all the time such as Button Renderer, Label Renderer and so on.

Now what if you wanted to create your own Base Renderer ? Let’s say you are creating a total complex Custom Control by yourself, and you need to have your own Renderer for it?

YES! it is possible, you just simply have to derive your Base Renderer from the generic ViewRenderer<?,?> where as you have to pass in your Custom Renderer type name and the associating Native Control type name for the renderer.

Well actually Xamarin doesn’t really recommend this, there some instance that you need to move towards this approach.

Let me Share some Wisdom…

Xamarin Forms Custom Renderers for the Rescue.022

Here’s something interesting I really want share with your all is that, Xamarin doesn’t really require in depth Mobile Development knowledge but it is very beneficial to have some, specially in scenarios like these Custom Renderer implementation. The more you are aware of the Native development, the more advantages for you.

So if you are planning to move towards Xamarin mobile development, I would suggest you take a little look at native development as well… Which will prepare you better for your Xamarin Mobile Development journey.

Important facts to consider BEFORE implementing Custom Renderers…

Earlier I mentioned about the facts that you need to keep in mind when you implement Custom Renderers, now let’s see what are the facts you need to focus BEFORE you decide to implement Custom Renderers in your application.

 

1. Think twice…

You need to think twice before you move on towards Custom Renderer implementation for your Application. Once you get familiar with Custom Renderer implementation, you get very tempted to go for custom renderers all the time even for the simplest requirement, but trust me it is not a good practice at all.

Why I say this is because, and untold truth about Custom Renderers is that, they are a little process intensive.

Therefore it’s wise to first of all explore all the possible solutions you could come up with from Xamarin Forms level it self to solve your requirement. So do not over-use Custom Renderers just because of the ease of development.

You could also try out other alternatives such as,

  1. Xamarin Forms Controls sub-classing and forming Custom Control (by merging multiple Controls to create a new Control).
  2. Xamarin Forms Effects (which is almost like Custom Renderers but simplified).

 

2. Re-usability…

Whenever you decide to implement a Custom Renderer You need to pay attention to the reusability of it. Make sure to implement it in a way its reusable as much as possible.

When ever you implement Custom Renderers, don’t only focus on the current implementation, think ahead and implement all the possible needs in one go, without implementing custom renderers for every single need from one type of control.

Since Custom renderers are process intensive it very important to focus on reusability.

3. Mapping of Xamarin Forms -> Native Level…

Last but not least before you implement your Custom Renderer always make sure to take a look down through your Rendering Hierarchy…

Xamarin Forms Custom Renderers for the Rescue.026

Look at the available Properties and Behaviours down to the Native control and see whether it actually fulfils your requirements, in all three platforms (Android, iOS, Windows Phone). That way you will have a better idea on how to implement the Custom renderer more efficiently.

Conclusion…

Xamarin Forms Custom Renderers for the Rescue.028

Custom Renderers plays an extremely important role in Xamarin Forms development. In my opinion it’s more like the Magic behind the whole Xamarin Forms Awesomeness.

Don’t be scared of Custom Renderer’s because they are here for your rescue.

Also finally make sure to keep in mind all the important tid bits I discussed today, so it will help you implement custom renderers more efficiently and effectively. 🙂

AAAANND THAT BROUGHT US TO THE END OF THE PRESENTATION! Hope this was helpful for anyone missed this session and keep in touch everyone! 😀

Once again Thanks for the Organisers for organising this event and Microsoft for hosting. As well as the enthusiastic crowd. 🙂

– Udara Alwis
CODENAME: [ÇøŋfuzëРSøurcëÇødë]

https://www.linkedin.com/in/udaraalwis

https://www.facebook.com/confuzed.sourcecode

Nǐ hǎo ma! fellow awesome developers ! ;)

Woot Woot! I’m back fellas! Yeah, it’s been a while since I have last been in this blog-sphere…

To keep it short, I was extremely busy last few months due to some awesome career related changes in my life. 😀

Probably you are wondering what’s with the “Nǐ hǎo ma!”, yeah that’s how you say hello! in Chinese and I have moved to Singapore fellas!
(PS – I’m self learning Chinese these days with the help of some colleagues here lol 😛 )

23349203364_8bb092e6e9_o

Flickr Album of some sceneries in Singapore – https://www.flickr.com/photos/confuzed-source-code/albums/72157660613627064

Yep, that’s right. Last November, I got recruited by a company in Singapore as a Xamarin Mobile Engineer, so I moved to Singapore from Sri Lanka, and settled down there. 😉
Hence I couldn’t keep in touch with my blog, but now things are completely settling down with my new life in Singapore, I have finally managed to get back on my blog-sphere.

I have been doing some really interesting and challenging work at my new company related to Xamarin, so I’m looking forward to share a lot of cool stuff with you guys in the coming weeks.

So let’s get this going fellow Awesome developers! 😀

Cheers! 😉

Stay Awesome! 😀

Winning a Special Award at ICTA e-Swabhimani Competition 2014

Oh yeah ! xD One of the most awesome moments in my entire life was when they announced… 😀

“ICTA e-Swabhimani competition’s e-Entertainment and Games section SPECIAL AWARD goes to Sri Lankan Newspaper Cartoons project by Udara Alwis ! “

OMG ! 😀 that moment of unexpectancy, thinking that I would have no chance among the big companies I competed with during the competition…

WP_20141105_22_50_59_Pro

WOHOOOOOOOOO ! 😀 Thank you very much Information and Communication Technology Agency of Sri Lanka (ICTA) and yes it was truly a wonderful event ! 😀

And this was me presenting on my project ‘Sri Lankan Newspaper Cartoons‘ in front of all the judges and competing Corporate giants… as a Finalist at ICTA e-Swabhimani Competition 2014 ! 😀

Link to Sri Lankan Newspaper Cartoons project –
http://lkpapercartoons.confuzed-sourcecode.com/

LogoBanner

 

You can Check out the Official Fan page of the Project here –
https://www.facebook.com/SriLankanNewspaperCartoonsProject

Slide1

 

Some Moments to Share…

Receiving the Special Award at ICTA e-Swabhimani all island competition for my Sri Lankan Newspaper Cartoons project ! 🙂

10441485_10152525533831977_6344200139861072666_n

 

That moment when you make your own Mother proud… :’)  !  Oh yeah so much of Amma points 😛

1907292_10152525535366977_2791329620654159984_n

Among the Winners at ICTA e-Swabhimani all island Competition… 🙂

10644963_10152525536016977_8166573454344299038_n

Sometimes you just gotta believe in yourself and follow your Dreams by yourself… despite of what everyone else tells you…
And someday you will end up there among the giants… 😉

WP_20141105_21_55_26_Pro

 

Some Blog posts regarding my project, Sri Lankan Newspaper Cartoons,

https://theconfuzedsourcecode.wordpress.com/2013/08/18/sri-lanka-newspaper-cartoons-gallery/

https://theconfuzedsourcecode.wordpress.com/2013/08/18/sri-lankan-cartoons/

https://theconfuzedsourcecode.wordpress.com/2014/11/03/welcome-to-confuzed-sourcecode-tech-innovations/

#SriLankanNewspaperCartoons   #SriLanka  #Newspaper   #Cartoon   #NewspaperCartoons  #ICTA

Final Presentation at ICTA e-Swabhimani Competition 2014

And this was me presenting on my project ‘Sri Lankan Newspaper Cartoons‘ in front of all the judges and competing Corporate giants…
as a Finalist at ICTA e-Swabhimani Competition 2014 ! 😀

And yes I won the Special Award for e-Entertainment category ^_^ !

Visit the Project Website here –
http://lkpapercartoons.confuzed-sourcecode.com/

You can Check out the Official Fan page of the Project here –
https://www.facebook.com/SriLankanNewspaperCartoonsProject

#ICTA #eSwabhimani #SriLanka #Achievements #SpecialAward #Moments #SriLankanNewspaperCartoons #Newspaper #Cartoon #NewspaperCartoons

The amazing journey I had as a Microsoft Student Partner..

I always loved building things, and solving problems, which is one of the reasons why I got into Software Development in my early higher studies. I would always look at any problem or requirement, and try to come up with a solution to fix them, with my passion for technology, even if I’m not able to solve it I would seek out and self-learn the knowledge and skills required.

I remember back in the day, around the end of my 1st year in University, when I was a self-taught Java code junkie, building cool little scripts, software tools and apps while sharing them among my friends and fellow students for fun, well for the sheer joy of building things and fixing problems. 😉

Around the same time, I stumbled into a senior fellow, Nisal “Cheezy”, who’d later become a good friend of mine, who heard of my work around the campus and introduced me into the world of Microsoft. So I was a bit skeptical in the beginning, given my inspiration towards Open Source Software movement where I started off of my enthusiasm.

So I attended few student work shops hosted by Microsoft Sri Lanka and I was stunned, well you could even say I was hooked. The next thing I know, I self taught .NET framework and started building things off of C#, given the amount of free tools and support they have for the University students those days. 😀

Since then I went down a journey that would inspire my whole career, from being an enthusiastic college kid to a Software Engineering professional. So here’s me sharing a bit of that journey to mark a remarkable turning point of my life…

One of the first few workshops for Students I attended was at the Microsoft Sri Lanka office, which was led by Mr. Wellington, Uditha and Malin, this was around May, 2012 as I recall…

Those workshops and demonstrations were truly incredible learning opportunities I’ve ever had, where the presenters and instructors were well experienced and very welcoming of us.

The Microsoft App Sunday was a workshop and a full day hackathon program that was hosted by Microsoft Sri Lanka, around October, 2012, which I believe they continued on for several months. This was really fun!

Oh that guy in Blue T-Shirt on the right side photo is me! xD

We were hand picked by the Student Ambassadors at the time, from different universities and we’d spend our whole Sunday at the Microsoft Sri Lanka office, with free food, snacks and drinks, building awesome Windows Phone and Windows 8 Store Apps. 😀

Early 2013 I got involved in organizing these Microsoft Student workshops in my own University as well… These were the days of Windows 8 hype!

APIIT Windows 8 App Fest was one of those initiatives that I was part of, sharing the awesomeness of latest Microsoft tech among fellow students…

Microsoft Student Champs is something that definitely needs mentioning here, where Microsoft Sri Lanka office hosted these monthly meetups for University students for free, to come together as a student community, and share knowledge and experience, gaining insights from industry experts.

Microsoft Student Champs: https://www.facebook.com/studentchamps

That’s the little meeting room that these monthly meetups were held, so much wonderful memories right here, lots of friendships formed and connections across universities all over Sri Lanka.

Even I got the opportunity to present some of my self taught expertise in Windows Phone App development… 😀

Udara Aliws presenting at Microsoft Student Champs meeting in Sri Lanka

Oh yeah goodie bags from Microsoft for coming forward and presenting was my all times favorites! 😉 lol

This was an incredible opportunity for us as students to share our knowledge and expertise with the rest of the student community and improve our presentation skills!

Then next big achievement was, around June 2013, when I was appointed for a Microsoft Student ambassadorship under the Student Partnership program, in recognition of my contribution to the student community as a fellow student.

News article: https://www.readme.lk/sri-lankan-msps-appointed/

That right there are some of my fellow Student Partners from my University at the time. Good friends, good times!

Microsoft Student Champs Ambassadors Sri Lanka APIIT 2012
Microsoft Student Champs Sri Lanka Monthly Meeting 2013

This wonderful opportunity only propelled me further sharing knowledge and experience where I continued on my passionate journey. One of those memorable events was Infotel 2013 where we got to volunteer for the Microsoft stall with our expertise of Windows Phone!

This was an awesome event, we as students had quite a lot of fun, and had a lot networking opportunities showcasing our skills and passion.

One of the best things ever happened to me was, being inspired to build over 30 Windows Phone Apps and published them on Microsoft Store, gaining over 160,000 users across the world… 😀

Not only that, I even managed to build a whole bunch of Windows Store Apps for Windows 8 as well. My Windows 8 Store App Development Projects : https://theconfuzedsourcecode.wordpress.com/2013/11/11/my-windows-8-store-app-development-projects/

This is something I really enjoyed connecting a worldwide audience through the Apps that you have built by yourself, knowing that out there people are using stuff that you’ve built!

Well my official Microsoft Student Partnership came to an end in mid 2014, since I graduated from my University. But all in all, this entire journey had a massive effect in my Software Engineering career. I’ve gained so much knowledge and expertise thanks to the Microsoft Student Champs initiative, while making a whole bunch of friends and wonderful memories.

So once again thank you Microsoft for this incredible opportunity, and for Mr. Wellington who lead this entire program during the time. This is one of the most remarkable opportunities I had ever stumbled upon as a Student, for that I will forever be grateful, and I hope you guys keep on inspiring many more students like my myself. Cheers!