Custom Switch in Xamarin Forms

Xamarin Forms is a wonderful ecosystem to develop cross platform mobile applications.

Like any platforms, it has limitations too, but yeah there are work arounds. At times you simply can contribute to the awesome “Open Source Xamarin Forms”

Today we will be discussing a small problem I faced in one of our projects, where Xamarin Forms Switch control fires “Toggled” event both when changed by user or programmatically. This was not ideal for our requirements.

So I planned to create a Custom Switch over the Original Switch.

Warning: This work around might not be the best way to do this.

To get started create a Class File, in my case “CustomSwitch”, inherit it from Switch class of Xamarin Forms.

We will create a IsCustomToggled property (which is Bindable Property), to use instead of IsToggled and CustomToggled instead of Toggled event.

Once we reach the constructor, we subscribe to the original Toggled event with our own function.

Also whenever IsCustomToggled is changed in code / program, we will Unsubscribe before setting original IsToggled, and then subscribe back to the event.

The CustomToggled event has CustomToggledEventArgs which contain the new value for switch and an bool “isUser” for indicating whether the action was result of user interaction or code change.

 

Once the Custom Switch is ready, the usage at any place in project is straight forward,

from Xaml

 

Samples and CustomSwitch available at GitHub

Hope this helps someone with same issue, in case of any queries do drop a mail to muhaymin at fantacode com where I am available Xamarin Consulting  or use the comment section below.

 

 

Upgrading PCL Xamarin Forms Project to .NET Standard Like a Boss

Sorry readers, running own company possess great challenges, so didn’t do justice to my blog, and when I get free time I use it for sleeping :D.

Recently I had to port our existing Xamarin.Forms Project from PCL to .NET Standard.

It’s not a simple Xamarin Forms project, for upgrading simple projects, we have various blog post covering those. I am taking about Xamarin.Forms project of very large scale (around 100k Lines of Code, more than 500 Views &ViewModels,  multiple custom renderes and around 90+ Nuget Libraries).

So all the libraries we used didn’t have support for .NET Standard. So we have multiple requirements here

1. Upgrade our PCL without affecting Git History

2. Keep using Libraries which don’t have .NET Standard support yet.

3. Make sure that your Resx file works as expected. (This I am still experimenting, will be sharing findings).

So the first step you have to make sure is take a copy of your working project in current state and keep it somewhere safe.

If you use git / version control, create a branch and let’s start tinkering with the project. Steps are pretty straight forward.

1. Unload your PCL project (right click -> unload), and start editing it (right -> click edit), VS Mac users, just use Visual Studio code, it’s straight forward.

2. You have to delete everything in the .csproj and insert


So in .NETStandard approach, there is no packages.config. References included in .csproj So you have to move all the stuff in packages.config to your .csproj.

In my case manually changing the to the new format was time consuming for 90+ Nuget Reference I had, so I wrote a simple C# Console application to make my life easier, sharing it here 😀

3. Delete AssemblyInfo.cs, these informations will be in .csproj and packages.config (also in csproj via PackageReference)

4. Basically Reload the project, you are ready to go. But there is catch if your project contains libraries which don’t have .NetStandard.

So we will need to add FallBack criteria for Nuget restores.

Under Property Group add this line (based on you requirements of which previous PCL profile do you want restores to based on)

Other issues you may face is that if you have any references to Microsoft.Bcl.Build nugets in any of your projects (Platform Specific and the new .NET Standard), remove those references.

To avoid possible issues, it is always better to remove the existing PCL reference from Platform Specific Projects, and adding it again.

Points to take care for avoiding potential crashes.

  • If  you are were using Embedded Resources in your PCL project, you have to mark the Build actions again. Otherwise those resources wont load.
  • If you are using Resx for localization, it’s always best to remove the current file (ofcourse take a backup), add one again with same name and replace contents.

Before Building, clean all bin/obj folders, Rebuild the project with fingers crossed :D.

If you face any issue please don’t hesitate to contact me or I can help you with this, Just mail to muhaymin at fantacode dot com

Do share your experiences.

References:

How to Convert PCL Library to NET Standard and Keep Git History – James Montemagno

 

Google Place Picker Plugin for Xamarin Projects

It has been long since I have updated my blog, here is a new post for Xamarin community 🙂

You might have come across different needs for selecting location in your apps, and might have resorted of developing Custom Renderer in case of Xamarin.Forms app.

I have developed an open source plugin for Xamarin to make this process easier. If you are interested in helping me out to extend the plugin, you can start contributing here: https://github.com/muhaym/crossplacepicker

One line of code, you will get Google Place Picker in your application.

Let’s get into step:

Step 1: Install Nuget to all projects in solutions (ie. in Shared PCL and Platform Specific projects)

https://www.nuget.org/packages/Fantacode.Plugin.CrossPlacePicker/

Step 2: Sign up for Google Maps Key at https://developers.google.com/places/android-api/signup

Step 3:

Follow Platform setup guide from

https://github.com/muhaym/crossplacepicker#important-permission-and-setup-information

Step 4:

Wherever you require place picker, use

If you want to set initial map screen to specific bounds, use

If you face any issues, comment here, or in issues tracker at github https://github.com/muhaym/crossplacepicker/issues

Sample for this plugin used in and Xamarin.Forms project can be found here

https://github.com/muhaym/CrossPlacePicker/tree/master/samples/PlacePickerForms

 

Getting Started with Twitter Fabric – Digits in Xamarin.Android

Twitter have some awesome tools for saving developers time and boosting productivity. One such tool is Twitter Fabric. Fabric is a collection of tools like Crashlytics (Crash Reporting), Mobile Analytics, Digits and much more.

Sadly, their official SDK’s are not yet available for Xamarin, still, there is a Xamarin binding which works well. Thanks to Michel Moreira for this binding.

This binding is available as Nuget Package, so getting started with this plugin is so easy.

Steps to integrate Digits to your Xamarin.Android app.

Step 1: Get a Fabric Account (https://fabric.io)

Step 2: Sadly, for getting API Keys, you need Android studio. So make sure you have Android Studio Installed (just for the sake of API keys).

Step 3: In Android Studio, select Plugins-> Browse Repositories -> Search for Fabric Plugin, Install it, Restart the IDE.

Step 4: Start a Blank New Project with the name Intended for your Xamarin.Android project.

Step 5: Click on Fabric Icon in Android Studio, Login to Fabric with your account and select Digits from the kits listed.

Step 6: Create Digits Account, and get the API keys obtained from AndroidManifest.xml file and MainActivity.java.

Step 7: Build the project in Android Studio. Once the app is built from Android Studio, your app gets listed in Fabric Dashboard where you can customize the One Time Password message, and get all they API keys.

Step 8: Enough with Android Studio (make sure you copy the keys from AndroidManifest.xml and MainActivity.java

AndroidManifest.xml

<meta-data
android:name=”io.fabric.ApiKey”
android:value=”your-key-here”
/>

MainActivity.java

Step 9: Back to our awesome Xamarin, either in Visual Studio or Xamarin Studio. (I use VS)

Step 10: Open your project, Right Click your project in Solution Explorer and Select Manage Nuget Package.

Step 11: Search for Digits by Michel Moreira, and Install the package.

Step 12: Open your activity, in which you want Digits Authentication (in my case MainActivity.cs)

Step 13:  Paste the TWITTER_KEY and TWITTER_SECRET TO your MainActivity.cs

Also, paste the meta data information to AndroidManifest.xml under application node.

  <application android:label=”Fabric_Demo”>
<meta-data
android:name=”io.fabric.ApiKey”
android:value=”your-key-here”
/>
</application>

Step 14:  Initialize fabric in your OnCreate method.

Step 15: Inherit your MainActivity from  IAuthCallBack and implement the interface. (Which will add two methods namely Success and Failure to your Activity)

Step 16:  There are multiple ways to authenticate. You can theme your default button or have custom Authentication action from anywhere in the program.

Step 17: For example, you need to authenticate mobile number on a button click, just have  Digits.Authenticate(this);  in your button click event.

Step 18: If you want to have digits button, add

   <com.digits.sdk.android.DigitsAuthButton
android:id=”@+id/auth_button”
android:layout_width=”match_parent”
android:layout_height=”wrap_content” />

in your layout file.

and in your Main Activity, set the callback of the button to the current class.

Step 19: Handle Success and Failure methods. Success method will be called when your authentication using mobile number if verified and it will have the details in DigitsSession p0 variable or p1 gives the mobile number. Failure method will be called if the number cannot be authenticated or User cancels the process.

Step 20: Run and see it in action.

Skip Step 1 to 10 by requesting Twitter Fabrics team a Xamairn plugin 🙂 https://twitter.com/fabric

Shout out your suggestions, feedback and doubts in comment section below.

The Fabric Demo Solution can be downloaded from my Github

Credits: Michel Moreira‘s Fabric Binding for Xamarin.

Blindsist – Assisting Visually Impaired People using IBM Bluemix Visual Recognition

This blog post will cover how I developed Blindsist app for Xhacknight.

The app was developed using Xamarin.Forms, targeting 3 major platforms (iOS, Android and Windows Phone) same time.

Blindsist is a simple one page application. Objective of the application is taking a photo using Smartphone, The photo is then uploaded to IBM Bluemix using REST Api. IBM Bluemix returns the data in Json format, which will be parsed and spoken out using Native Text to Speech services.

Open a new Xamarin.Forms Portable Class Project.

Right click on the Project Blindsist (Portable), click Add new Item, Select Forms Xaml Page, name it ScanPage.xaml

Update the XAML content in ScanPage as below

What it basically does is create a Button Called “ScanButton” which on click trigger event handler called “ScanButtonClicked”.

Let us look to ScanPage.xaml.cs for C# code!

In the constructor ScanPage() write following Code.

For this to work, we have to add a awesome library developed by JamesMontemagno.

It can be found here https://www.nuget.org/packages/Xam.Plugins.TextToSpeech/

To install, right click project, Manage Nuget Package, Search for Xam.Plugins.TextToSpeech, install it in every individual projects.

So when the app starts up, It starts speaking introduction to visually impaired user.

Next is adding Button Clicked event. Just copy this code in your ScanPage.xaml.cs

Now right click your Portable class project, right click, add new item. Add new class file, name it Library.cs

Add following data members.

Now add a Member function GetImage() for Getting Image from Camera, The specialty of coming code is that it works in all 3 platforms with single code. Thanks to another library, which is available in Nuget. Search for Xam.Plugin.Media and install in every projects.

It will check whether Camera is available, if not available return a null object with error message embedded.

Else it will create a file, takes a photo from Camera and store as byte[] format, if file is OK, it returns the Image, with Image Url, and Image in byte[] format.

Now add a member function ProcessImage() to process the image by sending to Bluemix Watson Service.

Each line is commented for understanding what happens there. Atlast we get string bb with Json formatted data from IBM Bluemix with possible results in order of priority.

Now revisit ScanPage.xaml.cs, We have to add “GetPicture()” function on button click. Copy the following code.

Now string temp has the json data, we have to parse it to get the results. Add new class file called Classify.cs in PCL project.

Using http://json2csharp.com we can generate class required for parsing json data from IBM Bluemix service.

To parse json data, again there is a good library called NetwonSoft.Json, obtain it from Nuget, and add it to all projects.

Now we need a simple function to perform deserializing json data.

Create a static class Operations, and a function GetMatch()

Now back to ScanPage.xaml.cs, We have temp ready with Json string. Just pass it to Operations.GetMatch() to get the required data back. Add following codes to where you stopped earlier.

That’s all.. Try Building and running the project. If you face any errors it might be due to not adding Nuget Package mentioned in this post for all projects, or some other errors. Feel free to ask. Together we can build this project to perfection.

The project is in github, https://github.com/muhaym/Xamarin.Forms-Blind-Assist

Feel free to fork, modify, report errors, ask doubts and do whatever you want with the project for the sake of learning.

Please assist me to add Image Compression, because the image upload to Watson Service and getting response back is taking hell of time now.

 

IBM Bluemix & Xamarin Xhacknight 2.0 experiences!

Ooops… I know I am very late to write about my experience at the second Xhacknight conducted by Xamarin Enthusiast group Xhackers and IBM Bluemix.

Let me tell the long tale of our journey. If last time it was Faheem who motivated me to attend the event taking decision last minute, this time I was ready to go at the moment when Nish messaged me they are going to announce Xhacknight.

This time it was my duty to bring more members to the world of Xamarin and motivate them. So I asked my friends to come with me.

The best of my friends ‘geeks’ and ‘jokers’ joined us, Thanks Shabeeb, Farshan, Sabeer, Athul, Yoonus, Marzook for joining me! After all having lot of friends at Hackathons helps to keep awake and have fun whole night! Also we made new friend Yash from Bangalore who joined with us ‘Mallus’ for ultimate entertainment!

  Reached IKP Eden, the venue for Hacknight. I have no words to praise the venue, thanks IKP Management for providing us a wonderful and peaceful atmosphere to learn and hack. The event started exactly at 10:00 am with a Introduction to Xhacknight by none other than VidyaSagar, our friendly #gamedev who now works at IBM. Followed by Naveen Gupta, Head – Asia pacific Mobility group, IBM who introduced the range of IBM Services intended for developers. I was a firm believer that IBM always focused on their enterprise customers and did nothing for the normal developers out there. Naveen’s introduction corrected me! The part which excited me much was Ajay Chebbi’s ReImagine who works at IBM. The amount of energy in his presentation was high, the IronMan, Hololens and such stuff are not science fictions anymore, but reality. Introduction to Bluemix which covered what all services IBM Bluemix provides like Watson, Alchemy, Text to Speech, Speech to text, Personality Insights, Visual Recognition, etc. Complete Catalog of IBM Bluemix Service is here which was explained by Rajesh Jeyapaul. Next was Nish (Nishanth Anil), about whom I boast to my friends that he is one of the greatest Xamarin developer, and one who helps me always when I end up with errors in  my application.

His introduction to Xamarin and all its features was awesome and expectation given to my friends was met :D. Again VidyaSagar came up with Xhacknight’s challenges, Rules,the Rules & Code of conduct. We were split into three groups. We came up with an Idea, and got it approved by Nish and Vidyasagar. IMAG0937Assisting Visually impaired people to understand what is in front of them using IBM Bluemix Visual Recognition and Speaking out the result in order of priority was our idea. Started building the app, opted for Xamarin.Forms so that I can target all 3 platforms atIMAG0906 once, More detail on how I developed the app will be published in coming blog posts. Being awake for about 30 Hours, developing application, debugging with help of  Anubhav (one who helps me always), helping other hackers out there, and getting help from them, It was result time.  Nobody can forget the awesome food and drinks sponsored by DropKaffe  and others. Indeed the Redbull gave us energy to stay awake overnight!

Time to submit our app, presented our project to panel of judges out there.

It’s result time. Finger Crossed.

3rd prize goes to the CodeJunkie for his awesome IOT project.

2nd prize goes to none other than MY TEAM FANTACODE 🙂 Yea It was the awesome android phone One Plus One. Thanks Xhackers & IBM judging panel for selecting us.IMAG0952

1st prize goes to Match.AI, seriously it was a great project that nobody other than them can complete overnight.

I thank the awesome support team, who provided us Internet (Network Guy 😛 we named him) and rest of them for keeping all the hackers comfortable.`Looking forward for next Xhacknight!

 

Contest Winner Announcement

Hi,

Sorry for being late for announcement. Thanks for your great support, submitting Azure Screenshots. Hope you learned something from the process. Keep going, build great Cloud Solution.

I have selected the winner, completely on Random basis, with the help of Random.org.

The winner is Afis Moossa P (afismoosa-at-gmail-dot-com)

I will be contacting the winner by mail, Congrats!

 

 

Contest: Win Windows 8.1 Pro License (Students Only) – Azure Dreamspark Subscription

With few steps, you could win Windows 8.1 Pro (Yes Worth Rs 10,000) for student randomly selected from submission and a Azure subscription for get started with Microsoft Cloud Computing Solution.

So what you have to do is follow

Step 1: Create a Microsoft Account – Go to Outlook.com if you don’t have one.

Microsoft Account is one stop for your 15 GB Free Onedrive Cloud Space, Windows Store, Microsoft Azure, Xbox & even login to Windows Based device, so if you don’t have one, its time to create one.

Step 2: Start Utilizing Microsoft Virtual Academy.

Microsoft Virtual Academy is the best resource for beginners to develop some skills like Application development, Game development, learning C#, Javascript, etc. This step is not compulsory,  still it is best to utilize the free resource Microsoft provide to develop your skills.

Visit htp://www.microsoftvirtualacademy.com

Suggested Course to Complete:

Microsoft Azure Fundamentals: Websites

Microsoft Azure Fundamentals: Storage and Data

I will be blogging how to use Azure for hosting Websites, and for Mobile Services.

Step 3: Create a Dreamspark Subscription and Activate Azure

Detailed instructions on Creation of account & Activation of Azure Student Offer.

For a net- new user, the flow of activating your Azure Student Offer would be as follows: Create an account -> Get your student status verified -> Activate your account -> Avail the Azure Student offer.

  1. Visit the link here and click on ‘Create Account’ and create your Microsoft login credentials.
  2. After creating the login credentials, login to the site here, and click on ‘Verify your student status’
  3. Select the ‘I can provide documentation’ tab as shown below: azure1  Provide the requested details & get your academic status verified.
  4.  Once you get a confirmation email from the team, please click on the link provided in the email to activate your student account.  (In case you see any error in these step, Contact their support team for immediate activation, It takes upto 2-3 business day)
  5. Once the account is activated, you can activate your Azure account, by following the detailed instructions given here.

Step 4: Take a Screenshot and Mail me!

Login to your azure portal and take a screenshot like this.

To get the details, place your mouse over Your Name at right top corner.

RAShid

Mail the screenshot with your Name, College, and your education details (like course, year) to muhaymin – at – muhaym.in muhaym.in

LAST DATE FOR SUBMISSION IS 15th of September, Don’t wait for last date because dream spark activation takes more than 2-3 days. Follow me in twitter for more updates http://twitter.com/muhaym

I will select random submission as winner and will announce in this blog on 20th September after verification.

I will be blogging about Azure, using Azure Mobile Service in your apps in coming days. If any doubts feel free to ask in the comment section below.

How to develop a Xamarin.Forms Hello World Application – Xamarin.Forms Series Part 1

Xamarin.Forms a quick Introduction

Today, we will learn how to develop a cross platform Hello World application using Xamarin.Forms.

Xamarin.Forms is not the final word for Cross platform Mobile app development. It is best for getting started with Xamarin, and targetting 3 major platform by sharing 99% Code.

Xamarin.Android or Xamarin.iOS is best for application dealing with high device specific API  usage like geolocation, and other such capabilities. Through Xamarin.Android or Xamarin.iOS a C# developer can share the business logic among Projects and design Native UI’s and make use of Device specific capabilities for 3 platforms independently.

Xamarin.Forms on other hand can be used for simple application where there is less Platform specific API usage.

Xamarin.Forms is great for prototyping or making a quick prototype application. And after you’ve done that, you might just find that you can continue using Xamarin.Forms features to build the entire application.

Hello World using Xamarin.Forms

To get started you must have Installed latest version of Xamarin, I am using Visual Studio for developing the Hello World application so that I can target 3 platform. But I wont be showing iOS screenshots because I don’t have an Apple device in my network. But don’t worry, all the implementations we do here will hopefully work in iOS device.

Hello World! The first application you probably create when you learn new language or start using new development tool.

I am not covering everything in detail, like the basic C# concepts, or Xamarin.Forms complete capabilities.  This tutorial is intended for Getting started with Xamarin.Forms, everything in detail can be learned from Creating Mobile Apps with Xamarin.Forms Book Preview 2 by Charles Petzold http://www.microsoftvirtualacademy.com/ebooks#9780735697232

Open Visual studio, and Create new project.

Select Xamarin.Forms Portable Class Library Project (PCL).  As Xamarin Documentation suggests to go for shared if our Project contains XAML (Extensible Markup language, usually pronounced Zammel), in which we will be developing from now on.

For Xamarin.Forms solutions that contain XAML, we recommend using the Xamarin.Forms Portable Class Library (PCL) template rather than using Shared Asset Projects (SAP). The PCL approach isolates Xamarin.Forms code in a separate DLL, while the SAP shares code directly among the three platforms. Before using XAML with the Shared Asset Project (SAP) template read the details below on enabling experimental XAML support in SAPs.

Xamarin.Forms PCL New Project in VS2015
Create Xamarin.Forms PCL New Project in VS2015.

Xamarin.Forms Projects

The Xamarin.Forms Blank template will set up projects for iOS, Android and Windows Phone 8.0. Feel free to delete any project if you are not going to target it.

Right click the solution, click Build Solutions and Run the project in platform of your choice by setting startup project.

Hint for beginners: Startup Project can be changed by right clicking desired Project in Solution, and Selecting “Set as startup project”.

Screenshot with Blank Template

You can see that app is generated as above screenshot.

Now let us dig deep, so we can understand what is happening.

Each Projects in the solution has

  1. iOS – AppDelegate.cs
  2. Android – MainActivity.cs
  3. Windows Phone – MainPage.xaml.cs

These three files are the starting points of respective platforms. All these files contain a line

Here HelloWorld is our Project Shared, App is the entry point (App.cs) in our PCL Project.

This line invokes the App.cs in the main HelloWorld Project which is where we write code to Share among three platform, which contains

MainPage is the entry point of your app, the first page displayed in app. Why I love programming with help of XAML is that I can write the complex parts like the new ContentPage{ … part in above code in more understandable form.

So We just want to create a new entry page. Right Click HelloWorld (Portable) Project, Click Add new Item.

Select Forms Xaml Page, and give it a name FirstPage.xaml. We will use this project as continuation for next tutorial in the series, navigation of pages in Xamarin.Forms.

addnewitem

In FirstPage.xaml, write the code as below

<?xml version=”1.0″ encoding=”utf-8″ ?>
<ContentPage xmlns=”http://xamarin.com/schemas/2014/forms”
xmlns:x=”http://schemas.microsoft.com/winfx/2009/xaml”
x:Class=”HelloWorld.FirstPage”>
<StackLayout VerticalOptions=”Center” HorizontalOptions=”Center” >
<Label Text=”I love XAML” />
</StackLayout>
</ContentPage>

Now we will compare with the first set of code we wrote (or was there in default in App.cs).

new ContentPage { is a main node <ContentPage> in xml format

new StackLayout { is a child node <StackLayout> under <ContentPage>

new Label { is again a child node <Label> under <StackLayout>.

In my view this is simpler than coding it in C#. You can code in the way you want.

Now we want this FirstPage.xaml loaded in startup. Just a small changes in App.cs will get it done.

and comment out the rest of part so that you can compare and study.

Now Build the project and run again.

Voila! The new Xaml Page loads in startup.

HelloWorldFinal

So in our First Series, we have learned bit more than a simple Hello World app.

We covered

  1. Creating Xaml.Forms New PCL Project.
  2. Building it and Running.
  3. Coding UI in C# and XAML.
  4. Loading any Xamarin.Form Page as MainPage.

Shout out your suggestions, feedbacks and doubts in comment section below. To be frank this is the first time I am writing tutorial, so your suggestions will help me improve my self.

The HelloWorld Solution can be downloaded from my Github (not a good Project to share, still you guys can fork it and start building on it in case of any issues)

https://github.com/muhaym/Xamarin.Forms.HelloWorld

Xamarin Students Offer

Hey Guys,

I have been long since I have blogged. Sorry for being away. I think I am the laziest person in this world.

Today I have something to share  with you guys.

Hope you all know about Xamarin, Xamarin is a cross platform mobile application development tool, Which lets you create applications for major platforms such as iOS, Android and Windows Phone. I will be blogging about developing cross platform application using Xamarin. So this tool is sooooooo costly that we students, or startup can’t afford.

Wait, But what if they want you to develop something great? Yea.. Xamarin is free for students, you can apply for a Students license which will let you develop iOS, Android application using Visual Studio or Xamarin Studio.

It is very easy to apply for Xamarin Student License.  Just mail your student ID card scanned copy or some document to verify that you are student to student – at – xamarin dot com.

For more details visit http://xamarin.com/student

Sit tight and we will start developing cross platform application from next post onward.