How to login to facebook in Xamarin.Forms

Let's start with the core of the app, the Xamarin.Forms PCL project. Your App class will look something like this:

namespace OAuth2Demo.XForms
{
    public class App
    {
        static NavigationPage _NavPage;

        public static Page GetMainPage ()
        {
            var profilePage = new ProfilePage();

            _NavPage = new NavigationPage(profilePage);

            return _NavPage;
        }

        public static bool IsLoggedIn {
            get { return !string.IsNullOrWhiteSpace(_Token); }
        }

        static string _Token;
        public static string Token {
            get { return _Token; }
        }

        public static void SaveToken(string token)
        {
            _Token = token;
        }

        public static Action SuccessfulLoginAction
        {
            get {
                return new Action (() => {
                    _NavPage.Navigation.PopModalAsync();
                });
            }
        }
    }
}

The first thing to notice is the GetMainPage() method. This tells the app which screen it should load first upon launching.

We also have a simple property and method for storing the Token that is returned from the auth service, as well as a simple IsLoggedIn property.

There's an Action property as well; something I stuck in here in order to have a way for the platform implementations to perform a Xamarin.Forms navigation action. More on this later.

You'll also notice some red in your IDE because we haven't created the ProfilePage class yet. So, let's do that.

Create a very simple ProfilePage class in the Xamarin.Forms PCL project. We're not even going to do anything fancy with it because that will depend on your particular need. For the sake of simplicity in this sample, it will contain a single label:

namespace OAuth2Demo.XForms
{
    public class ProfilePage : BaseContentPage
    {
        public ProfilePage ()
        {
            Content = new Label () {
                Text = "Profile Page", 
                VerticalOptions = LayoutOptions.CenterAndExpand,
                HorizontalOptions = LayoutOptions.CenterAndExpand, 
            };
        }
    }
}

Again, you'll probably have some red in your IDE because we seem to be missing the BaseContentPage class. The sole purpose of the BaseContentPage class is to ensure that none of the app's screens can be displayed until the user has logged in. (In this simplified demo, we're just persisting the user info to memory, so you'll need to re-login every time the app is run. In a real-world app, you'd be storing the authenticated user info to the device's keychain, which would eliminate the need to login at each app start.)

Create a BaseContentPage class in the Xamarin.Forms PCL project:

namespace OAuth2Demo.XForms
{
    public class BaseContentPage : ContentPage
    {
        protected override void OnAppearing ()
        {
            base.OnAppearing ();

            if (!App.IsLoggedIn) {
                Navigation.PushModalAsync(new LoginPage());
            }
        }
    }
}

There's a few interesting things going on here:

  1. We're overriding the OnAppearing() method, which is similar to the ViewWillAppear method in an iOS UIViewController. You can execute any code here that you'd like to have run immediately before the screen appears.

  2. The only thing we're doing in this method is checking to see if the user is logged in. If they're not, then we perform a modal push to a class called LoginPage. If you're unfamiliar with the concept of a modal, it's simply a view that takes the user out of the normal application flow in order to perform some special task; in our case, to perform a login.

So, let's create the LoginPage class in the Xamarin.Forms PCL project:

namespace OAuth2Demo.XForms
{
    public class LoginPage : ContentPage
    {

    }
}

Wait...why doesn't this class have a body???

Since we're using the Xamatin.Auth component (which does the job of building and presenting a web view that works with the provided OAuth2 info), we actually don't want any kind of implementation in our LoginPage class. I know that seems weird, but bear with me.

The LoginPageRenderer for iOS

Up until this point, we've been working solely in the Xamarin.Forms PCL project. But now we need to provide the platform-specific implementation of our LoginPage in the iOS project. This is where the concept of a Renderer comes in.

In Xamarin.Forms, when you want to provide platform-specific screens and controls (i.e. screens that do not derive their content from the abstract pages in the Xamarin.Forms PCL project), you do so withRenderers.

Create a LoginPageRenderer class in your iOS platform project:

[assembly: ExportRenderer (typeof (LoginPage), typeof (LoginPageRenderer))]

namespace OAuth2Demo.XForms.iOS
{
    public class LoginPageRenderer : PageRenderer
    {
        public override void ViewDidAppear (bool animated)
        {
            base.ViewDidAppear (animated);

            var auth = new OAuth2Authenticator (
                clientId: "", // your OAuth2 client id
                scope: "", // the scopes for the particular API you're accessing, delimited by "+" symbols
                authorizeUrl: new Uri (""), // the auth URL for the service
                redirectUrl: new Uri ("")); // the redirect URL for the service

            auth.Completed += (sender, eventArgs) => {
            // We presented the UI, so it's up to us to dimiss it on iOS.
            App.SuccessfulLoginAction.Invoke();

            if (eventArgs.IsAuthenticated) {
                // Use eventArgs.Account to do wonderful things
                App.SaveToken(eventArgs.Account.Properties["access_token"]);
            } else {
                // The user cancelled
            }
        };

        PresentViewController (auth.GetUI (), true, null);
            }
        }
    }
}

There are important things to note:

  1. The [assembly: ExportRenderer (typeof (LoginPage), typeof (LoginPageRenderer))] line at the top (and importantly before the namespace declaration) is using the Xamarin.FormsDependencyService. It's not the most beautiful thing in the world because it's not IoC/DI, but whatever...it works. This is the mechanism that "maps" our LoginPageRenderer to the LoginPage.

  2. This is the class in which we're actually using the Xamarin.Auth component. That's where the OAuth2Authenticator reference comes from.

  3. Once the login is successful, we fire off a Xamarin.Forms navigation via App.SuccessfulLoginAction.Invoke();. This gets us back to the ProfilePage.

  4. Since we're on iOS, we're doing all of our logic sinde of the ViewDidAppear() method.

The LoginPageRenderer for Android

Create a LoginPageRenderer class in your Android platform project. (Note that class name you're creating is identical to the one in the iOS project, but here in the Android project the PageRenderer inherits from Android classes instead of iOS classes.)

[assembly: ExportRenderer (typeof (LoginPage), typeof (LoginPageRenderer))]

namespace OAuth2Demo.XForms.Android
{
    public class LoginPageRenderer : PageRenderer
    {
        protected override void OnModelChanged (VisualElement oldModel, VisualElement newModel)
        {
            base.OnModelChanged (oldModel, newModel);

            // this is a ViewGroup - so should be able to load an AXML file and FindView<>
            var activity = this.Context as Activity;

            var auth = new OAuth2Authenticator (
                clientId: "", // your OAuth2 client id
                scope: "", // the scopes for the particular API you're accessing, delimited by "+" symbols
                authorizeUrl: new Uri (""), // the auth URL for the service
                redirectUrl: new Uri ("")); // the redirect URL for the service

            auth.Completed += (sender, eventArgs) => {
            if (eventArgs.IsAuthenticated) {
                App.SuccessfulLoginAction.Invoke();
                // Use eventArgs.Account to do wonderful things
                App.SaveToken(eventArgs.Account.Properties["access_token"]);
            } else {
                // The user cancelled
            }
        };

        activity.StartActivity (auth.GetUI(activity));
        }
    }
}

Again, let's take a look at some interesting things:

  1. The [assembly: ExportRenderer (typeof (LoginPage), typeof (LoginPageRenderer))] line at the top (and importantly before the namespace declaration) is using the Xamarin.FormsDependencyService. No difference here from the iOS version of LoginPageRenderer.

  2. Again, this is where we're actually using the Xamarin.Auth component. That's where the OAuth2Authenticator reference comes from.

  3. Just as with the iOS version, once the login is successful, we fire off a Xamarin.Forms navigation via App.SuccessfulLoginAction.Invoke();. This gets us back to the ProfilePage.

  4. Unlike the iOS version, we're doing all of the logic inside of the OnModelChanged() method instead of the ViewDidAppear().

 

 

Happy Coding ... :)

 

How to fix the NuGet package update for Xamarin

Problem : 

When you create a new Xamarin.Forms app or open existing one, if you’ve fresh formatted machine with fresh VS and Xamarin installation, the build may last for longer than expected. The reason for this being, it downloads NuGet packages along with its dependencies like Android Support Packages. If in between, VS hangs or there are interruptions in network, you’ll see some errors.

Solution :

Well, at first you may think it is issue with Xamarin or Visual Studio or NuGet. But this all has to do with lot of NuGet packages and their dependencies download. So it all depends on machine config and network connectivity. If ever you see above errors follow the below steps:

1) Start from fresh. Close Visual Studio instances and delete everything under %appdata%local/Xamarin (e.g. C:\Users\<<USERNAME>>\AppData\Local\Xamarin)

2) Launch Visual Studio and open the solution. Right click each project and update NuGet packages. Android is the one which will take longer to update.

3) Wait till all packages are downloaded. Make sure the %appdata% folder contents all the necessary directories and files.

4) Build the solution. And if you still get issues about some missing some resources. Open Android SDK Manager from Tools > Android and make sure right API levels (in this case API Level 23) is installed.

Now run the project and it should run without any issues.

 

Happy Coding ... :)

 

How to customize a ListView in Android using Xamarin

In the previous post, we saw how to create a genrice ListView control and add some items to it. In this post we will take a step further to create a custom ListView with a text field to represent each row of the ListView control and write a custome Adapter to bind the items to ListView.

Step 1: Add a new layout file that will represent a single row of the list view item. We will add a TextView control within the layout and name it txtName

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minWidth="25px"
    android:minHeight="25px">
    <TextView
        android:text="Name goes here ..."
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtName"
        android:minHeight="100px"
        android:padding="15px"
        android:textStyle="bold" />
</LinearLayout>

Step 2: We will add a custom Adapter that will inherit the BaseAdapter with the following implementation:

class MyListViewAdapter : BaseAdapter
    {
        private List<string> mItems;
        private Context mContext;

        public MyListViewAdapter(Context context, List<string> items)
        {
            mItems = items;
            mContext = context;
        }

        public override Object GetItem(int position)
        {
            return mItems[position];
        }

        public override long GetItemId(int position)
        {
            return position;
        }

        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            View row = convertView ?? LayoutInflater.FromContext(mContext).Inflate(Resource.Layout.ListView_Row, null);

            TextView txtName = row.FindViewById<TextView>(Resource.Id.txtName);
            txtName.Text = mItems[position];

            return row;
        }

        public override int Count
        {
            get { return mItems.Count; } 
        }
    }

 

After this step we will set the layout binding to the custom adapter in MainActivity.cs

[Activity(Label = "ListViewTutorial", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        private List<string> mItems;
        private ListView mListView;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            
            mListView = FindViewById<ListView>(Resource.Id.myListView);

            mItems = new List<string> {"Apples", "Oranges", "Bananas"};
            
            MyListViewAdapter adapter = new MyListViewAdapter(this, mItems);

            mListView.Adapter = adapter;
            
        }
    }

This should complete the binding of the mList items to MyListViewAdapter and actually set the mListView adapter.

The final app should look like below :

 

 

Happy Coding ..... :)

How to create a ListView in Android using Xamarin

In this post we will see how to create a Listview in Android using Xamarin project.

Step 1: Start Visual Studio and selected Android -> Blank App

Step 2: Open Main.axml and replace its content with the following:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:minWidth="25px"
    android:minHeight="25px">
    <ListView
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/myListView" />
</LinearLayout>

The step2 is just adding the ListView Control from the toolbox and giving it an id "myListView"

Step 3 : In this step we are going to create a List of strings and bind this list to the myListView control we just added to the Main.axml page

Code for creating the List and assigning to the myListView contol should be in the MainActivity.cs as follows :

private ListView mListView;
mListView = FindViewById<ListView>(Resource.Id.myListView);

mItems = new List<string> {"Apples", "Oranges", "Bananas"};

ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, mItems);
            
mListView.Adapter = adapter;

In these lines of code we created a list named mListView which holds a list of strings. Then we created an ArrayAdapter that specifies that the Android resource layout is a SimpleListItem1 type and the list is mItems. Next we just sep the Adapter property to the adapter to display the values in the ListView.

 

Here is the complete code for MainActivity.cs

public class MainActivity : Activity
    {
        private List<string> mItems;
        private ListView mListView;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            
            mListView = FindViewById<ListView>(Resource.Id.myListView);

            mItems = new List<string> {"Apples", "Oranges", "Bananas"};

            ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, mItems);
            mListView.Adapter = adapter;
            
        }
    }

And here is the output of the complete program:

 

 

Happy Coding .... :)

 

How to create an animated clock using Jquery

The following code snippet will create an animated clock using JQuery and ASP.NET form.

var getCurrentTime = function () {
            var dt = new Date();
            var dtHour = ("0" + dt.getHours()).slice(-2);
            var dtMinutes = ("0" + dt.getMinutes()).slice(-2);
            var dtSeconds = ("0" + dt.getSeconds()).slice(-2);
            var strAmPm = "";
            if (dtHour >= 12)
                strAmPm = "PM";
            else
                strAmPm = "AM";
            if (dtHour > 12)
                dtHour -= 12;
            var time = dtHour + ":" + dtMinutes + ":" + dtSeconds + " "
            + strAmPm;
            return time;
        };

        $(function() {
            setInterval(function() {
                $('#<%= lblTime.ClientID%>').text(getCurrentTime);
                $("#<%=lblTime.ClientID%>").animate({
                    opacity: 0
                }, 950).animate({
                    opacity: 1
                }, 50);
            }, 1000);
        });

 

Here is the complete aspx page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .container {
            background-color: lightgray;
            font-size: 24px;
            font-family: 'Times New Roman', Times, serif;
            color: black;
            border: solid;
            border-color: darkblue;
            border-width: 1px;
            width: 150px;
            text-align: center;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Panel ID="pnlTimer" runat="server" CssClass="container">
            <asp:Label ID="lblTime" runat="server" Text=""></asp:Label>
        </asp:Panel>
    </div>
    </form>
    <script src="scripts/jquery-2.2.1.js"></script>
    <script src="scripts/jquery-ui-1.11.4.js"></script>
    <script type="text/javascript">
        var getCurrentTime = function () {
            var dt = new Date();
            var dtHour = ("0" + dt.getHours()).slice(-2);
            var dtMinutes = ("0" + dt.getMinutes()).slice(-2);
            var dtSeconds = ("0" + dt.getSeconds()).slice(-2);
            var strAmPm = "";
            if (dtHour >= 12)
                strAmPm = "PM";
            else
                strAmPm = "AM";
            if (dtHour > 12)
                dtHour -= 12;
            var time = dtHour + ":" + dtMinutes + ":" + dtSeconds + " "
            + strAmPm;
            return time;
        };

        $(function() {
            setInterval(function() {
                $('#<%= lblTime.ClientID%>').text(getCurrentTime);
                $("#<%=lblTime.ClientID%>").animate({
                    opacity: 0
                }, 950).animate({
                    opacity: 1
                }, 50);
            }, 1000);
        });
    </script>
</body>
</html>

 

Download Source

 

Happy Coding ... :)

 

 

Using jQuery $(document).ready within UpdatePanels

While using jquery $(document).ready within Update panels the code is not registered in the event of a postback. This is because, an UpdatePanel completely replaces the contents of the update panel on an update. This means that those events you subscribed to are no longer subscribed because there are new elements in that update panel.

A quick fix is to use the jquery approach on the initial load and then use Microsoft's Page Request Manager to re-subscribe to the events again,

 

$(document).ready(function() {
    // bind your jQuery events here initially
});

var prm = Sys.WebForms.PageRequestManager.getInstance();

prm.add_endRequest(function() {
    // re-bind your jQuery events here
});

 

The PageRequestManager is a javascript object which is automatically available if an update panel is on the page. You shouldn't need to do anything other than the code above in order to use it as long as the UpdatePanel is on the page.

If you need more detailed control, this event passes arguments similar to how .NET events are passed arguments (sender, eventArgs) so you can see what raised the event and only re-bind if needed.

Here is the latest version of the documentation from Microsoft: Sys.WebForms.PageRequestManager endRequest Event

 

Happy Coding .... :)

Useful features of C# 6.0

Lets start this article by creating a typical class that might be a part of simple application:

public class Person
{
    public Person()
    {
        FirstName = string.Empty;
        LastName = string.Empty;
        DateCreated = DateTime.UtcNow;
        Qualifications = new HashSet<Qualification>();
    }
    public int PersonId { get; set; }
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string FullName { get { return string.Format("{0} {1}", FirstName, LastName); } }
    public DateTime DateCreated { get; set; } 
    public DateTime BirthDate { get; set; }
    public ICollection<Qualification> Qualifications { get; set; } 
}



public class Qualification
{
    public Qualification()
    {
        Awardees = new HashSet<Person>();
        Name = string.Empty;
    }
    public int QualificationId { get; set; }
    public string Name { get; set; } 
    public DateTime WhenAwarded { get; set; }
    public virtual ICollection<Person> Awardees { get; set; } 
}

The models Person and Qualification, has many-to-many relationship between them. 

  • Auto-property Initializers : If you want to set a default value for a property in a class, you do this in the constructor in C# 5 or less. C# 6 introduces Auto-property initializers that enable you to assign a default value for a property as part of the property declaration.
public class Person
{
    public int PersonId { get; set; }
    public string FirstName { get; set; } = string.Empty;
    public string LastName { get; set; } = string.Empty;
    public string FullName { get { return string.Format("{0] {1}", FirstName, LastName); } }
    public DateTime DateCreated { get; set; } = DateTime.UtcNow;
    public DateTime BirthDate { get; set; }
    public ICollection<Qualification> Qualifications { get; set; } = new HashSet<Qualification>();
}

 

  • Expression Bodied members :  In C# 6, this expression can be used in the same way as the auto-property initializer, reducing the syntax down a bit:
public string FullName => string.Format("{0} {1}", FirstName, LastName);

 

  • Getter-only auto-properties :  With C# 6, you can now omit the set accessor to achieve true readonly auto implemented properties:
public DateTime BirthDate { get; }

 

  • String Interpolation : Rather than filling placeholders with indexes then provide an array of values to be slotted in at runtime, you provide the source of the parameter value instead, and the string.Format call is replaced by a single $ sign. This is how the FullName property declaration looks when using string interpolation in the expression body instead:
public string FullName => $"{FirstName} {LastName}";

 

  • Null-conditional operators : This is very useful if you want to simplify the null checks. 
var people = new List<Person>();
var name = string.Empty;
if(people.FirstOrDefault() != null)
{
    name = people.First().FullName;
}

The above code can be shortened to the below snippet 

var people = new List<Person>();
var name = people.FirstOrDefault()?.FullName;

 

  • Index Initializers : This can be applied to index based collections like Dictionary. 
Dictionary<int, string> dict = new Dictionary<int, string>
{
    {1, "string1" },
    {2, "string2" },
    {3, "string3" }
};

can be re-written as, 

Dictionary<int, string> dict = new Dictionary<int, string>
{
    [1] = "string1",
    [2] = "string2",
    [3] = "string3" 
};

 

 

Happy Coding .... :)

Implementing Knockout.js in MVC Views

In your MVC project add the Nuget Package for Knockout.js and ensure that the Knockout scripts are included in the project.

In _Layout.cshtml add the script reference for the knockout.js file.

<script src="~/Scripts/knockout-3.4.0.js"></script>

Then create a Basic.cshtml file in the Home folder and add the following script.

@{
    ViewBag.Title = "Basic";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Hello <span data-bind="text: name"></span></h2>

@section Scripts{
    <script> 
        var ViewModel = {
            name: 'Hozefa Mangalorewala'
        };

        ko.applyBindings(ViewModel);
    </script>
}

This should bind the span tag with the ViewModel. The ko.applyBindings maps the model to the current view.

 

Happy Coding .... :)

How to Bulk Insert in SQL using User Defined Table Types

Here is a quick way to Bulk Insert data into SQL with the help of User Defined Table Types

Step 1: Create a User Defined Table Types. 

CREATE TYPE UDT_MyTable AS TABLE 
(     
        Name varchar(100),
        Age Int 
 )

Step 2: Create a Stored procedure that accepts the UDT_MyTable as input parameter

CREATE PROC [dbo].[Usp_VUpdate]
       @UserDefineTable UDT_MyTable READONLY
AS
BEGIN

  INSERT INTO MyTargetTable
  (SELECT * FROM UDT_MyTable)
    
END;

Note: Here I am assuming that MyTargetTable is having exactly similar columns to the UDT_MyTable.

 

Happy Coding ...

How to create an Excel like interface using Handsontable plugin - jquery

I had a requirement to create a web application that should have an excel like user input to accept data and perform run-time calculations like Microsoft Excel Formulas handle the calculations.

I came across a jquery plugin that fits my requirement - HandsOnTable. The plugin is seamless and can handle large data, and works perfectly with the calculations that are based on Excel like formulas. They also have an excellent documentation

Lets go through the Quick start steps to use this plugin:

1. Install or reference the js/css for handsontable

<script src="//handsontable.com/dist/handsontable.full.js"></script>
<link rel="stylesheet" media="screen" href="//handsontable.com/dist/handsontable.full.css">

2. Create a div that acts as a placeholder for the control.

<div id="example"></div>

3. Add the following script to set the data and initialize the handsontable plugin with options.

var data = [
  ["", "Ford", "Volvo", "Toyota", "Honda"],
  ["2016", 10, 11, 12, 13],
  ["2017", 20, 11, 14, 13],
  ["2018", 30, 15, 12, 13]
];

var container = document.getElementById('example');
var hot = new Handsontable(container, {
  data: data,
  rowHeaders: true,
  colHeaders: true
});

4. Run the application to see the excel like UI.

There are many advance features available in the plugin... do check it out.

 

Happy Coding ...