Google OAuth Xamarin.Auth – iOS implementation with Custom Tabs/SafariController

Previously Google OAuth used to support WebViews at the time of authentication. Trade off with that approach was – one (HACKERS) can easily intercept what is happening around with the Authentication request. The client_id/client_secret etc were exposed.

To handle that Google has blocked the use of WebViews whatsoever. Now while authenticating user will be redirected to the Safari or any other Custom browser instance and from there the authentication will happen.

Now as Xamarin.Auth is a quite old repository – so it had quite a bit of issues with this new authentication structure. Now with latest Xamarin 1.4.1 (At the time of writing 1.5.0 alpha was also there but not that stable one) we can handle the Google OAuth 2.0 quite efficiently with all the constraint google has imposed so far for security reason.

There is a very useful sample in Github – using which we will try to figure out what can be done in terms of development to integrate Google OAuth in your Xamarin.iOS app.

Please download or clone this repository before reading forward if you are new to this. (Rest of the steps are performed in Xamarin.Studio – Mac. In case you are using Visual Studio the same steps can be replicated)

Before starting off with the demo please have your client_id, redirect_uri, authorize_uri, accesstoken_uri, scope etc for your iOS app handy.

Open the solution. You will see a project structure like below snapshot. There you might see some indicator icon with your iOS project.


N.B:
We need to mark our project as active configuration. To do that follow the below steps – go to Xamarin.Auth.Samples.TraditionalStandard -> Right click -> Options -> Under build menu select configurations -> In configuration mappings tab check the build option against your iOS project.Screen Shot 2017-05-01 at 10.59.06 AM

Now set your iOS project as start-up project and select Debug mode with Simulator or Device whichever you prefer.
(While running this project if at all you face any other issues you can post it comments below or try to find any workaround in web also there might be few unnecessary codes Which you might throw you some build error, you might want to comment out those codes for the time being).

Now go to the iOS app under the condition
else if (oauth2.OAuth_UriAccessToken_UriRequestToken != null)
 [as this is OAuth2 Authentication that we are talking about)
replace the parameters of
Auth2 = new OAuth2Authenticator
as per your project specific id and url.

We have set our project for OAuth – now we need to get the Token from 1st step of authentication and request the actual token from the Google and use it in your subsequent server calls.

For that under Xamarin.Auth folder you will find a partial class of AppDelegate.cs 
There you will see one override of OpenUrl method. From there we need to fetch the token of 1st step auth. I extracted the auth in below manner and assign it to a constant in YourViewController.constUri

int pFrom = url.AbsoluteString.IndexOf("&code=", StringComparison.Ordinal) + "&code=".Length;
int pTo = url.AbsoluteString.LastIndexOf("&authuser=", StringComparison.Ordinal);
 YourViewController.constUri = url.AbsoluteString.Substring(pFrom, pTo  pFrom);

Now we will use this Token to Get our actual access token and our service call be authorized.
In the auth_completed method call the  RequestAccessTokenAsync.
You need to specify all the query values while passing the parameters with the auth_code that you got from Open_url.
With that request you will have all your required data like access_token/refresh_token etc.

Store all the values that you get from that call and use it in subsequent requests.

Let me know in case you have any issues. Please post it in comments or tweet me @codersubhamoy

We also have a Slack channel dedicated to that. Please visit there.

Assembly, Metadata and IL in .NET framework

Assembly, Metadata and IL are some darker and geekier side of .NET. As a developer we don’t really delve into these stuffs on day to day basis while spewing out applications for our users. But we must know these as sometimes the code we write can break and the simple solution or fix might not be available by simply googling the error. Error could be embedded in deep.

An assembly in .NET is a logical unit of deployment, execution and reuse. It can be a exe or dll. Now the when comes when do we have a exe and when do we have an dll as our assembly.  If we have a directly runnable program eg: we have created an Windows form application, then we have an exe which would run to provide the output. In case we have an library that can be used with a different program that library is being referred as dll with an .dll extension.

A Manifest has all of the information that .NET runtime needs in order to execute the code. This information includes all the types and IL(intermediate language) code.

Now lets talk about IL  – IL stands or intermediate language. As we know C# is high level language, humans can read it but machines can’t understand it. So C# need to complied at something that computer can understand. So rather than converting source to machine code .NET compiler generates IL – which is somewhere in between human readable code and machine code. The good news is that we can see the generated IL using tools like ILDASM or ILSPY.

Use of Comparer in C#

One of the interfaces in C# which is very vital but a bit underutilized in day to day programming is IComparer<T>. IComparer<T> basically says it knows how to compare two objects of type T, to determine which one is greater.

Suppose I have a array with name of weekdays, we want to sort on the basis of character length of each weekday. Eg: in our array of day-week , Wednesday would be the longest one.

Create a console application and copy paste the below code inside your main program namespace

    class Program
    {
        static void Main(string[] args)
        {
            
            string[] daysOfWeek = new string[] 
            {
                "Monday",
                "Tuesday",
                "Wednesday",
                "Thursday",
                "Friday",
                "Saturday",
                "Sunday"
            };

            Array.Sort(daysOfWeek,new StringComparer());
            foreach (var item in daysOfWeek)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();
        }

    }

    public class StringComparer : IComparer<string>
    {

        public int Compare(string x, string y)
        {
            return x.Length.CompareTo(y.Length);
        }
    }

So here we have used our code with Array.Sort() method, this particular method has number of overloads. One of the overload is

public static void Sort(Array array, IComparer comparer);

We have used that particular method in our code. Lets explore the code :

1. We have declared an array of string where we have some values, our aim is to sort that array based on the length of array items.

2. For that we will use a Sort method overload available in .NET for Arrays.

3. To use sort we have to first create our comparer class by implementing comparer<string>. Where we compare the string elements length.

Array.Sort(daysOfWeek,new StringComparer());

our program will now sort the Array based on no of characters in ascending.

PS: If I have to sort an Array I would rather use an LINQ, as Arrays are of type IEnumerable so we can easily apply order by clause over array elements. But there might be cases where we need to use IComparer

What is Array Covariance?

In C# some language features are hard to get in one glance, Array covariance is one of those. Lets have a look into the below code

namespace ArrayDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] daysOfWeek = new string[] 
            {
                "Monday",
                "Tuesday",
                "Wednesday",
                "Thursday",
                "Friday",
                "Saturday",
                "Sunday"
            };

            object[] objectArray = daysOfWeek;
            foreach (var item in objectArray)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();
        }
    }
}

In the above code I am declaring a array of strings , assigning some value into that. Then I declare another array of type object and assign my first array to that, afterwards I have printed all the items of objectArray. It will print values with a charm.

output of program

Now one must remember Array of strings never derive from Array of objects. Rather object array and string array both derives from  Array base class. So why does the compiler not shouting here..with the scream of “Type mismatch”. The reason is :   This is a feature of Array in .NET which states you can always implicitly cast array of derived to array of base type and it is known as array covariance. Though veteran C# geeks suggest not to use array covariance, still its a nice to know feature.

Mobile Applications protege: Native, Hybrid or Crossplatform, with whom should I go with?

If you are working as an mobile application developer and if a user today comes to you/your corporation – asks for a complete mobile solution(in all the top platform – iOS/Android/Windows Phone) for his business module then what should be your first step? Of-course requirement gathering, but whats next ? If 3 guys are available in your team then would you people just divide Android, iOS, Windows Phone among each other and delve into the next steps or is there any deeper evaluation to be done?

A mobile application can be of hype hybrid, native or cross platform. Lets peek into each of them.

Native: Native applications are specifically made for a mobile platform and runs only on that particular mobile platform. In one sentence – native applications runs on the operating system RunTime. The development languages, tooling and libraries are different for each platform. For example –  iOS apps development language is Objective c or Swift(which is in its early days at the time of writing) , tool that is being used for iOS – XCode, class libraries used – Cocoa touch. Where as Android Apps are written on Java and API or library used is Android API. So of-course to develop native app for all three platforms one need to know you need to know all three languages, knowledge of framework also code reusability would be a blunt “Zero”.

Hybrid: Hybrid mobile applications are developed in simple HTML and Javascript. Although they are available in App store still they can be rather marked as Web app. So how does it work? It runs in browser only the user doesn’t get the feel to that it is running in browser, also notably all the HTML/CSS/Javascript are are stored locally not on a server. To develop hybrid apps there are number of free and paid tools available. Free tools like Phonegap, Apache Cordova are there, also commercial tools like Telerik Appbuilder can be used to develop a Hybrid app. After you develop you will be able to get the package for each platform.

Cross-Platform: Native mobile apps that are developed using a framework which enables code sharing between application. How does it differ from hybrid ? Cross platform apps runs as native mobile app with the use of shared runtime. Also not full code sharing is possible – sharing of code upto some degree is possible. But as only one programming language is used to develop across all the platforms so evidently support and maintenance becomes much easier.  There are several commercial tools available for cross-platform application development like Xamarin. Xamarin also let us share the UI across platforms Version 3 onward.

Now the question comes which one to choose : answer is choose whichever fits to your need most. How to determine which suits your need best. Lets take a scientific approach –  to get into a conclusion first finalize the parameters based on which we need to derive at our choice. For a certain application development I find the following parameters are essential :

  1. Language
  2. Debugging
  3. UI Design
  4. Performance
  5. Footprint(What is the package size of the deployable app)
  6. Tooling support
  7. Costs
  8. Code Sharing – How much level of code sharing is possible(If you are designing a game then code sharing won’t be any fruitful in general scenarios – as it will be all about user interaction)

Along with the above list you can add your own list based on the requirement. Like how much async support you need, camera support – image processing. Then give each one of them a weightage of 1 to 10 based on their importance in your app. Then make corresponding column for each platform – native, cross-platform, Hybrid against your parameter. So your table should look like below

Eval_Param

Now mark how much a certain framework suffice its corresponding parameter in a scale of 10. Eg : if you find Cross-Platform(Xamarin) serves all your language requirement mark it 10.

At last multiply the weightage with framework weightage, and find the sum of he results for each platforms. You might well get decisive picture on that.

Still it is suggested that several brainstorming session has to be done among the developers and architects before zeroing down to a particular framework.

Getting started with Windows Embedded 8 Handheld

In my latest project I have been working with Windows Embedded 8 Handheld, idea was to create an App for a American Retailer with functionalities like scanning, printing, signature capture etc. If you are a .NET developer with some WPF back ground, things will go in ease with you because Windows Embedded handheld applications are built in XAML and C#. Hopefully by following this post you will be able to start your first project with ease.

Tools and SDKs

Make sure you have the below configurations and tools installed

1. Windows 8/8.1 as Operating System

2. Visual Studio 2012 Professional or Higher

3. Windows Phone 8 SDK

4. Windows Handheld SDK

Lets start

1. Lets go to Visual Studio File -> New project, If you have installed everything correctly then you will see under templates Windows Phone appearing. Select that template and in main list select Windows Phone App (as shown in the picture), I have named my project as MyFirstHandHeld.

HH12. You will be prompted for the target version select Windows 8.0 as target there.

3. Then you will land up in the project window along with with solution explorer. Now to check whether your handheld SDK was successfully installed you can click on the dropdown arrow in Emulator options in upper task bar. If you see the emulator options with ‘H’ suffix in their name like “WE8H Emulator WVGA” etc…it means that handheld SDK was correctly installed.

hh24. Now if you run your application by targeting a WE8H emulator it will run perfectly but you will not be able to use native features like Scanner, MSR etc. To take advantage of the Native features you have to include postnativeutils library which you are supposed to find in “c:\Program Files (x86)\Microsoft SDKs\Windows Embedded Handheld\v8.0\Libraries\x86\POSTestNativeUtils.winmd”. So now to add this library

a. go to References in your solution explorer and right click it and select “Add Reference”

Note: You will see few options like “Add Reference”, “Add Service Reference” etc

b. go to browse and browse the path of POSTestNativeUtils we mentioned before.hh3 After including and clicking ok, your app is ready to use scanner and other native utils.. So Congratulations you have created your first native windows handheld app. Now you can go ahead and use the Native libraries of Scanner/ Printer/ Card Reader etc..

Troubleshoot

Now there’s one catch after you add your libraries. Before going ahead remember if the Native peripheral devices runs on 32 bit architecture you might want to select X86 as the target platform. Right click on your solution and select configuration manager. There you will be able to select the Target Platform as X86, follow the below screenshot for reference.

hh4

Moving Forward

Now we can go ahead and use our native features like Scanning/ MSR card reading etc. That is a different sort of discussion I will create few more posts for that.

What does a programmer has to do with Big Data!!!

I came across this latest industry buzzword “Big Data” quite sometime back around 2 years . Since then I have been thinking of doing some digging around on that but my schedule(read Breaking Bad episodes and boring projects) did not allow me to get any hold of that. Well.. so now that I have gone through some introductory documents and couple of geeky webinars I think I now get what could be accomplished through Big Data and more importantly how programmers could contribute there. Lets start….

Big Data_1

Big Data in one sentence  – the data which cannot be analyzed with the traditional relational database/row column based excel. Definitely that sounds a bit ambiguous. So lets define what it is not – it is not traditional data, it can’t be analyzed with conventional data analyzing method like pivoting. So some common characteristics are It has Tremendous volume, Tremendous variety, Tremendous  Velocity – so the old geeks call it 3Vs of Big data.

Lets talk about the 3Vs with a simple example – twitter, twitter has a really great volume of data(billions of tweets, photos, videos) ,variety stands for how many data sources you handle ( users, other websites, API interactions etc) so the data analysis could not be done through general DBMS approach –   velocity refers to how fast data coming onto your system – do me a favor go to http://www.internetlivestats.com/one-second/#tweets-band  and find out yourself what velocity really is.

So going by the example so it seems like mostly data crunching kind of work for MBAs, so what does we programmer really do with Big Data, how can we developers contribute to it? Lets take a graphical peek at what are the skill sets required for being a Big Data Analytic professional. Take a closer look at the below Venn Diagram.

BiG Data 2   So for this diagram, you could see to be a complete Data Science professional(namely Big Data) one need to have knowledge in Statistics, Domain Expertise & Coding. Talking about practical scenario if a company wants to start with Big Data work its pretty unlikely get professionals who specifically posses this kind of skill set. So instead if they hire “Traditional Researcher” and “Machine Learning” professionals it is quite suffice their needs. So we programmer can very easily be machine learning experts and delve into the pool of Big Data, now those programmer who are with a Computer Science academic background might think that “Man what the hell is machine learning”. Quoting Wikipedia.

Machine learning is a scientific discipline that explores the construction and study of algorithms that can learn from data. Such algorithms operate by building a model based on inputs and using that to make predictions or decisions, rather than following only explicitly programmed instructions.

So programmer build predictive models to help taking decisions based on the available data and running the statistical analysis over that. Now the question comes what is predictive model, lets explore it with one example – how often we buy stuffs online in Amazon, Flipkart and we often see a section called “Recommended Products”. How this these websites know “What to recommend me” when I am merely looking for some random books. This is called prediction and this back end programming is being done by machine learning experts. Netflix in 2009 declared an open contest for the people , whoever increases their predictive algorithms efficiency by 10% will be awarded a grand 1M $. You can read all about it  here.

So to sum up programmers with machine learning expertise are rather inseparable part of Big Data. Researcher can only define some fundamental grounds still at the end of day programmers will do all the heavy lifting for Big Data Analysis.

There are some interesting open source Big Data projects

  1. Google Flu trend
  2. Internet Live stats