Playing with keyboard shortcuts is very interesting and reduce the head-ache of using mouse again and again while programming with visual studio IDE. Actually, keyboard shortcuts also enhance your productivity and make your programming life easy and convenient. So, Here i am share a list of visual studio keyboard with different platform

Visual Studio For Windows :

Here you can find about Visual studio shortcuts for windows



Reference from : https://code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdf

VisualStudio For Mac :

Here you can find about Visualstudio shortcuts for Mac



Reference from : https://code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdf

VisualStudio For Linux :

Here you can find about Visualstudio shortcuts for Linux



Reference from : https://code.visualstudio.com/shortcuts/keyboard-shortcuts-linux.pdf

Issue:

In Xamarin Form , While adding reference Sqlit PCL or PCl storage ,etc . if you get following error

Severity Code Description Project File Line Suppression State
Error Unable to resolve dependencies. 'Xamarin.Android.Support.v4 23.0.1.3' is not compatible with 'Xamarin.Android.Support.Design 23.0.1.3 constraint: Xamarin.Android.Support.v4 (>= 23.0.1.3)', 'Xamarin.Forms 2.2.0.45 constraint: Xamarin.Android.Support.v4 (= 23.3.0)'. 0.

Just follow below steps for resolution

Step 1:

Close Visual Studio

Step 1:

Navigate following Folder C:\Users\<username>\AppData\Local\Xamarin
and Remove “ Zib “ Folder (it will re-create automatically while build solution )

Step 2:

Right Click on Your Solution /Project ➔ manage nuget Package➔ Click Update ➔ Update Xamarin Form like below


Step 3:

Restart Visual studio⇒Open project ==> Clean Solution and build

Step 4:

Add your Nuget package Now .



After upgrade xamarin Form , if you get below issue
Issue :

obj\Release\android\src\mono\android\support\v7\internal\widget\ActivityChooserModel_OnChooseActivityListenerImplementor.java:8: error: package android.support.v7.internal.widget.ActivityChooserModel does not exist

android.support.v7.internal.widget.ActivityChooserModel.OnChooseActivityListener
^
obj\Release\android\src\mono\android\support\v7\internal\widget\ActivityChooserModel_OnChooseActivityListenerImplementor.java:28: error: package android.support.v7.internal.widget does not exist

public boolean onChooseActivity (android.support.v7.internal.widget.ActivityChooserModel p0, android.content.Intent p1)
^
obj\Release\android\src\mono\android\support\v7\internal\widget\ActivityChooserModel_OnChooseActivityListenerImplementor.java:33: error: package android.support.v7.internal.widget does not exist

private native boolean n_onChooseActivity (android.support.v7.internal.widget.ActivityChooserModel p0, android.content.Intent p1);
^
obj\Release\android\src\mono\android\support\v7\internal\widget\FitWindowsViewGroup_OnFitSystemWindowsListenerImplementor.java:8: error: package android.support.v7.internal.widget.FitWindowsViewGroup does not exist

android.support.v7.internal.widget.FitWindowsViewGroup.OnFitSystemWindowsListener
^
obj\Release\android\src\mono\android\support\v7\internal\widget\ViewStubCompat_OnInflateListenerImplementor.java:8: error: package android.support.v7.internal.widget.ViewStubCompat does not exist

android.support.v7.internal.widget.ViewStubCompat.OnInflateListener
^
obj\Release\android\src\mono\android\support\v7\internal\widget\ViewStubCompat_OnInflateListenerImplementor.java:28: error: package android.support.v7.internal.widget does not exist

public void onInflate (android.support.v7.internal.widget.ViewStubCompat p0, android.view.View p1)

obj\Release\android\src\mono\android\support\v7\internal\widget\ViewStubCompat_OnInflateListenerImplementor.java:33: error: package android.support.v7.internal.widget does not exist

Resolution :

Step 1:

go to following folder

C:\Users\<username>\AppData\Local\Xamarin

Step 2:

clear all the folder and files.

Step 3:

Rebuild solution

Xamarin is great technology for develop cross mobile application development. You can create, Build and Debug iOS application in windows machine using Visual Studio. In this article, I will explain what are the way to debug and build Xamarin.iOS application in windows machine. 

Xamarin and Microsoft giving very great solution for create, build and debug IOS application on windows machine using visual studio. but, it cannot do this alone, an IOS app cannot be created without apple Compiler, and it cannot be deployed without apple certificate and code-signing tools. Read below I will explain about software requirement and steps. 

Software Requirement

You can install following software from Windows and Mac machine.
Build and Debug Xamarin.iOS Application on Windows Machine

Windows Machine

It greatly helps if your machines are physically near each other, since when you build and run on Windows, the iOS Simulator will load on your Mac. 

Build and Debug iOS Application

I have explained about basic xamarin.Form application creation in my previous article .You can refer and create basic xamarin.iOS or xamarin.Form application
After create, Visual Studio will prompt you to prepare your Mac to be the Xamarin build host using below 3 steps. 

Mac Machine

Step 1: On the mac Machine, Select “System Preferences” 

Build and Debug Xamarin.iOS Application on Windows Machine


Step 2: In System Preferences, Click on “Sharing” 

Build and Debug Xamarin.iOS Application on Windows Machine 

Step 3: In Sharing, Turn on Remote Login and Change Allow access to All Users or Only these users and add a user. 

Build and Debug Xamarin.iOS Application on Windows Machine

Windows Machine

Step 1: In the Visual Studio, you can click on “Connection Indicator “


Build and Debug Xamarin.iOS Application on Windows Machine


Step 2: You Can Select your mac name from mac agent window and click on “connect”. 

Build and Debug Xamarin.iOS Application on Windows Machine 

Step 3: you can enter mac username and password and Click on Login .


Build and Debug Xamarin.iOS Application on Windows Machine 

After connection, Connection indicator color will change to green, If its connection is very less bandwidth means it will change to orange color (it’s not recommended for debug application) 

Build and Debug Xamarin.iOS Application on Windows Machine 

Your app will compile and execute, but you won’t see it running on Windows. Instead, you’ll see it on your Mac build host. 


iOS Simulator Remoting

The Evolve 2016 Conference, Xamarin announced iOS Simulator remoting that will soon allow you to interact with apps running in Apple iOS simulator as through the Simulator were running on your Windows Machine.

iOS Simulator Remoting also you need follow above all the steps and below steps as well 

Windows Machine

Step 1: Download the installer and install on your Windows computer
Step 2: After install, In Visual Studio go to Tools > Options > Xamarin > iOS Settings and tick the box for Remote Simulator to Windows:


Build and Debug Xamarin.iOS Application on Windows Machine


Output


Now build and run solution and ios simulator will open in windows machine 

Build and Debug Xamarin.iOS Application on Windows Machine


Issues and Resolution


Issue 1: 


Error Cannot resolve reference: C:/Program Files (x86)/Reference Assemblies/Microsoft/Framework/Xamarin.iOS/v1.0/Facades/System.IO.FileSystem.Watcher.dll I1Vector.iOS

Resolution:

This issue happened because of different versions of Xamarin.iOS on Windows Machine and mac machine. After updating xamarin.ios, this problem will get resolved.
How to Check xamarin.iOS Version Number ?
In Windows Machine, Go to Visual Studio ➔ Help ➔ About Microsoft Visual Studio

In mac machine, Go to Xamarin Studio ➔ Select Xamarin Studio Menu ➔ Click About Xamarin Studio ➔ click Show details





How to Update Xamarin.Ios in Mac and Windows?

Mac Machine:

Go to xamarin Studio and Click on “Check for Update” and Update

Windows Machine:

Go to Visual Studio ➔ Tools ➔ extensions and updates.
Some time it won’t available in update list. if it’s not available, go to control Panel➔Uninstall program ➔ Select Visual studio ➔ and Click Change option and update
Issue 2: Mac Agent can't connect after update:
Starting connection to mac machine. Xcode license must be accepted in order to be connected and working against the Mac
 


Solution: 


Go to Xcode ➔ Preferences ➔ Location
Check if "Command Line Tool" set or Select XCode version
Run sudo xcodebuild -license in terminal
Xcode license must be accepted press Space bar and press q
Issue 3: iOS simulator not display on Windows 

Solution 1: Check Windows and Mac firewall rule or disable and test application. 


Solution 2: 


You need make sure xcode installed in Application Folder. If it’s not ,you need to change in visual studio Apple SDK path


Build and Debug Xamarin.iOS Application on Windows Machine





Microsoft changed from MSDN Subscription to Visual Studio Subscription and also changed Url into https://my.visualstudio.com/

Today I have logged into MSDN but its showed like below



Watch the quick video https://my.visualstudio.com/getstarted?campaign=o~mpsa~migrate~msdn_benefit

New Look MSDN

The State Persistence between app restarts and when suspending/resuming. The values in the Properties dictionary are only stored when the app goes to Start(OnStart), sleep(OnSleep), resime(OnResume) method. I have tried with application crashes out with an exception properties it’s not saved.

Xamarin.Forms plugin which uses the native settings management. Refer below image different platform state persistence.

This can be accessed from anywhere in your Xamarin.Forms code using Application.Current.Properties .The syntax look like below

Application.Current.Properties [ <StringKey> ] = <Assign Object Type Value >;

Application different Action:

Refer below code for different xamarin Form application property action like assign,read,delete,Clear value.

Set value:

Key value always should be string and Value should be object (any type)

Application.Current.Properties["Email"] = "jssuthahar@gmail.com";

Get Value:

While getting the value, check if its available or not and always convert object type into your specific variable type.

if (Application.Current.Properties.ContainsKey("Email"))
{
var emailId = Convert.ToString(Application.Current.Properties["Email"]);
}
If you want to reuse the same key value or update value. just assign value like below
Application.Current.Properties["Email"] = "nikhil@msdn.com";

The properties dictionary can only serialize primitive types for storage. Attempting to store other types like List<int> can fail silently

Remove Value:

If you want to remove application key and value, try below code
if (Application.Current.Properties.ContainsKey("Email"))
{
Application.Current.Properties.Remove("Email");
}

Clear Value:

You can clear all the application property value
Application.Current.Properties.Clear();

If you have question type(?) ask in Comments Box

Issue:

Android Emulator Keyboard not displaying and not able to Type using hard keyboard

Solution:

Try to follow below steps in Android Emulator

Open Android Emulator

Click on Setting

Select Language & Input



Go to the "Keyboard & Input Methods”.

Select Default

Disable the Hardware Keyboard by switching the hardware keyboard from on to off. Like below screen

Problem:

I have installed VS 2015 with update 3 and created Blank xamarin Form application. I can able to build the application but when I run android app with VS emulator is running but not starting my app and not getting any error message

Solution:

Just follow below 5 steps for resolution
Open the Hyper-V manager
Select the Android emulator you are trying to use
Right-click and select settings
Expand processor and select Compatibility
Set checkbox “Migrate to a physical computer with a different processor version”

Input Validation in Xamarin Forms Behaviors


Introduction:

Xamarin.Forms behaviors are created by deriving from the Behavior or Behavior<T> class, where T is the type of the control (Entry, DateTime, etc) to which the behavior should apply.

In this article I will demonstrates how to create and consume Xamarin.Forms behaviors and Input Validation using xamarin Forms Behaviors.

Why We Need Behaviors?

Normally we will write validation code into the code-behind because it directly interacts with the API of the control so that we can create Behaviors and reuse into the different control. We can be used to provide a full range of functionality to controls, like below
  • Number Validation
  • Date Validation
  • Email Validation
  • Password Validation
  • Compare Validation
  • Building and Running the Application
The Creating xamarin.Forms Behaviors application is as follow below steps

Step 1 - Create new Xamarin Form Application

Let's start with creating a new Xamarin Forms Project in Visual Studio.

Open Run - Type Devenev.Exe and enter - New Project (Ctrl+Shift+N) - select Blank Xaml App (Xamarin.Forms Portable) template



You can find my previous article for more about create new xamarin.Form application from Here.

Step 2 – Create new class and inherits from the Behavior:

Create a new class and inherits from the Behavior or Behavior<T> class .We can add behavior to any control so you can specify your control name instead of T.


Step 2 –Override Behavior class method:

We need to override OnAttachedTo and OnDetachingFrom method from our validation class



The OnAttachedTo method is fired immediately after the behavior is attached to a control. This can be used to register event handlers or perform other setup that's required to support the behavior functionality.

The OnDetachingFrom method is fired when the behavior is removed from the control. This method receives a reference to the control to which it is attached, and is used to perform any required cleanup.

Step 3 –Validation Behavior Class:

3.1 – PasswordValidationBehavior:

The below code is password validation behaviors. Password rule should contain at least 8 character, 1 numeric, 1 lowercase, 1 uppercase, 1 special character [eg: No1C#cornar]

The password validation behavior added into Entry control. We can re-use this behavior to Entry control.

using System.Text.RegularExpressions;
using Xamarin.Forms;

namespace DevenvExeBehaviors
{
public class PasswordValidationBehavior : Behavior<Entry>
{
const string passwordRegex = @"^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$";

protected override void OnAttachedTo(Entry bindable)
{
bindable.TextChanged += HandleTextChanged;
base.OnAttachedTo(bindable);
}
void HandleTextChanged(object sender, TextChangedEventArgs e)
{
bool IsValid = false;
IsValid = (Regex.IsMatch(e.NewTextValue, passwordRegex));
((Entry)sender).TextColor = IsValid ? Color.Default : Color.Red;
}

protected override void OnDetachingFrom(Entry bindable)
{
bindable.TextChanged -= HandleTextChanged;
base.OnDetachingFrom(bindable);
}
}
}

3.2 - Date Validation Behaviors:

The below code is Date of birth validation behaviors. I used a date picker and restricted the max date to be 100 years from the current day and min date to be 1.

The DOB validation behavior added into DatePicker control. We can re-use this behavior to Date Picker control.

using System;
using Xamarin.Forms;

namespace DevenvExeBehaviors
{
class DateValidationBehavior : Behavior<DatePicker>
{
protected override void OnAttachedTo(DatePicker datepicker)
{
datepicker.DateSelected += Datepicker_DateSelected;
base.OnAttachedTo(datepicker);
}

private void Datepicker_DateSelected(object sender, DateChangedEventArgs e)
{
DateTime value = e.NewDate;
int year = DateTime.Now.Year;
int selyear = value.Year;
int result = selyear - year;
bool isValid=false;
if(result <=100 && result >0)
{
isValid = true;
}
((DatePicker)sender).BackgroundColor = isValid ? Color.Default : Color.Red;
}

protected override void OnDetachingFrom(DatePicker datepicker)
{
datepicker.DateSelected -= Datepicker_DateSelected;
base.OnDetachingFrom(datepicker);
}
}
}

3.3 - EmailValidation Behaviors

The below code is Email validation behaviors. Email validation behavior added into Entry control. We can re-use this behavior to Entry control.

using System;
using System.Text.RegularExpressions;
using Xamarin.Forms;

namespace DevenvExeBehaviors
{
public class EmailValidatorBehavior : Behavior<Entry>
{
const string emailRegex = @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
@"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$";

protected override void OnAttachedTo(Entry bindable)
{
bindable.TextChanged += HandleTextChanged;
base.OnAttachedTo(bindable);
}
void HandleTextChanged(object sender, TextChangedEventArgs e)
{
bool IsValid = false;
IsValid = (Regex.IsMatch(e.NewTextValue, emailRegex, RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)));
((Entry)sender).TextColor = IsValid ? Color.Default : Color.Red;
}

protected override void OnDetachingFrom(Entry bindable)
{
bindable.TextChanged -= HandleTextChanged;
base.OnDetachingFrom(bindable);
}
}
}

3.4 - Number Validation

The below code is Number validation behaviors. The Entry box will allow only numeric value.

using Xamarin.Forms;

namespace DevenvExeBehaviors
{
public class NumberValidationBehavior : Behavior<Entry>
{
protected override void OnAttachedTo(Entry entry)
{
entry.TextChanged += OnEntryTextChanged;
base.OnAttachedTo(entry);
}

protected override void OnDetachingFrom(Entry entry)
{
entry.TextChanged -= OnEntryTextChanged;
base.OnDetachingFrom(entry);
}

void OnEntryTextChanged(object sender, TextChangedEventArgs args)
{
int result;
bool isValid = int.TryParse(args.NewTextValue, out result);
((Entry)sender).TextColor = isValid ? Color.Default : Color.Red;
}
}
}

Step 4 –Behaviors with Parameter:

You can create multiple property in behaviors class and assign value in xaml controls.

Step 4.1- Max length Behaviors

You can restrict the number of characters in the Entry field as given below,

using Xamarin.Forms;
namespace DevenvExeBehaviors
{
public class MaxLengthValidatorBehavior : Behavior<Entry>
{
public static readonly BindableProperty MaxLengthProperty = BindableProperty.Create("MaxLength", typeof(int), typeof(MaxLengthValidatorBehavior), 0);
public int MaxLength
{
get { return (int)GetValue(MaxLengthProperty); }
set { SetValue(MaxLengthProperty, value); }
}

protected override void OnAttachedTo(Entry bindable)
{
bindable.TextChanged += bindable_TextChanged;
}

private void bindable_TextChanged(object sender, TextChangedEventArgs e)
{
if (e.NewTextValue.Length >= MaxLength)
((Entry)sender).Text = e.NewTextValue.Substring(0, MaxLength); }

protected override void OnDetachingFrom(Entry bindable)
{
bindable.TextChanged -= bindable_TextChanged;
}
}
}

Step 4.2 - Compare Validation:

The CompareValidator control allows you to compare the value entered by the user into an input control, such as a Entry control, with the value entered into another Entry control.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace DevenvExeBehaviors
{

public class CompareValidationBehavior : Behavior<Entry>
{
public static BindableProperty TextProperty = BindableProperty.Create<CompareValidationBehavior, string>(tc => tc.Text, string.Empty, BindingMode.TwoWay);
public string Text
{
get
{
return (string)GetValue(TextProperty);
}
set
{
SetValue(TextProperty, value);
}
}

protected override void OnAttachedTo(Entry bindable)
{
bindable.TextChanged += HandleTextChanged;
base.OnAttachedTo(bindable);
}
void HandleTextChanged(object sender, TextChangedEventArgs e)
{
bool IsValid = false;
IsValid = e.NewTextValue ==Text;
((Entry)sender).TextColor = IsValid ? Color.Default : Color.Red;
}

protected override void OnDetachingFrom(Entry bindable)
{
bindable.TextChanged -= HandleTextChanged;
base.OnDetachingFrom(bindable);
}
}
}

Step 5 – Add Behaviors into Control:

Refer below xaml code for add behaviors into entry box

<Entry x:Name="txtpassword" IsPassword="True" Placeholder="Enter Your Password" >
<Entry.Behaviors>
<local:PasswordValidationBehavior />
</Entry.Behaviors>
</Entry>

Step 6 – Add Multiple Behaviors into Control:

Refer below code for attach multiple behaviors into single entry box and pass parameter value

<Entry IsPassword="True" Placeholder="Enter same as above" >
<Entry.Behaviors>
<local:PasswordValidationBehavior />
<local:CompareValidationBehavior BindingContext="{x:Reference txtpassword}" Text="{Binding Text}"/>
</Entry.Behaviors>
</Entry>

Step 7 -UI Design

You can refer below UI Design for all control and behaviors Design

<?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:local="clr-namespace:DevenvExeBehaviors"
x:Class="DevenvExeBehaviors.MainPage" >
<StackLayout Padding="0,20,0,0">
<Label Text="Name" FontSize="Small" />
<Entry Placeholder="Enter Your Name" />
<Label Text="Age" FontSize="Small" />
<Entry Placeholder="Age" FontSize="Small">
<Entry.Behaviors>
<local:MaxLengthValidatorBehavior MaxLength="2"/>
<local:NumberValidationBehavior/>
</Entry.Behaviors>
</Entry>
<Label Text="DOB" FontSize="Small" />
<DatePicker >
<DatePicker.Behaviors>
<local:DateValidationBehavior/>
</DatePicker.Behaviors>
</DatePicker>
<Label Text="Email" FontSize="Small" />
<Entry Placeholder="Enter Your Email ID" >
<Entry.Behaviors>
<local:EmailValidatorBehavior />
</Entry.Behaviors>
</Entry>
<Label Text="Password" FontSize="Small" />
<Entry x:Name="txtpassword" IsPassword="True" Placeholder="Enter Your Password" >
<Entry.Behaviors>
<local:PasswordValidationBehavior />
</Entry.Behaviors>
</Entry>
<Label Text="Confirm Password" FontSize="Small" />
<Entry IsPassword="True" Placeholder="Enter same as above" >
<Entry.Behaviors>
<local:PasswordValidationBehavior />
<local:CompareValidationBehavior BindingContext="{x:Reference txtpassword}" Text="{Binding Text}"/>
</Entry.Behaviors>
</Entry>
<Label Text="Phone Number" FontSize="Small" />
<Entry Placeholder="Enter 10 digit phone number" >
<Entry.Behaviors>
<local:MaxLengthValidatorBehavior MaxLength="10"/>
<local:NumberValidationBehavior />
</Entry.Behaviors>
</Entry>
</StackLayout>
</ContentPage>

You can download sample source code and run the application .

For Debug your application we need follow below steps

1. Open zenfone Settings and scroll down and click on About link.
2. Scroll down and select Software Information.
3. Click on Build Number 7 times to enable Developer Options.
4. Come back to Settings and scroll down to find Developer Options.



5. Click on Developer Options and enable USB Debugging
6. Go to Visual Studio check your device will visible






Introduction:



OAuth is an Authorization framework that enable application to obtain limited access to user accounts on HTTP service in Facebook, google and Microsoft etc. Nowadays no need to create registration logic alternatively you can choose to use identity provider login. In this case a person signs up for the app using identity provider Login, an account is created for them, and the authentication step is taken care of by identity provider.

In this article I will explain how to implement below oAuth identity provider in xamarin Forms and manage the authentication process in a xamarin Forms application

GOOGLE
FACEBOOK
TWITTER
MICROSOFT
LINKEDIN
GITHUB
FLICKER
YAHOO
DROPBOX


Register Mobile App with Identity Provider:

You can find my previous article for register mobile app with identity provider from here

Step 1: Create New Xamarin.Forms Project:

Let Start create new Xamarin Forms Project in Visual studio
Open Run ➔ Type Devenev.Exe and enter ➔ New Project (Ctrl+Shift+N)➔ select Blank Xamarin.Forms Portable template



It will automatically create multiple project like Portable, Android, iOS, UWP but Here, I will be targeting only Android, as iOS and UWP implementation is similar.

Step 2: Install OAuth Client Components

Xamarin.Auth is a cross-platform SDK for authenticating users and storing their accounts. It includes OAuth authenticators that provide support for consuming identity providers.

Let's add the Xamarin.Auth component for OAuth. We will have to add this in all platform specific projects separately.

Go to Any project (DevEnVExeLogin.Droid) ➔ Components ➔ Right Click Get More Components

If you are not login already, it will show login page.

Next, Search and double-click on Xamarin.Auth component and click on Add to App


Step 3: Create Base Login Page (LoginPage.Xaml)

I have created quick and simple login screen .You can modify as per your requirement
Right Click Portable Class Library ➔ Add New Item ➔ Select Xaml Page(Login Page)
LoginPage.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:local="clr-namespace:DevEnvExeLogin"
x:Class="DevEnvExeLogin.LoginPage">
<StackLayout>
<Entry Placeholder="Username" />
<Entry IsPassword="true" Placeholder="Password" />
<Button Text="Login" HeightRequest="50" />
<Button Text="Google" Clicked="LoginClick" Image="GOOGLE.png" HeightRequest="50"/>
<Button Text="FaceBook" Clicked="LoginClick" Image="FACEBOOK.png" HeightRequest="50"/>
<Button Text="Twitter" Clicked="LoginClick" Image="TWITTER.png" HeightRequest="50"/>
<Button Text="Github" Clicked="LoginClick" Image="GITHUB.png" HeightRequest="50"/>
<Button Text="Yahoo" Clicked="LoginClick" Image="YAHOO.png" HeightRequest="50"/>
<Button Text="DropBox" Clicked="LoginClick" Image="DROPBOX.png" HeightRequest="50"/>
<Button Text="LinkedIn" Clicked="LoginClick" Image="LINKEDIN.png" HeightRequest="50"/>
<Button Text="Flicker" Clicked="LoginClick" Image="FLICKER.png" HeightRequest="40"/>
<Button Text="Twitter" Clicked="LoginClick" Image="MICROSOFT.png" HeightRequest="40"/>
</StackLayout>
</ContentPage>

LoginPage.Xaml.CS

Add LoginClick event in login page code behind file and sender object will return button text name (eg:Facebook,Twitter..etc)

using System;
using Xamarin.Forms;

namespace DevEnvExeLogin
{
public partial class LoginPage : ContentPage
{
public LoginPage()
{
InitializeComponent();
}
void LoginClick(object sender, EventArgs args)
{
Button btncontrol = (Button)sender;
string providername = btncontrol.Text;
if (OAuthConfig.User == null)
{
Navigation.PushModalAsync(new ProviderLoginPage(providername));
//Need to create ProviderLoginPage so follow Step 4 and Step 5
}
}
}
}

Step 4: Create Identity Provider Login Page

As we will be having platform specific LoginPage implementation of Xamarin.Auth, we don't need any specific implementation in the portable project.

We do need to add an empty ProviderLoginPage which will be resolved at runtime and substituted by actual implementation regarding this will explain on step 5

Right Click Portable Project ➔ Add New Item ➔Select Xaml page (ProviderLoginPage.Xaml )

using Xamarin.Forms;

namespace DevEnvExeLogin
{
public partial class ProviderLoginPage : ContentPage
{
//we will refer providename from renderer page
public string ProviderName { get; set; }
public ProviderLoginPage(string _providername)
{
InitializeComponent();
ProviderName = _providername;
}
}
}

** In Xaml page no Changes

Step 5: Create Platform Specific Login Renderer:



We need to create platform specific LoginRenderer Page so you can create platform specific Login page (loginRenderer.CS) to iOS, Android and UWP project.

We need to add LoginPageRenderer which will be used by Xamarin.Auth to display web view for OAuth Login Page

Code Snippet Explanation:

The below code is Xamarin.Forms DependencyService which maps ProviderLoginPage to LoginRenderer.

[assembly: ExportRenderer(typeof(ProviderLoginPage), typeof(LoginRenderer))]
Get Identity ProviderName from Providerloginpage
var loginPage = Element as ProviderLoginPage;
string providername = loginPage.ProviderName;

Create OauthProviderSetting class from Portable Class Library with Oauth Implementation, regarding this I have explained in Step 6.

//Create OauthProviderSetting class with Oauth Implementation .Refer Step 6
OAuthProviderSetting oauth = new OAuthProviderSetting();
var auth = oauth.LoginWithProvider(providername);
Create Oauth event for provider login completed and canceled.
auth.Completed += (sender, eventArgs) =>
{
if (eventArgs.IsAuthenticated)
{ //Login Success }
else
{
// The user cancelled
}
};

If you want get and save user info. You can create UserEntity from Portable library and refer below code
namespace DevEnvExeLogin
{
public class UserDetails
{
public string TwitterId { get; set; }
public string Name { get; set; }
public string ScreenName { get; set; }
public string Token { get; set; }
public string TokenSecret { get; set; }
public bool IsAuthenticated
{
get
{
return !string.IsNullOrWhiteSpace(Token);
}
}
}
}

LoginRenderer.CS

using Android.App;
using Xamarin.Forms.Platform.Android;
using DevEnvExeLogin;
using Xamarin.Forms;
using DevEnvExeLogin.Droid.PageRender;

[assembly: ExportRenderer(typeof(ProviderLoginPage), typeof(LoginRenderer))]

namespace DevEnvExeLogin.Droid.PageRender
{
public class LoginRenderer : PageRenderer
{
bool showLogin = true;

protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
{
base.OnElementChanged(e);
//Get and Assign ProviderName from ProviderLoginPage
var loginPage = Element as ProviderLoginPage;
string providername = loginPage.ProviderName;
var activity = this.Context as Activity;
if (showLogin && OAuthConfig.User == null)
{
showLogin = false;
//Create OauthProviderSetting class with Oauth Implementation .Refer Step 6
OAuthProviderSetting oauth = new OAuthProviderSetting();
var auth = oauth.LoginWithProvider(providername);
// After facebook,google and all identity provider login completed
auth.Completed += (sender, eventArgs) =>
{
if (eventArgs.IsAuthenticated)
{
OAuthConfig.User = new UserDetails();
// Get and Save User Details
OAuthConfig.User.Token = eventArgs.Account.Properties["oauth_token"];
OAuthConfig.User.TokenSecret = eventArgs.Account.Properties["oauth_token_secret"];
OAuthConfig.User.TwitterId = eventArgs.Account.Properties["user_id"];
OAuthConfig.User.ScreenName = eventArgs.Account.Properties["screen_name"];
OAuthConfig.SuccessfulLoginAction.Invoke();
}
else
{
// The user cancelled
}
};
activity.StartActivity(auth.GetUI(activity));
}
}
}
}

Step 7: OAuth Implementation

The OAuth2Authenticator class is responsible for managing the user interface and communicating with authentication services. It will support all the identity provider

But In Twitter Oauth Authentication will support only on OAuth1Authenticator so you can use OAuth1Authenticator instead of OAuth2Authenticator.

The OAuth2Authenticator and OAuth1Authenticator class requires a number of parameters, as shown in the following list

Client ID – Identity provider client ID, while register app you will unique client ID.

Client Secret –identifies the client that is making the request. while register app you will unique client secret

Scope – this identifies the API access being requested by the application, and the value informs the consent screen
that is shown to the user. For more information about scopes,

Authorize URL – this identifies the URL where the authorization code will be obtained from.

Redirect URL – this identifies the URL where the response will be sent. The value of this parameter must match
one of the values that appears in the Credentials page for the project.

AccessToken Url — this identifies the URL used to request access tokens after an authorization code is obtained.

Step 7.1: Access GOOGLE Account:

var googleauth = new OAuth2Authenticator(
// For Google login, for configure refer http://jsdotnetsupport.blogspot.in/2016/08/register-identity-provider-for-new.html
"ClientId",
"ClientSecret",
// Below values do not need changing
"https://www.googleapis.com/auth/userinfo.email",
new Uri("https://accounts.google.com/o/oauth2/auth"),
new Uri("http://www.devenvexe.com"),// Set this property to the location the user will be redirected too after successfully authenticating
new Uri("https://accounts.google.com/o/oauth2/token")
);

Step 7.2: Access FACEBOOK Account:

var OauthFacebook = new OAuth2Authenticator(
clientId: "MyAppId", // For Facebook login, for configure refer http://jsdotnetsupport.blogspot.in/2016/08/register-identity-provider-for-new.html
scope: "",
authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"), // These values do not need changing
redirectUrl: new Uri("http://www.facebook.com/connect/login_success.html")// These values do not need changing
);

Step 7.3: Access TWITTER Account:

OAuth1Authenticator auth = new OAuth1Authenticator(
consumerKey: "*****", // For Twitter login, for configure refer http://jsdotnetsupport.blogspot.in/2016/08/register-identity-provider-for-new.html
consumerSecret: "****", // For Twitter login, for configure refer http://jsdotnetsupport.blogspot.in/2016/08/register-identity-provider-for-new.html
requestTokenUrl: new Uri("https://api.twitter.com/oauth/request_token"), // These values do not need changing
authorizeUrl: new Uri("https://api.twitter.com/oauth/authorize"), // These values do not need changing

accessTokenUrl: new Uri("https://api.twitter.com/oauth/access_token"), // These values do not need changing

callbackUrl: new Uri("http://www.devenvexe.com") // Set this property to the location the user will be redirected too after successfully authenticating

Step 7.4 Access Microsoft Account:


var OauthMicrosoft = new OAuth2Authenticator(

clientId: "MY ID", // For Micrsoft login, for configure refer http://jsdotnetsupport.blogspot.in/2016/08/register-identity-provider-for-new.html

scope: "bingads.manage",

authorizeUrl: new Uri("https://login.live.com/oauth20_authorize.srf?client_id=myid&scope=bingads.manage&response_type=token&redirect_uri=https://login.live.com/oauth20_desktop.srf"),

redirectUrl: new Uri("https://adult-wicareerpathways-dev.azurewebsites.net/Account/ExternalLoginCallback")
);

Step 7.5 Access LINKEDIN Account:

var authLinkediN = new OAuth2Authenticator(

clientId: "**",// For LinkedIN login, for configure refer http://jsdotnetsupport.blogspot.in/2016/08/register-identity-provider-for-new.html
clientSecret: "**",
scope: "",
authorizeUrl: new Uri("https://www.linkedin.com/uas/oauth2/authorization"),
redirectUrl: new Uri("http://devenvexe.com/"),
accessTokenUrl: new Uri("https://www.linkedin.com/uas/oauth2/accessToken")

Step 7.6 Access GITHUB Account:

auth = new OAuth2Authenticator(
// For GITHUB login, for configure refer http://jsdotnetsupport.blogspot.in/2016/08/register-identity-provider-for-new.html
"ClientId",
"ClientSecret",
// Below values do not need changing
"",
new Uri("https://github.com/login/oauth/authorize"),
new Uri("http://www.devenvexe.com"),// Set this property to the location the user will be redirected too after successfully authenticating
new Uri("https://github.com/login/oauth/access_token")
);

Step 7.7 Access FLICKER Account:

auth = new OAuth2Authenticator(
// For Flicker login, for configure refer http://jsdotnetsupport.blogspot.in/2016/08/register-identity-provider-for-new.html
"ClientId",
"ClientSecret",
// Below values do not need changing
"",
new Uri("https://www.flickr.com/services/oauth/request_token"),
new Uri("http://www.devenvexe.com"),// Set this property to the location the user will be redirected too after successfully authenticating
new Uri("http://www.flickr.com/services/oauth/access_token"));

Step 7.8 Access YAHOO Account:

auth = new OAuth2Authenticator(
// For Yahoo login, for configure refer http://jsdotnetsupport.blogspot.in/2016/08/register-identity-provider-for-new.html
"ClientId",
"ClientSecret",
// Below values do not need changing
"",
new Uri("https://api.login.yahoo.com/oauth2/request_auth"),
new Uri("http://www.devenvexe.com"),// Set this property to the location the user will be redirected too after successfully authenticating
new Uri("https://api.login.yahoo.com/oauth2/get_token")
);
You can download source and replace client ID or AppID and Client secret





Singleton
 Static Class
1
Single means single object across the application
life cycle so it application level
The static does not have any Object pointer, so the scope is at App Domain level.
2
Singleton is a pattern and not a keyword
Static is key word
3
A Singleton can implement interfaces and inherit from other classes and allow inheritance.
Static class allows only static methods 
and you cannot pass static class as parameter.
Static class cannot inherit their instance members
4
Singleton Objects stored on heap memory
Static class stored in stack memory
5
Singleton Objects can have constructor
Static class will have only static constructor ,so overloading it won’t
work
6
Singleton Objects can dispose
We can’t dispose in static class
7
Singleton Objects can clone
We can’t clone in static class

Introduction:

OAuth is a web authentication protocol and open standard for authorization, Nowadays Internet users to log in to third party websites using following account without exposing user registration.

Google
Facebook
Twitter
Microsoft
LinkedIn
Githup
Flicker
Yahoo
DropBox
You can find below wiki for some more list of notable identity provider
https://en.wikipedia.org/wiki/List_of_OAuth_providers

How Oauth will Work:

Third party app /website can access your data stored in another website without registries.

The OAuth flow has three steps

  • Get a Request Token
  • Get the User's Authorization
  • Exchange the Request Token for an Access Token

Register New OAuth Applications:

Before you can integrate Identity provider sign-in into your apps, you must register your application and get the corresponding client ID and client secret from below steps, which we need to call the Sign-in API


Configure Google OAuth:

Register New OAuth application follow below steps

Navigate to https://console.developers.google.com and login with your google Account credentials when prompted.

Select Credentials tab and Click on Create Project.

Add your App/website name and click on Create



In the Credentials API Popup, select the create credentials drop-down list, and choose OAuth client ID.




Select Application Type As Web Application or iOS, android and click on configure button


Fill personal details, privacy details and click on save

Get the package name from your AndroidManifest.xml file then use the following command to get the fingerprint and Click on Create



8. From the resulting OAuth client dialog box, copy the Client ID. The Client ID lets your app access enabled Google APIs.

Configure Facebook OAuth:

Register New OAuth application follow below steps



Navigate to https://developers.facebook.com and login with your facebook Account credentials when prompted.
Click on “ My Apps” Dropdown and select “Add a New App”.



Select a App Platform ( iOS,Android,Facebook Canvas,WebSite,etc)
Give Unique App/Website Name


Fill email, select app category and click on “Create APP ID”.
Complete security check and click on Submit
Get the package name from your AndroidManifest.xml file then add package name and class name



Generate development key hash and press on Finish
From the resulting OAuth client dialog box, copy the Client ID. The Client ID lets your app access enabled Facebook APIs.

Configure Twitter OAuth:

Register New OAuth application follow below steps
Navigate to https://dev.twitter.com/apps/new and login with your Twitter Account credentials when prompted.
Enter your Application Name, Description ,your website address and callback URL.


Accept the Developer agrement and clicking the Create your Twitter Application.
Copy the consumer key (API key) and consumer secret from the screenand use into your application

Configure Microsoft OAuth:

Go to https://apps.dev.microsoft.com/, and login with your Microsoft Account (Hotmail, Windows Live, Messenger, Active Directory, Xbox, Skype, and OneDrive) credentials when prompted.
Select My Application and click Add an App
Enter the Application name and click on Create application



Generate application ID and secrets and use into the application


Configure LinkedIn OAuth:

Register New OAuth application follow below steps
Navigate to http://developer.linkedin.com/ and login with your LinkedIn Account credentials when prompted
Select platform (RESTAPI,Javascript ,Android SDK,iOS SDK)
Click the "Add New Application" link and fill in the required fields(Company Name,Application Name,Description,Application URL,logo,Business website,email and phone) and agree Licience condition



4. Click on Submit. To retrieve your API Key and Secret Key later, click on the link for your Application Name and they will now be listed in the application's details.


Configure Githup OAuth:

Register New OAuth application follow below steps
Navigate to https://github.com/settings/developers and login with your Github Account credentials when prompted.
Click the "Register New App" link and fill in the required fields(Application Name,Description, URL and callback url) and click on”Regsiter Application “

Copy the Client ID and Client Secret from the screen and use into your application


Configure Dropbox OAuth

Navigate to https://www.dropbox.com/developers and login with your DropBox Account credentials when prompted.
Choose an API Type and Access type
Enter the Application name and click on Create App



Copy the App Key and App Secret from the screen and use into your application


Configure Flicker OAuth:

Navigate to https://developer.yahoo.com/flickr/ and login with your Yahoo Account credentials when prompted.
For getting API Key ,Clcik on “ Create an APP”.

Choose if Non-Commercial or Commercial.
Enter the Application name, description and click on submit


Copy the App Key and App Secret from the screen and use into your application


Configure Yahoo OAuth:

Register New OAuth application follow below steps
Navigate to https://developer.yahoo.com/apps/ and login with your Yahoo Account credentials when prompted.
Enter the Application name, application type and access and click on Create App







Copy the Client ID and Client Secret from the screen and use into your application



I will explain about implementation on Next article

Featured Post

How to Get an Free Azure Subscription for Learning

This guide will help you get started with Microsoft Azure for free. It explains three easy ways: using a Free Azure Account Signing up for A...

MSDEVBUILD - English Channel

MSDEVBUILD - Tamil Channel

Popular Posts