Delpin Susai Raj Monday, 7 December 2020

Xamarin.Forms - Open App Store or Play Store in XamarinApp

 In this blog post, you will learn how to Open Play Store or App Store in XamarinApp.

Introduction

Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.

Prerequisites

  • Visual Studio 2017 or later (Windows or Mac)

Setting up a Xamarin.Forms Project

Start by creating a new Xamarin.Forms project. You wíll learn more by going through the steps yourself.

Create a new or existing Xamarin forms(.Net standard) Project. With Android and iOS Platform. 

Note: Your app must be live in App store and Playstore 

Android

Here, you need the Android app id Ex:com.twitter.android.

I'm using twitter for this sample.

https://play.google.com/store/apps/details?id=com.twitter.android

Code

if (Device.RuntimePlatform == Device.Android)
{
url = "https://play.google.com/store/apps/details?id=com.twitter.android";
await Browser.OpenAsync(url, BrowserLaunchMode.External);
}
view raw Android.cs hosted with ❤ by GitHub

iOS

Here, you need AppName and AppId with location you will get appname and aped from apple developer connect.

https://apps.apple.com/in/app/twitter/id333903271

Code

var location = RegionInfo.CurrentRegion.Name.ToLower();
if (Device.RuntimePlatform == Device.iOS)
{
url = "https://itunes.apple.com/" + location + "/app/twitter/id333903271?mt=8";
await Browser.OpenAsync(url, BrowserLaunchMode.External);
}
view raw iOS.cs hosted with ❤ by GitHub

Simple UI

MainPage.xaml

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:TitleView="clr-namespace:XamarinApp.CustomView"
mc:Ignorable="d" x:Class="XamarinApp.MainPage">
<NavigationPage.TitleView>
<TitleView:TitleView/>
</NavigationPage.TitleView>
<StackLayout Margin="0,100,0,0" VerticalOptions="StartAndExpand">
<Image VerticalOptions="Center" Source="xamarinmonkeysbanner.png"/>
<Button Text="Update your app" Clicked="Button_Clicked" />
</StackLayout>
</ContentPage>
view raw MainPage.xaml hosted with ❤ by GitHub

Full Source Code

MainPage.xaml.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Essentials;
using Xamarin.Forms;
namespace XamarinApp
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
async void Button_Clicked(System.Object sender, System.EventArgs e)
{
string url = string.Empty;
var location = RegionInfo.CurrentRegion.Name.ToLower();
if (Device.RuntimePlatform == Device.Android)
url = "https://play.google.com/store/apps/details?id=com.twitter.android";
else if (Device.RuntimePlatform == Device.iOS)
url = "https://itunes.apple.com/" + location + "/app/twitter/id333903271?mt=8";
await Browser.OpenAsync(url, BrowserLaunchMode.External);
}
}
}

Alternate way

You can use Lancher.OpenAsync also for opening App Store and Play store.

Launcher.OpenAsync(new Uri("https://itunes.apple.com/in/app/facebook/id284882215?mt=8"));
view raw Launcher.cs hosted with ❤ by GitHub

Using Dependency Service

Interface

using System;
namespace XamarinApp
{
public interface IOpenAppStore
{
void OpenAppStore();
}
}

iOS Implementation

Below sample code for open App store in App iOS.

[assembly:Dependency(typeof(AppStoreImplementation))]
namespace XamarinApp.iOS
{
public class AppStoreImplementation : IOpenAppStore
{
public void OpenAppStore()
{
Device.OpenUri(new Uri("https://itunes.apple.com/in/app/facebook/id284882215?mt=8"));
}
}
}

Android Implementation

Below sample code for open play store in App android. 

[assembly:Dependency(typeof(AppStoreImplementation))]
namespace XamarinApp.Android
{
public class AppStoreImplementation : IOpenAppStore
{
public void OpenAppStore()
{
Device.OpenUri(new Uri("https://play.google.com/store/apps/details?id=com.twitter.android"));
}
}
}

Debug your App

I hope you have understood you will learn how to Open Play Store or App Store in XamarinApp.

Thanks for reading. Please share your comments and feedback. Happy Coding :)

Delpin Susai Raj Friday, 20 November 2020

Xamarin.Forms - File Browser

 In this blog post, you will learn how to pick files from your device, Drive, iCloud in Xamarin.Forms.

Introduction

Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.

Prerequisites

  • Visual Studio 2017 or later (Windows or Mac)

Setting up a Xamarin.Forms Project

 Start by creating a new Xamarin.Forms project. You wíll learn more by going through the steps yourself.

 Create a new or existing Xamarin forms(.Net standard) Project. With Android and iOS Platform. 

Nuget

Install following Nuget from Nuget Manager In your visual studio.

Name.      : Xamarin.Plugin.FilePicker

Version    : 2.1.41

Url           : https://www.nuget.org/packages/Xamarin.Plugin.FilePicker/

Xamarin.Essentials

Xamarin.Essentials also supports File Picker but it's in Preview. Once the FilePicker moved to stable you can update Xamarin.Pulgin.FilePicker to Xamarin.Essentials

https://docs.microsoft.com/en-us/xamarin/essentials/file-picker

Setup UI

Now, I created simple UI for file browser.

MainPage.xaml

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:d="http://xamarin.com/schemas/2014/forms/design" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="FileUploadPOC.MainPage">
<StackLayout HorizontalOptions="Center">
<!-- Place new controls here -->
<Image Source="xamarinmonkeysbanner.png" HorizontalOptions="Center" Margin="0,100,0,0"/>
<Button Margin="0,20,0,0" Text="Browse File" Clicked="Button_Clicked"></Button>
<Label x:Name="lblName"/>
<Label x:Name="lblFilePath"/>
</StackLayout>
</ContentPage>
view raw MainPage.xaml hosted with ❤ by GitHub

File Browser

Below code for file picker, Here will get two values FileName and FilePath.

private async Task PickAndShow(string[] fileTypes)
{
try
{
var pickedFile = await CrossFilePicker.Current.PickFile(fileTypes);
if (pickedFile != null)
{
lblName.Text = pickedFile.FileName;
lblFilePath.Text = pickedFile.FilePath;
}
}
catch (Exception ex)
{
}
}
view raw FilePicker.cs hosted with ❤ by GitHub

File Types

Note, you can define the file types for platform specific.

if (Device.RuntimePlatform == Device.Android)
{
fileTypes = new string[] { "image/png", "image/jpeg" };
}
if (Device.RuntimePlatform == Device.iOS)
{
fileTypes = new string[] { "public.image" }; // same as iOS constant UTType.Image
}
if (Device.RuntimePlatform == Device.UWP)
{
fileTypes = new string[] { ".jpg", ".png" };
}
if (Device.RuntimePlatform == Device.WPF)
{
fileTypes = new string[] { "JPEG files (*.jpg)|*.jpg", "PNG files (*.png)|*.png" };
}
view raw FilePicker.cs hosted with ❤ by GitHub

Reference for other file types.

https://stackoverflow.com/questions/41797644/xamarin-ios-filtering-out-the-filetype-show-on-document-picker

MainPage.Xaml.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Plugin.FilePicker;
using Xamarin.Essentials;
using System.Security.Cryptography.X509Certificates;
namespace FileUploadPOC
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
async void Button_Clicked(System.Object sender, System.EventArgs e)
{
try
{
string[] fileTypes = null;
if (Device.RuntimePlatform == Device.iOS)
{
fileTypes = new string[] {"com.adobe.pdf", "public.rft", "com.microsoft.word.doc", "org.openxmlformats.wordprocessingml.document" }; }
await PickAndShow(fileTypes);
}
catch (Exception ex)
{
}
}
private async Task PickAndShow(string[] fileTypes)
{
try
{
var pickedFile = await CrossFilePicker.Current.PickFile(fileTypes);
if (pickedFile != null)
{
lblName.Text = pickedFile.FileName;
lblFilePath.Text = pickedFile.FilePath;
}
}
catch (Exception ex)
{
}
}
}
}

Debug your App



Once select the file you will get the FileName and FilePath.

I hope you have understood you will learn how to browse file in your device and drive in Xamarin.Forms..

Thanks for reading. Please share your comments and feedback. Happy Coding :)

Delpin Susai Raj Thursday, 12 November 2020

Xamarin.Forms - Custom TitleView

 In this blog post, you will learn how to create a custom TitleView in Xamarin.Forms.

Introduction

Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.

Prerequisites

  • Visual Studio 2017 or later (Windows or Mac)

Setting up a Xamarin.Forms Project

Start by creating a new Xamarin.Forms project. You wíll learn more by going through the steps yourself. Create a new or existing Xamarin forms(.Net standard) Project. With Android and iOS Platform. 

Simple Title

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="XamarinApp.MainPage"
Title="My Page">
<StackLayout Margin="0,100,0,0" VerticalOptions="StartAndExpand">
<Image VerticalOptions="Center" Source="xamarinmonkeysbanner.png"/>
</StackLayout>
</ContentPage>
view raw MainPage.Xaml hosted with ❤ by GitHub

Simple TitleView with NavigationPage

App.Xaml.cs

Your page must be a Navigation Page

public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
}
view raw App.xaml.cs hosted with ❤ by GitHub

Here, we going to use NavigationPage,TitleView. You can use this for Custom TitleView.

MainPage.Xaml

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:d="http://xamarin.com/schemas/2014/forms/design" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="XamarinApp.MainPage">
<NavigationPage.TitleView>
<StackLayout HorizontalOptions="Center" VerticalOptions="Center" Orientation="Horizontal">
<Label HorizontalOptions="Center" VerticalTextAlignment="Center" Text="MyPage" FontSize="Small"/>
</StackLayout>
</NavigationPage.TitleView>
<StackLayout Margin="0,100,0,0" VerticalOptions="StartAndExpand">
<Image VerticalOptions="Center" Source="xamarinmonkeysbanner.png"/>
</StackLayout>
</ContentPage>
view raw MainPage.Xaml hosted with ❤ by GitHub

Title with Icon

Now, added Title with Image in TitleView

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:d="http://xamarin.com/schemas/2014/forms/design" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="XamarinApp.MainPage">
<NavigationPage.TitleView>
<StackLayout HorizontalOptions="Center" VerticalOptions="Center" Orientation="Horizontal">
<Label HorizontalOptions="Center" VerticalTextAlignment="Center" Text="Refresh" FontSize="Small"/>
<Image VerticalOptions="Center" HorizontalOptions="End" Source="sync.png"/>
</StackLayout>
</NavigationPage.TitleView>
<StackLayout Margin="0,100,0,0" VerticalOptions="StartAndExpand">
<Image VerticalOptions="Center" Source="xamarinmonkeysbanner.png"/>
</StackLayout>
</ContentPage>
view raw MainPage.xaml hosted with ❤ by GitHub

TitleView with SearchView

You can add SearchBar also in the TitleView

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" x:Class="XamarinApp.MainPage">
<NavigationPage.TitleView>
<SearchBar Placeholder="Search items..."
HorizontalTextAlignment="Center"
FontSize="Medium"
/>
</NavigationPage.TitleView>
<StackLayout Margin="0,100,0,0" VerticalOptions="StartAndExpand">
<Image VerticalOptions="Center" Source="xamarinmonkeysbanner.png"/>
</StackLayout>
</ContentPage>
view raw MainPage.xaml hosted with ❤ by GitHub

Custom TitleView

Here, Going to create a common TitleView, you can reuse your Content pages.

TitleView.Xaml

<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="XamarinApp.CustomView.TitleView">
<ContentView.Content>
<Label HorizontalOptions="Center" Text="Xamarin Monkeys"/>
</ContentView.Content>
</ContentView>
view raw TitleView.xaml hosted with ❤ by GitHub

Consume TitleView

Now, Consume the TitleView from your custom files folder.

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:TitleView="clr-namespace:XamarinApp.CustomView"
mc:Ignorable="d" x:Class="XamarinApp.MainPage">
<NavigationPage.TitleView>
<TitleView:TitleView/>
</NavigationPage.TitleView>
<StackLayout Margin="0,100,0,0" VerticalOptions="StartAndExpand">
<Image VerticalOptions="Center" Source="xamarinmonkeysbanner.png"/>
</StackLayout>
</ContentPage>
view raw MainPage.xaml hosted with ❤ by GitHub

I hope you have understood you will learn how to create a custom TitleView in Xamarin.Forms.

Thanks for reading. Please share your comments and feedback. 

Happy Coding :)

Delpin Susai Raj Friday, 23 October 2020

Xamarin.Forms - Mobile Network Speed Check(Slow or Fast) in Android

In this blog post, you will learn how to check you mobile network speed(slow or speed) using android native in Xamarin.Forms.



Introduction

Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.

Prerequisites

  • Visual Studio 2017 or later (Windows or Mac)

Setting up a Xamarin.Forms Project

 Start by creating a new Xamarin.Forms project. You wíll learn more by going through the steps yourself.

Create a new or existing Xamarin forms(.Net standard) Project. With Android and iOS Platform. 


Create a Interface

public interface INetwork
{
bool IsConnected();
bool IsConnectedFast();
}
view raw INetwork.cs hosted with ❤ by GitHub

Create a NetworkConnectivity

Following code will check the Mobile network connection and Check the Network status whether speed or slow.

NetworkConnectivity.cs

public class NetworkConnectivity
{
public static NetworkInfo GetNetworkInfo(Context context)
{
ConnectivityManager cm = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);
return cm.ActiveNetworkInfo;
}
/**
* Check if there is any connectivity
* @param context
* @return
*/
public static bool IsConnected(Context context)
{
NetworkInfo info = NetworkConnectivity.GetNetworkInfo(context);
return (info != null && info.IsConnected);
}
/**
* Check if there is any connectivity to a Wifi network
* @param context
// @param type
* @return
*/
public static bool IsConnectedWifi(Context context)
{
NetworkInfo info = NetworkConnectivity.GetNetworkInfo(context);
return (info != null && info.IsConnected && info.Type == ConnectivityType.Wifi);
}
/**
* Check if there is any connectivity to a mobile network
* @param context
// @param type
* @return
*/
public static bool IsConnectedMobile(Context context)
{
NetworkInfo info = NetworkConnectivity.GetNetworkInfo(context);
return (info != null && info.IsConnected && info.Type == ConnectivityType.Mobile);
}
/**
* Check if there is fast connectivity
* @param context
* @return
*/
public static bool IsConnectedFast(Context context)
{
NetworkInfo info = NetworkConnectivity.GetNetworkInfo(context);
TelephonyManager tm = TelephonyManager.FromContext(context);
return (info != null && info.IsConnected && NetworkConnectivity.IsConnectionFast(info.Type, tm.NetworkType));
}
/**
* Check if the connection is fast
* @param type
* @param subType
* @return
*/
public static bool IsConnectionFast(ConnectivityType type, NetworkType subType)
{
if (type == ConnectivityType.Wifi)
{
return true;
}
else if (type == ConnectivityType.Mobile)
{
switch (subType)
{
//case TelephonyManager.NETWORK_TYPE_1xRTT:
case NetworkType.OneXrtt:
return false; // ~ 50-100 kbps
//case TelephonyManager.NETWORK_TYPE_CDMA:
case NetworkType.Cdma:
return false; // ~ 14-64 kbps
//case TelephonyManager.NETWORK_TYPE_EDGE:
case NetworkType.Edge:
return false; // ~ 50-100 kbps
//case TelephonyManager.NETWORK_TYPE_EVDO_0:
case NetworkType.Evdo0:
return true; // ~ 400-1000 kbps
//case TelephonyManager.NETWORK_TYPE_EVDO_A:
case NetworkType.EvdoA:
return true; // ~ 600-1400 kbps
//case TelephonyManager.NETWORK_TYPE_GPRS:
case NetworkType.Gprs:
return false; // ~ 100 kbps
//case TelephonyManager.NETWORK_TYPE_HSDPA:
case NetworkType.Hsdpa:
return true; // ~ 2-14 Mbps
//case TelephonyManager.NETWORK_TYPE_HSPA:
case NetworkType.Hspa:
return true; // ~ 700-1700 kbps
//case TelephonyManager.NETWORK_TYPE_HSUPA:
case NetworkType.Hsupa:
return true; // ~ 1-23 Mbps
//case TelephonyManager.NETWORK_TYPE_UMTS:
case NetworkType.Umts:
return true; // ~ 400-7000 kbps
/*
* Above API level 7, make sure to set android:targetSdkVersion
* to appropriate level to use these
*/
//case TelephonyManager.NETWORK_TYPE_EHRPD: // API level 11
case NetworkType.Ehrpd:
return true; // ~ 1-2 Mbps
//case TelephonyManager.NETWORK_TYPE_EVDO_B: // API level 9
case NetworkType.EvdoB:
return true; // ~ 5 Mbps
//case TelephonyManager.NETWORK_TYPE_HSPAP: // API level 13
case NetworkType.Hspap:
return true; // ~ 10-20 Mbps
//case TelephonyManager.NETWORK_TYPE_IDEN: // API level 8
case NetworkType.Iden:
return false; // ~25 kbps
//case TelephonyManager.NETWORK_TYPE_LTE: // API level 11
case NetworkType.Lte:
return true; // ~ 10+ Mbps
// Unknown
//case TelephonyManager.NETWORK_TYPE_UNKNOWN:
case NetworkType.Unknown:
return false;
default:
return false;
}
}
else
{
return false;
}
}
public static bool IsHostReachable(string host)
{
if (string.IsNullOrEmpty(host))
return false;
bool isReachable = true;
Thread thread = new Thread(() =>
{
try
{
//isReachable = InetAddress.GetByName(host).IsReachable(2000);
/*
* It's important to note that isReachable tries ICMP ping and then TCP echo (port 7).
* These are often closed down on HTTP servers.
* So a perfectly good working API with a web server on port 80 will be reported as unreachable
* if ICMP and TCP port 7 are filtered out!
*/
//if (!isReachable){
URL url = new URL("http://" + host);
URLConnection connection = url.OpenConnection();
//if(connection.ContentLength != -1){
//isReachable = true;
if (connection.ContentLength == -1)
{
isReachable = false;
}
//}
}
catch (UnknownHostException e)
{
isReachable = false;
}
catch (IOException e)
{
isReachable = false;
}
});
thread.Start();
return isReachable;
}
}

Android Implementation

Here, Implement the Interface and return the network status.

NetworkHelper.cs

[assembly: Xamarin.Forms.Dependency(typeof(NetworkHelper))]
namespace NetworkPOC.Droid
{
public class NetworkHelper : INetwork
{
Context context = Android.App.Application.Context;
public bool IsConnected()
{
return NetworkConnectivity.IsConnected(context);
}
public bool IsConnectedFast()
{
return NetworkConnectivity.IsConnectedFast(context);
}
}
}


Consume the Network helper

Here, you will call the Network helper class and you will get the network speed.

MainPage.Xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="NetworkPOC.MainPage">
<StackLayout HorizontalOptions="Center" VerticalOptions="Start" Margin="0,150,0,0">
<Label FontSize="Large" Text="Xamarin Monkeys"/>
<Button Text="Check" Clicked="Button_Clicked"></Button>
</StackLayout>
</ContentPage>
view raw MainPage.xaml hosted with ❤ by GitHub


Here I shows the result in toast. 

MainPage.xaml.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Essentials;
using System.Net.Http;
namespace NetworkPOC
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
var current = Connectivity.NetworkAccess;
if (current == NetworkAccess.Internet)
{
bool isConnectionFast = DependencyService.Get<INetwork>().IsConnectedFast();
if (isConnectionFast)
DependencyService.Get<IToast>().ShowToast("Network Connection is good");
else
DependencyService.Get<IToast>().ShowToast("Network Connection is slow");
}
else
{
DependencyService.Get<IToast>().ShowToast("No Internet Connection");
}
}
}


Run



I hope you have understood you will learn how to check you mobile network speed(slow or speed) using android native in Xamarin.Forms.

Thanks for reading. Please share your comments and feedback. 

Happy Coding :)

Delpin Susai Raj Wednesday, 21 October 2020

Xamarin.Forms - Network Speed Monitor

 In this blog post, you will learn how to monitor you network speed in Xamarin.Forms.

Introduction

Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.

Prerequisites

  • Visual Studio 2017 or later (Windows or Mac)

Setting up a Xamarin.Forms Project

Start by creating a new Xamarin.Forms project. You wíll learn more by going through the steps yourself.

Create a new or existing Xamarin forms(.Net standard) Project. With Android and iOS Platform.


 Network Monitor 

Now, create a network helper class for check network connectivity in xamarin.froms.

NetworkHelper.cs

public class NetworkHelper
{
public async Task<string> CheckInternetSpeed()
{
DateTime dt1 = DateTime.Now;
string internetSpeed;
try
{
var client = new HttpClient();
byte[] data = await client.GetByteArrayAsync("http://xamarinmonkeys.blogspot.com/");
DateTime dt2 = DateTime.Now; Console.WriteLine("ConnectionSpeed: DataSize (kb) " + data.Length / 1024);
Console.WriteLine("ConnectionSpeed: ElapsedTime (secs) " + (dt2 - dt1).TotalSeconds);
internetSpeed = "ConnectionSpeed: (kb/s) " + Math.Round((data.Length / 1024) / (dt2 - dt1).TotalSeconds, 2);
}
catch (Exception ex)
{
internetSpeed = "ConnectionSpeed:Unknown Exception-" + ex.Message;
}
Console.WriteLine(internetSpeed);
return internetSpeed;
}
}


Consuming Network helper

Here, you will call the Network helper class and you will get the network speed.

MainPage.Xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="NetworkPOC.MainPage">
<StackLayout HorizontalOptions="Center" VerticalOptions="Start" Margin="0,150,0,0">
<Label FontSize="Large" Text="Xamarin Monkeys"/>
<Button Text="Check" Clicked="Button_Clicked"></Button>
</StackLayout>
</ContentPage>
view raw MainPage.Xaml hosted with ❤ by GitHub


Here I shows the result in toast. 

MainPage.xaml.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Essentials;
using System.Net.Http;
namespace NetworkPOC
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private async void Button_Clicked(object sender, EventArgs e)
{
if (current == NetworkAccess.Internet)
{
var speed=await CheckInternetSpeed();
DependencyService.Get<IToast>().ShowToast(speed);
}
else
{
DependencyService.Get<IToast>().ShowToast("No Internet Connection");
}
}
}
}


Run



I hope you have understood you will learn how to check network speed in Xamarin.Forms.

Thanks for reading. Please share your comments and feedback. 

Happy Coding :)

Delpin Susai Raj Monday, 12 October 2020

Enable Dark Mode in iOS Simulator

 

Make sure your iOS version should be iOS 13 or Later

Goto Settings in your iOS Simulator.

Now scroll down in settings, you're able to see the Developer in the list. Click Developer.

Now, Enable the Dark Appearance toggle. Your simulator will behave dark mode.

Your simulator is Dark Mode.

I hope you have understood how to enable the dark mode in iOS Simulator.

Thanks for reading. Please share your comments and feedback. Happy Coding :)

Xamarin.Forms - Support Dark Mode

In this blog post, you will learn how to give support Dark Mode in Xamarin.Forms.

Introduction

Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.

Dark Mode


Nowadays iOS and Android apps should support both Dark and Light Theme.

Prerequisites

  • Visual Studio 2017 or later (Windows or Mac)

Setting up a Xamarin.Forms Project

 Start by creating a new Xamarin.Forms project. You wíll learn more by going through the steps yourself.

Create a new or existing Xamarin forms(.Net standard) Project. With Android and iOS Platform. 

Create a Theme

Create a ResourceDictionary for both Light and Dark Theme.

DarkTheme.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="DarkModePOC.Common.Styles.DarkTheme">
<Color x:Key="BackgroundColor">#FF000000</Color>
<Color x:Key="FrameColor">#FF1f1f1f</Color>
<Color x:Key="TextPrimaryColor">#B0FFFFFF</Color>
<Color x:Key="TextSecondaryColor">#eFeFeF</Color>
<Style x:Key="Title" TargetType="Label">
<Setter Property="TextColor" Value="{StaticResource TextPrimaryColor}"/>
<Setter Property="FontAttributes" Value="Bold"/>
<Setter Property="FontSize" Value="Large"/>
</Style>
</ResourceDictionary>
view raw DarkTheme.xaml hosted with ❤ by GitHub

LightTheme.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="DarkModePOC.Common.Styles.LightTheme">
<Color x:Key="BackgroundColor">#FFe0e0e0</Color>
<Color x:Key="FrameColor">#FFFFFFFF</Color>
<Color x:Key="TextPrimaryColor">#B0000000</Color>
<Color x:Key="TextSecondaryColor">#858585</Color>
<Style x:Key="Title" TargetType="Label">
<Setter Property="TextColor" Value="{StaticResource TextPrimaryColor}"/>
<Setter Property="FontSize" Value="Large"/>
</Style>
</ResourceDictionary>
view raw LightTheme.xaml hosted with ❤ by GitHub


Set App Theme

In app.xaml you can set the default theme.

App.xaml

<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="DarkModePOC.App">
<Application.Resources>
<ResourceDictionary Source="Common/Styles/LightTheme.xaml" />
</Application.Resources>
</Application>
view raw App.xaml hosted with ❤ by GitHub

Now, Create a Enum in App.xaml.cs

public partial class App : Application
{
public static Theme AppTheme { get; set; }
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
}
protected override void OnStart()
{
}
protected override void OnSleep()
{
}
protected override void OnResume()
{
}
public enum Theme
{
Light,
Dark
}
}
view raw App.xaml.cs hosted with ❤ by GitHub

Create a Interface

Create a interface for set Theme at runtime.

public interface IAppTheme
{
void SetAppTheme(Theme theme);
}
view raw IAppTheme hosted with ❤ by GitHub


iOS Implementation

Below code to change the Theme at runtime.

ThemeHelper.cs


[assembly:Dependency(typeof(DarkModePOC.iOS.ThemeHelper))]
namespace DarkModePOC.iOS
{
public class ThemeHelper : IAppTheme
{
public void SetAppTheme(App.Theme theme)
{
SetTheme(theme);
}
void SetTheme(Theme mode)
{
if (mode == Theme.Dark)
{
if (App.AppTheme == Theme.Dark)
return;
App.Current.Resources = new DarkTheme();
}
else
{
if (App.AppTheme != Theme.Dark)
return;
App.Current.Resources = new LightTheme();
}
App.AppTheme = mode;
}
}
}
view raw ThemeHelper.cs hosted with ❤ by GitHub


Android Implementation

Below code to change the Theme at runtime.

ThemeHelper.cs


[assembly: Dependency(typeof(DarkModePOC.Droid.ThemeHelper))]
namespace DarkModePOC.Droid
{
public class ThemeHelper : IAppTheme
{
public void SetAppTheme(App.Theme theme)
{
SetTheme(theme);
}
void SetTheme(Theme mode)
{
if (mode == Theme.Dark)
{
if (App.AppTheme == Theme.Dark)
return;
App.Current.Resources = new DarkTheme();
}
else
{
if (App.AppTheme != Theme.Dark)
return;
App.Current.Resources = new LightTheme();
}
App.AppTheme = mode;
}
}
}
view raw ThemeHelper.cs hosted with ❤ by GitHub


Consuming the Styles


Now, you can use the resource "DynamicResource BackgroundColor" like this.


<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
BackgroundColor="{DynamicResource BackgroundColor}"
x:Class="DarkModePOC.MainPage">
<StackLayout HorizontalOptions="Center" VerticalOptions="Center">
<!-- Place new controls here -->
<Switch x:Name="themeToggle" IsToggled="False" Toggled="Switch_Toggled"/>
<Label TextColor="{DynamicResource TextSecondaryColor}" Text=" sample"/>
<Button HorizontalOptions="Center" VerticalOptions="Center" TextColor="Red" Text="Next Page" Clicked="Button_Clicked" />
</StackLayout>
</ContentPage>
view raw MainPage.xaml hosted with ❤ by GitHub


private void Switch_Toggled(object sender, ToggledEventArgs e)
{
var toggleStatus = themeToggle.IsToggled;
SetTheme(toggleStatus);
}
void SetTheme(bool status)
{
Theme themeRequested;
if (status)
{
themeRequested = Theme.Dark;
}
else
{
themeRequested = Theme.Light;
}
DependencyService.Get<IAppTheme>().SetAppTheme(themeRequested);
}


Click the "Play" button to try it out.

Dark Mode


Light Mode

I hope you have understood you will learn how to give support Dark Mode in Xamarin.Forms..

Thanks for reading. Please share your comments and feedback. 

Happy Coding :)

Delpin Susai Raj Wednesday, 15 July 2020

Xamarin.Forms - Debugging WebView

In this blog post, you will learn how to debugging WebView in xamarin forms.

Introduction
 
Xamarin.Forms code runs on multiple platforms, each of which has its own filesystem. This means that reading and writing files are most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.

Debugging Webview

Mobile developers are facing major difficulties for debugging web URLs. I  going to explain how to debug your xamarin.forms webview in an Emulator or simulator.

Prerequisites
  • Visual Studio 2017 or later (Windows or Mac)
Setting up a Xamarin.Forms Project
 
Start by creating a new Xamarin.Forms project. You will learn more by going through the steps yourself.
 
Create a new or existing Xamarin forms (.Net standard) Project with Android and iOS Platform.

Choose the Mobile App (Xamarin. forms) project under C# and Mobile.
 
Name your app. You probably want your project and solution to use the same name as your app. Put it on your preferred location for projects and click "Create".
 
Now, select the blank app and target platforms - Android, iOS and Windows (UWP).
 
Subsequently, go to the solution. In there, you get all the files and sources of your project (.NET Standard). Now, select the XAML page and double-click to open the MainPage.Xaml page.
 
You now have a basic Xamarin.Forms app. Click the Play button to try it out.

Create a Custom Webview

Here going to create a custom webview inherit from webview for debug webview.

CustomWebView.cs

public class CustomWebView : WebView
{
}

Android Implementation

Here, Create a custom renderer for enable debugging in android.

CustomWebViewRenderer.cs

[assembly: ExportRenderer(typeof(CustomWebView), typeof(CustomWebViewRenderer))]
namespace XamWebView.Droid
{
public class CustomWebViewRenderer:WebViewRenderer
{
public CustomWebViewRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
global::Android.Webkit.WebView.SetWebContentsDebuggingEnabled(true);
}
}
}

iOS Implementation
 
Here, Create a custom renderer for enabling the Debugging in Webview.
 
CustomWebViewRenderer.cs

[assembly: ExportRenderer(typeof(CustomWebView), typeof(CustomWebViewRenderer))]
namespace PDFPOC.iOS
{
public class CustomWebViewRenderer : WebViewRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (NativeView != null && e.NewElement != null)
{
var webView = NativeView as UIWebView;
if (webView == null)
return;
webView.ScalesPageToFit = true;
}
}
}
}

Consuming the CustomWebview
 
Here, consume the Custom Webview in your xaml

Add Namespace

xmlns:controls="clr-namespace:XamWebView"
view raw MyWebPage.xaml hosted with ❤ by GitHub

Add your Custom Webview

MyWebPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:controls="clr-namespace:XamWebView"
x:Class="XamWebView.MainPage">
<controls:CustomWebView x:Name="webView" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
</controls:CustomWebView>
</ContentPage>
view raw XamWebView.Xaml hosted with ❤ by GitHub

MyWebPage.xaml.cs

namespace XamWebView
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
webView.Source = "https://xamarinmonkeys.blogspot.com/";
}
}
}

Android

Note: Must add the following line in your webview renderer

global::Android.Webkit.WebView.SetWebContentsDebuggingEnabled(true);

Go to Chrome on your Machine then inspect any webpage. Then click three dots, then go to More tools > Remote Devices. Now you can see at the bottom device setting URL you can click that URL.

chrome://inspect/#devices

Run your app in Emulator

Now go to the webpage you able to see your webpage link then click inspect.

Finally, you can inspect your webview.

iOS

Note: Check your iOS simulator have web inspector option enable it.
Go to Settings > Safari > Advanced, and toggling the Web Inspector option on.

Next, you must also enable developer tools in Safari. Go to Safari > Preferences in the menu bar. Click on the Advanced tab and then enable the Show Develop menu option at the bottom.

Finally, Run your app the go-to Safari, Click on Develop in the menu bar and hover over the dropdown option that is your iOS device's name to show a list of webview instances running on your iOS device

 
I hope you have understood how to enable debugging in webview in Xamarin.Forms.
 
Thanks for reading. Please share your comments and feedback. Happy Coding :)
Delpin Susai Raj Friday, 19 June 2020

Xamarin.Forms - Enable Default Zooming in Webview

In this blog post, you will learn how to enable webview default zooming in xamarin forms.

Introduction
 
Xamarin.Forms code runs on multiple platforms, each of which has its own filesystem. This means that reading and writing files are most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.

Prerequisites
  • Visual Studio 2017 or later (Windows or Mac)
Setting up a Xamarin.Forms Project
 
Start by creating a new Xamarin.Forms project. You will learn more by going through the steps yourself.
 
Create a new or existing Xamarin forms (.Net standard) Project with Android and iOS Platform.

Choose the Mobile App (Xamarin. forms) project under C# and Mobile.
 
Name your app. You probably want your project and solution to use the same name as your app. Put it on your preferred location for projects and click "Create".
 
Now, select the blank app and target platforms - Android, iOS, and Windows (UWP).
 
Subsequently, go to the solution. In there, you get all the files and sources of your project (.NET Standard). Now, select the XAML page and double-click to open the MainPage.Xaml page.
 
You now have a basic Xamarin.Forms app. Click the Play button to try it out.

Create a Custom Webview

Here going to create a custom webview inherit from webview for custom rendering to enable zooming.

CustomWebView.cs

public class CustomWebView : WebView
{
}

Android Implementation
 
There are two ways in android.

1. Use Platform Specific code.

Following code snippets enable the default zooming in webview.

MyWebView.xaml.cs

if (Device.RuntimePlatform == Device.Android)
{
webView.On<Android>().EnableZoomControls(true);
webView.On<Android>().DisplayZoomControls(true);
}

2. Custom Renderer

Here, Create a custom renderer for enabling zooming in android.

CustomWebViewRenderer.cs

[assembly: ExportRenderer(typeof(CustomWebView), typeof(CustomWebViewRenderer))]
namespace PDFPOC.Droid
{
public class CustomWebViewRenderer : WebViewRenderer
{
public CustomWebViewRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
var pdfView = Element as CustomWebView;
Control.Settings.AllowUniversalAccessFromFileURLs = true;
Control.Settings.SetSupportZoom(true);
Control.Settings.BuiltInZoomControls = true;
Control.Settings.DisplayZoomControls = true;
}
}
}
}

iOS Implementation
 
Here, Create a custom renderer for enabling the webview default zooming in iOS.
 
CustomWebViewRenderer.cs

[assembly: ExportRenderer(typeof(CustomWebView), typeof(CustomWebViewRenderer))]
namespace PDFPOC.iOS
{
public class CustomWebViewRenderer : WebViewRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (NativeView != null && e.NewElement != null)
{
var webView = NativeView as UIWebView;
if (webView == null)
return;
webView.ScalesPageToFit = true;
}
}
}
}

Consuming the CustomWebview
 
Here, consume the Custom Webview in your xaml

Add Namespace

xmlns:controls="clr-namespace:PDFPOC.Controls"
view raw MyWebPage.xaml hosted with ❤ by GitHub

Add your Custom Webview

MyWebPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:controls="clr-namespace:PDFPOC.Controls"
mc:Ignorable="d"
x:Class="PDFPOC.MyWebPage">
<ContentPage.Content>
<StackLayout>
<controls:CustomWebView x:Name="webView" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"/>
</StackLayout>
</ContentPage.Content>
</ContentPage>
view raw MyWebPage.xaml hosted with ❤ by GitHub

MyWebPage.xaml.cs

public partial class MyWebPage : ContentPage
{
public MyWebPage()
{
InitializeComponent();
webView.Source = "https://xamarinmonkeys.blogspot.com/";
}
}

Click the "Play" button to try it out

Android 
You can test zoom by emulator also use Shift + ctrl + Left click and mouse move

iOS 
Simulator also support zoom use Alt + Left click and mouse move

Wow, It's working.😍
 
I hope you have understood how to enable webview default zooming in Xamarin.Forms.
 
Thanks for reading. Please share your comments and feedback.

Happy Coding 🙌
Delpin Susai Raj Monday, 15 June 2020

Xamarin.Forms - Working with PDFView and Pinch Zoom

In this blog post, you will learn how to implement PDF view with pinch-zoom in xamarin forms.

Introduction
 
Xamarin.Forms code runs on multiple platforms, each of which has its own filesystem. This means that reading and writing files are most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.

PDF Viewer


The Problem(Android)

PDFView doesn't support the default webview in android xamarin forms.

Solution

PDFView is the biggest issue in android webview. I solved this problem by using google drive viewer and google doc viewer.
there is another way to view pdf files using pdfjs. but pdfjs doesn't support pinch zoom.


Note: The pdf URL must be extension.PDF and public.

Prerequisites
  • Visual Studio 2017 or later (Windows or Mac)
Setting up a Xamarin.Forms Project
 
Start by creating a new Xamarin.Forms project. You will learn more by going through the steps yourself.
 
Create a new or existing Xamarin forms (.Net standard) Project with Android and iOS Platform.

Choose the Mobile App (Xamarin. forms) project under C# and Mobile.
 
Name your app. You probably want your project and solution to use the same name as your app. Put it on your preferred location for projects and click "Create".
 
Now, select the blank app and target platforms - Android, iOS, and Windows (UWP).
 
Subsequently, go to the solution. In there, you get all the files and sources of your project (.NET Standard). Now, select the XAML page and double-click to open the MainPage.Xaml page.
 
You now have a basic Xamarin.Forms app. Click the Play button to try it out.

Create a Custom Webview

Here going to create a custom webview inherit from webview for custom rendering. I'm going to create two bindable properties following.
  1. Uri
  2. IsPDF
PDFView.cs
public class PDFView: WebView
{
public static readonly BindableProperty UriProperty = BindableProperty.Create(propertyName: "Uri",
returnType: typeof(string),
declaringType: typeof(PDFView),
defaultValue: default(string));
public string Uri
{
get { return (string)GetValue(UriProperty); }
set { SetValue(UriProperty, value); }
}
public static readonly BindableProperty IsPDFProperty = BindableProperty.Create(propertyName: "IsPDF",
returnType: typeof(bool),
declaringType: typeof(PDFView),
defaultValue: default(bool));
public bool IsPDF
{
get { return (bool)GetValue(IsPDFProperty); }
set { SetValue(IsPDFProperty, value); }
}
}
view raw PDFView.cs hosted with ❤ by GitHub

Android Implementation
 
Here, Create a custom renderer for webview. for android the webview doesn't support pdf file preview. so I'm going to view pdf files Google drive viewer.
Note: The Url must be an extension .PDF and public. 

https://drive.google.com/viewerng/viewer?embedded=true&url=" + "your url";
view raw google.json hosted with ❤ by GitHub

Another Solution

https://docs.google.com/gview?embedded=true&amp;url=" + "your url";
view raw google.json hosted with ❤ by GitHub

PDFViewRenderer.cs

[assembly: ExportRenderer(typeof(PDFView), typeof(PDFViewRenderer))]
namespace PDFPOC.Droid
{
public class PDFViewRenderer : WebViewRenderer
{
public PDFViewRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
var pdfView = Element as PDFView;
Control.Settings.AllowUniversalAccessFromFileURLs = true;
if (pdfView.IsPDF)
{
var url = "https://drive.google.com/viewerng/viewer?embedded=true&url=" + pdfView.Uri;
Control.LoadUrl(url);
}
else
{
Control.LoadUrl(pdfView.Uri);
}
}
}
}
}

iOS Implementation
 
Here, Create a custom renderer for webview to load pdf files in webview.
 
PDFViewRenderer.cs

[assembly: ExportRenderer(typeof(PDFView), typeof(PDFViewRenderer))]
namespace PDFPOC.iOS
{
public class PDFViewRenderer : WebViewRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (NativeView != null && e.NewElement != null)
{
var pdfControl = NativeView as UIWebView;
if (pdfControl == null)
return;
pdfControl.ScalesPageToFit = true;
}
}
}
}

Consuming the CustomWebview
 
Here, consume the Custom Webview in your xaml

Add Namespace

xmlns:controls="clr-namespace:PDFPOC.Controls"
view raw PDFViewer.xaml hosted with ❤ by GitHub

Add your Custom Webview

PDFView.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:controls="clr-namespace:PDFPOC.Controls"
mc:Ignorable="d"
x:Class="PDFPOC.PDFViewer">
<ContentPage.Content>
<StackLayout BackgroundColor="Green"
HorizontalOptions="CenterAndExpand"
VerticalOptions="CenterAndExpand">
<controls:PDFView x:Name="pdfView"
IsPDF="True"
HeightRequest="1000"
WidthRequest="1000"
VerticalOptions="FillAndExpand" />
</StackLayout>
</ContentPage.Content>
</ContentPage>
view raw PDFView.xaml hosted with ❤ by GitHub

PDFView.xaml.cs

public partial class PDFViewer : ContentPage
{
string url = "http://media.wuerth.com/stmedia/shop/catalogpages/LANG_it/1637048.pdf";
public PDFViewer()
{
InitializeComponent();
if (Device.RuntimePlatform == Device.Android)
{
pdfView.Uri = url;
pdfView.On<Android>().EnableZoomControls(true);
pdfView.On<Android>().DisplayZoomControls(false);
}
else
pdfView.Source = url;
}
}
view raw PDFView.xaml.cs hosted with ❤ by GitHub

Click the "Play" button to try it out

Android 
You can test Pinch zoom by emulator also use Shift + ctrl + Left click and mouse move

iOS 
Simulator also supports pinch-zoom use Alt + Left click and mouse move

Wow, It's working.
I hope you have understood how to implement PDF view with pinch-zoom in Xamarin.Forms.
 
Thanks for reading. Please share your comments and feedback. Happy Coding :)
Delpin Susai Raj Monday, 3 February 2020

Xamarin.Forms - Use BindableProperty in Effects

In this blog, you will learn how to use BindableProperty Effects in Xamarin.Forms


Tint Color Sample -  https://xamarinmonkeys.blogspot.com/2020/02/xamarinforms-tint-image-using-effects.html

(The Blog about change Image color at Runtime using Tint Color)


Introduction

Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files are most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.

Tint Image

TintImage is used for change image color at runtime with the help of effects, you can achieve with custom render also. Tint images mainly used to reduce the usage of the images.

BindableProperty

Attached properties can be used to define effect parameters that respond to runtime property changes. This article demonstrates using attached properties to pass parameters to an effect and changing a parameter at runtime.

Prerequisites
  • Visual Studio 2017 or later (Windows or Mac)
The Problem

We are not able to create a BindableProperty in Effect.

Solution

Create Effect

Now, Create a TintImage class inherit from RoutingEffect for Change image color.

TintImage.cs

public class TintImage: RoutingEffect
{
public Color TintColor { get; private set; }
public TintImage(Color color) : base($"MyCompany.{nameof(TintImage)}")
{
TintColor = color;
}
}
view raw TintImage.cs hosted with ❤ by GitHub
Create Static Class

Here, I'm Going to create a Static Class for creating BindableProperty to my Effect.

TintImageEffect.cs

public static class TintImageEffect
{
public static BindableProperty TintColorProperty =
BindableProperty.CreateAttached("TintColor",
typeof(Color),
typeof(TintImageEffect),
Color.Default,
propertyChanged: OnTintColorPropertyPropertyChanged);
public static Color GetTintColor(BindableObject element)
{
return (Color)element.GetValue(TintColorProperty);
}
public static void SetTintColor(BindableObject element, Color value)
{
element.SetValue(TintColorProperty, value);
}
static void OnTintColorPropertyPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
AttachEffect(bindable as Image, (Color)newValue);
}
static void AttachEffect(Image element, Color color)
{
var effect = element.Effects.FirstOrDefault(x => x is TintImage) as TintImage;
if (effect != null)
{
element.Effects.Remove(effect);
}
element.Effects.Add(new TintImage(color));
}
}
Android Implementation

Here, Implement Platform Effects for TintImage at Runtime.

TintImageImpl.cs

[assembly: ExportEffect(typeof(TintImageImpl), nameof(XamarinStudy.Common.Controls.TintImage))]
namespace XamarinStudy.Droid.Effects
{
public class TintImageImpl: PlatformEffect
{
protected override void OnAttached()
{
try
{
var effect = (XamarinStudy.Common.Controls.TintImage)Element.Effects.FirstOrDefault(e => e is XamarinStudy.Common.Controls.TintImage);
if (effect == null || !(Control is ImageView image))
return;
var filter = new PorterDuffColorFilter(effect.TintColor.ToAndroid(), PorterDuff.Mode.SrcIn);
image.SetColorFilter(filter);
}
catch (Exception ex)
{
}
}
protected override void OnDetached() { }
}
}
iOS Implementation

Here, Implement Platform Effects for TintImage at Runtime.

TintImageImpl.cs

[assembly: ExportEffect(typeof(XamarinStudy.iOS.Effects.TintImageImpl), nameof(TintImage))]
namespace XamarinStudy.iOS.Effects
{
public class TintImageImpl: PlatformEffect
{
protected override void OnAttached()
{
try
{
var effect = (XamarinStudy.Common.Controls.TintImage)Element.Effects.FirstOrDefault(e => e is XamarinStudy.Common.Controls.TintImage);
if (effect == null || !(Control is UIImageView image))
return;
image.Image = image.Image.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate);
image.TintColor = effect.TintColor.ToUIColor();
}
catch (Exception ex)
{
}
}
protected override void OnDetached() { }
}
}
Create ViewModel

Now, Create a Property for Binding the TintColor to View. and Create ChangeColorCommand For Change image color at runtime.

MainPageViewModel.cs

public class MainPageViewModel:BaseViewModel
{
#region Fields
private Command _changeColorCommand;
private Color _imageColor;
#endregion
#region Constructor
public MainPageViewModel()
{
_imageColor = Color.Gray;
}
#endregion
#region Properties
public Color ImageColor
{
get { return _imageColor; }
set { Set(() => ImageColor, ref _imageColor, value); }
}
public Command ChangeColorCommand
{
get
{
return _changeColorCommand ?? (_changeColorCommand = new Command(() =>
{
if(this.ImageColor==Color.Black)
{
this.ImageColor = Color.Gray;
}
else
{
this.ImageColor = Color.Black;
}
}));
}
}
#endregion
}
Consuming the TintImage

Now, Use the TintImage Effect in your XAML code.

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:behaviors="clr-namespace:XamarinStudy.Common.Behaviors"
xmlns:converters="clr-namespace:XamarinStudy.Common.Converters"
xmlns:Effects="clr-namespace:XamarinStudy.Common.Controls"
x:Class="XamarinStudy.MainPage" Title="Effects">
<StackLayout Margin="10,30,10,0" Spacing="20">
<Image Source="banner.png"/>
<Image Source="favicon.png" Effects:TintImageEffect.TintColor="{Binding ImageColor}">
</Image>
</StackLayout>
</ContentPage>
view raw MainPage.xaml hosted with ❤ by GitHub
Click the "Play" button to try it out.

Wow, It's Working.😍

I hope you have understood how to use BindableProperty Effects in Xamarin.Forms.

Thanks for reading. Please share your comments and feedback. Happy Coding 🙌
Delpin Susai Raj Sunday, 2 February 2020

Xamarin.Forms - Tint Image Color Using Effects

In this blog post, you will learn how to Change image color using Tint Color Effects in Xamarin.Forms.

Introduction

Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files are most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.

Tint Color

TintImage is used for change image color at runtime with the help of effects, you can achieve with custom render also. Tint images mainly used for reducing the usage of the images.

Prerequisites
  • Visual Studio 2017 or later (Windows or Mac)
Create TintImage

The Actual Image Color is Blue 

Now, Create a TintImage class inherit from RoutingEffect for Change image color.

TintImage.cs

public class TintImage: RoutingEffect
{
public Color TintColor { get; private set; }
public TintImage(Color color) : base($"MyCompany.{nameof(TintImage)}")
{
TintColor = color;
}
}
view raw TintImage.cs hosted with ❤ by GitHub
Android Implementation

Here, Implement Platform Effects for TintImage at Runtime.

TintImageImpl.cs

[assembly: ExportEffect(typeof(TintImageImpl), nameof(XamarinStudy.Common.Controls.TintImage))]
namespace XamarinStudy.Droid.Effects
{
public class TintImageImpl: PlatformEffect
{
protected override void OnAttached()
{
try
{
var effect = (XamarinStudy.Common.Controls.TintImage)Element.Effects.FirstOrDefault(e => e is XamarinStudy.Common.Controls.TintImage);
if (effect == null || !(Control is ImageView image))
return;
var filter = new PorterDuffColorFilter(effect.TintColor.ToAndroid(), PorterDuff.Mode.SrcIn);
image.SetColorFilter(filter);
}
catch (Exception ex)
{
}
}
protected override void OnDetached() { }
}
}
iOS Implementation

Here, Implement Platform Effects for TintImage at Runtime.

TintImageImpl.cs

[assembly: ExportEffect(typeof(XamarinStudy.iOS.Effects.TintImageImpl), nameof(TintImage))]
namespace XamarinStudy.iOS.Effects
{
public class TintImageImpl: PlatformEffect
{
protected override void OnAttached()
{
try
{
var effect = (XamarinStudy.Common.Controls.TintImage)Element.Effects.FirstOrDefault(e => e is XamarinStudy.Common.Controls.TintImage);
if (effect == null || !(Control is UIImageView image))
return;
image.Image = image.Image.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate);
image.TintColor = effect.TintColor.ToUIColor();
}
catch (Exception ex)
{
}
}
protected override void OnDetached() { }
}
}
Consuming the TintImage

Now, Use the TintImage Effect in your XAML code.

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:behaviors="clr-namespace:XamarinStudy.Common.Behaviors"
xmlns:converters="clr-namespace:XamarinStudy.Common.Converters"
xmlns:Effects="clr-namespace:XamarinStudy.Common.Controls"
x:Class="XamarinStudy.MainPage" Title="Effects">
<StackLayout Margin="10,30,10,0" Spacing="20">
<Image Source="banner.png"/>
<Image Source="favicon.png" Effects:TintImageEffect.TintColor="Green">
</Image>
</StackLayout>
</ContentPage>
view raw MainPage.xaml hosted with ❤ by GitHub
Click the "Play" button to try it out.

Wow, It's Working.😍

I hope you have understood how to Change image color using Tint Color Effects in Xamarin.Forms.

Thanks for reading. Please share your comments and feedback. Happy Coding 😀🙌
Delpin Susai Raj Monday, 27 January 2020

Xamarin.Forms - Bottom TabbedPage in Android

In this blog post, you will learn how to Change Tabbed Page Top to Bottom for Android Device in Xamarin.Forms.

Introduction

Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.


Prerequisites
  • Visual Studio 2017 or later (Windows or Mac)
  • Xamarin.Forms 3.1 Later
The Problem

TabbedPage Native Behaviour

Android   - Top
iOS           - Bottom


MyTabbedPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:pages="clr-namespace:XMonkey.Views"
x:Class="XMonkey.Views.XMonkeyTabbedPage">
<!--Pages can be added as references or inline-->
<pages:BlogFeedPage Title="BlogFeedPage" IconImageSource="tab_feed.png"/>
<pages:AboutPage Title="AboutPage" IconImageSource="tab_about.png"/>
</TabbedPage>

Solution

Add android platform-specific code in TabbedPage

Namespace

xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"
android:TabbedPage.ToolbarPlacement="Bottom"
MyTabbedPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"
android:TabbedPage.ToolbarPlacement="Bottom"
xmlns:pages="clr-namespace:XMonkey.Views"
x:Class="XMonkey.Views.XMonkeyTabbedPage">
<!--Pages can be added as references or inline-->
<pages:BlogFeedPage Title="BlogFeedPage" IconImageSource="tab_feed.png"/>
<pages:AboutPage Title="AboutPage" IconImageSource="tab_about.png"/>
</TabbedPage>
Or C# Code Behind

MyTabbedPage.xaml.cs

using Xamarin.Forms;
using Xamarin.Forms.PlatformConfiguration;
using Xamarin.Forms.PlatformConfiguration.AndroidSpecific;
using Xamarin.Forms.Xaml;
namespace XMonkey.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class XMonkeyTabbedPage : Xamarin.Forms.TabbedPage
{
public XMonkeyTabbedPage()
{
InitializeComponent();
On<Android>().SetToolbarPlacement(ToolbarPlacement.Bottom);
}
}
}
Click the "Play" button to try it out.

Wow, It's Working.😍

I hope you have understood how to Change TabbedPage Top to Bottom for Android Device in Xamarin.Forms.

Thanks for reading. Please share your comments and feedback. Happy Coding 😀