YouTube Android Player for Xamarin.Android

Xamarin-YouTube-Android-Player Have you tried embedding a YouTube video into your android app? May be you tried using the HTML to embed the YouTube player in a WebView. From a developer perspective they aren’t programmable – meaning if you wish to interact with the player like play, pause, forward, go full screen, change video quality etc from your app, there isn’t a straight way to do it. From a user perspective the experience isn’t nice and you definitely want to work a better way out. Fortunately, Google provides a slick native YouTube Player on Android platform and a player API written in Java. The player API is a set of client libraries that interacts with a service that is distributed as a part of the YouTube Android app itself. That said, you need to ensure that the YouTube App is installed in the user’s device beforehand. The advantage is - your app size does not bloat up and you can upgrade the client libraries to incorporate new changes to the YouTube app anytime. And, upgrading is not necessary if you do not care about new features or bug fixes.

Bringing this beauty to Xamarin in C#

Lot of developers out there haven’t unleashed the full potential of the Xamarin platform yet. One of the big wins for Xamarin over any other cross-platform solutions is the power to reuse the existing Java and Obj-C (in case of iOS) libraries in C#. Apps built-in Xamarin are fully native and anything that you can do with Java in Android or Objective-C/Swift in iOS can be done in C# using Xamarin. Java ecosystem is large and it is  likely that a functionality that you want in Xamarin.Android may have already been written in Java just like the YouTube Android player in this case. Technically, you will use Bindings to bring any reusable Java library to Xamarin.Android. Alternatively, you can use JNI framework or port the entire Java code to C# using an automated tools like Sharpen. In this case, I downloaded the YouTubePlayer API jar file  and bound this using the Java Bindings Library project which is part of my solution. This project generates C# dll of your jar file and they are referenced into my Android project just like any other C# dll.  I have plans of writing a dedicated post on bindings and you can expect that soon. For now, I suggest, you read the official documentation.

Using the YouTubeAndroid player in C#

The bindings project dll that is referenced into your main Android app has the full Java API in C# along with the beautiful features of C# that you can utilize – like anonymous methods, lambdas, Linq etc. The solution also includes a samples project that helps you understand each of the API features in detail. So, you can copy and paste the entire code “as is” to make it work with your app.

[Update:] See how @xakpc adds async-await feature to his YouTube Thumbnail sample and unleashes the full potential of C#.

Source Code

If all that you care is the binding library or you are aware of how to get started with it - Head straight to my github for download. Please note: You can execute theses samples only on a physical device that has YouTube App installed. If you have an emulator that has the Google Play Services installed then it may work there too – I haven’t tested this so can’t guarantee!

Before you start

Get a developer key from Google and register your application. Add your key to the DeveloperKey.cs file

public static class DeveloperKey
{
 public static string Key = "";
}

Simple PlayerView

This sample shows how to use a YouTubePlayerView to play a video.

Resource file (PlayerView.axml)

First add the player to your resource file -


Activity(PlayerViewActivity.cs)

In the onCreate() method, instantiate your YouTubePlayerView and initialize it with your DeveloperKey.

YouTubePlayerView youTubeView = FindViewById(Resource.Id.youtube_view);
youTubeView.Initialize(DeveloperKey.Key, this);

To start playing your video cue the video to the player’s playlist.

public override void OnInitializationSuccess (IYouTubePlayerProvider provider, IYouTubePlayer player, bool wasRestored)
{
if (!wasRestored) {
player.CueVideo("wKJ9KzGQq0w"); }
}

CueVideo method takes the YouTube video id that you want to play and loads them to your playlist. When user clicks play, well, they get played :-) Noticed the OnInitializationSuccess method that is overriden? I use a helper activity called YouTubeFailureRecoveryActivity as the base class for all the samples. This class handles all the failure and recovery mechanism in the Android player.

That’s it!

Don’t forget to take a look at the PlayerControlsActivity.cs file if you want to know how to interact with the player – like play, pause, seek to position, change player style etc.

ScreenShot1

Hope this helps you!

Thanks!

Say Hello to Nokia X in C# and Visual Studio

Nokia-X--

Nokia recently introduced the Nokia X family of smartphones, which provides users access to the world of Android. The good news for C# developers is that using Xamarin you can start writing apps for this platform from day 1. If you’re new to building Android apps in C#, do check out my blog post on “How I built an Android app in C# & Visual Studio in less than 24hrs” that I wrote few months back.

NokiaXStack

Setting things up

The core Nokia X platform is built on Android Open Source Project v4.1.2, which supports API level 16. That means you’ll be targeting API 16(4.1.2) for your app development. You’ll also need to install Nokia X specific packages in the Android SDK Manager.

Configure Nokia X specific packages

Start Android SDK Manager from Visual Studio.

  1. Select Tools > Manage Add-on Sites
  2. Open User Defined Sites tab and click the New… button
  3. Enter the following URL to the Add Add-on Site URL dialog:
    http://tools.nokia.com/nokia-x/repository/addon.xml
  4. Click OK

Add-On_Nokia-X

Install Nokia X specific packages and API level 16

Be sure to install Nokia X System Image under Android 4.1.2(API 16)

Nokia-X-API16-Install

You’ll also need to install the following extras:

  • Nokia X Device Definitions
  • Nokia X services
  • Nokia X USB Driver
  • Intel x86 Emulator Accelerator(HAXM) (optional)

Nokia-X-API16-Extras

Configure Nokia X emulator

Open Android Emulator Manager from Visual Studio and create a new emulator with the following configuration:

  • Give your emulator a name say Nokia-X
  • Select the Device Nokia X (480 x 800; hdpi)
  • Select Intel Atom (x86), if you have HAXM installed and Intel VT-X enabled (gives you a faster emulator)
  • Be sure to select Nokia X Services under Target
  • Have an SD card with a desired size
  • Select Use Host GPU as emulation options

Nokia-X-API16-CreateAVD

Kick Start the Emulator

Nokia-X-Start Nokia-X_running

Hello World

Writing your first app on Nokia X using Xamarin is as simple as creating a regular Android app in Visual Studio.

File > New Project > Visual C# > Android > Android Application

Nokia-X-Visual-Studio

In your project properties, be sure to compile your Android app with Version 16 or lower.

Android-Visual-Studio-Properties

That’s it. Go Run your first app!

Nokia-X-HelloC#

I had a simple code to Toast Notify with a custom message on a button click. When I ran it, I saw the message appearing on the top left corner instead of the usual Android toast. Looks like few things have changed here. Refer Nokia X Design Guidelines for changes that you must be aware of.

Nokia X Components

Nokia has shipped Xamarin components for their Nokia X SDK. Don’t forget to check them out at the component store.

Mike Bluestein has a nice post on Nokia HERE Maps component - Use Nokia X HERE Maps with Xamarin.Android.

Nokia-X-Component-Xamarin

- Cheers!

Adding custom buttons to iOS Keyboard in C# & Xamarin

What if you needed some extra keys for text input in your iOS app? Say for e.g.  if you needed text based emoticons on top of the standard keyboard for a chat application. Thankfully UIKit allows apps to have an accessory view above the system keyboard. The area above the keyboard is an extra UIView known as Input Accessory View which you can customize to add your extra keyboard buttons. To add an accessory view, all you gotta do is, set the InputAccessoryView property of the UITextView or UITextField  to an appropriate custom view.

Here’s how the extra keys on top of your standard keyboard looks like:

iOS-Custom-Buttons-C#-Xamarin

Following code sets the text based emoticons to the InputAccessoryView:

		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			UIToolbar toolbar = new UIToolbar (new RectangleF(0.0f, 0.0f, this.View.Frame.Size.Width, 44.0f));

			toolbar.TintColor = UIColor.White;
			toolbar.BarStyle = UIBarStyle.Black;

			toolbar.Translucent = true;

			var myButton = new UIBarButtonItem (":-)",
				UIBarButtonItemStyle.Bordered, AddBarButtonText);

			toolbar.Items = new UIBarButtonItem[]{
				myButton,
				new UIBarButtonItem(":-)",
					UIBarButtonItemStyle.Plain, AddBarButtonText),
				new UIBarButtonItem(":-(",
					UIBarButtonItemStyle.Plain, AddBarButtonText),
				new UIBarButtonItem(";-)",
					UIBarButtonItemStyle.Plain, AddBarButtonText),
				new UIBarButtonItem(":-P",
					UIBarButtonItemStyle.Plain, AddBarButtonText),
				new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
				new UIBarButtonItem(UIBarButtonSystemItem.Done, delegate {
					this.SampleText.ResignFirstResponder();
			})
			 };

			this.SampleText.KeyboardAppearance = UIKeyboardAppearance.Dark;
			this.SampleText.InputAccessoryView = toolbar;
		}

		public void AddBarButtonText(object sender, EventArgs e)
		{
			var barButtonItem = sender as UIBarButtonItem;
			if (barButtonItem != null)
				this.SampleText.Text += barButtonItem.Title;

		}

In the above code, we create a UIToolBar with UIBarButtonItems of text based emoticons and set it to the InputAccesoryView property of the SampleText. AddBarButtonText method then handles the key input events.

Playing Input Clicks

You can play standard system keyboard clicks when a user taps in your keyboard accessory views. If you had gone through the apple documentation on Custom Views for Data Input referred earlier, then you would have noticed Objective-C code to do so. Here’s how we can do it elegantly in C#:

  • Create a custom class called MyUIToolBar that inherits from UIToolbar (since we’re using UIToolbar as the custom view for InputAccessoryView)
  • Override the property  EnableInputClicksWhenVisible and return true from it
	public class MyUIToolbar : UIToolbar
	{
		public MyUIToolbar (RectangleF rect) : base(rect)
		{

		}

		public override bool EnableInputClicksWhenVisible {
			get {
				return true;
			}
		}
	}

In the calling code, use the newly created MyUIToolbar

  MyUIToolbar toolbar = new MyUIToolbar (
new RectangleF(0.0f, 0.0f, this.View.Frame.Size.Width, 44.0f));

and make sure you play the sound when user clicks:

public void AddBarButtonText(object sender, EventArgs e)
{
  var barButtonItem = sender as UIBarButtonItem;
  if (barButtonItem != null) {
  this.SampleText.Text += barButtonItem.Title;
  UIDevice.CurrentDevice.PlayInputClick ();
  }
}

Replace the entire keyboard (custom keyboard)?

At times you just want the textbox to input only the keys that you had set. It’s possible to replace the entire keyboard to a custom one. In this case, I just set our emoticon toolbar to InputView property instead of the InputAccessoryView . And this is what it outputs:

iOS-Custom-Keyboard-C#-Xamarin

Source Code

You can download the complete source code from my github repo.

Happy C# Coding!!

-Nish

 

How I built an Android app in C# & Visual Studio in less than 24hrs

Yes you read that right! – I built an android app with the tools that I know – Visual Studio and in my favorite language C#. Well that’s possible because of Xamarin. In case you didn’t know – Xamarin was founded by nice engineers(Nat Friedman & Miguel de Icaza of Mono fame) who built MonoTouch and Mono for Android which are cross-platform implementations of Common Language Infrastructure (CLI) and Common Language Specifications.

I love C# and it has been the language that I have been associated with all my developer life. So when I thought of developing an app for mobile, I wanted to use the tools that I know rather than go learn something new! Being a C# developer it is quite obvious for me to choose Windows Phone or Windows 8 as the mobile platform to launch my app. But wait a minute, I want them to be built on other shiny platforms too – Who’s gonna build the same app for the famous Android and iOS ? Well I want my app to be used by a million users, if not more! HTML5 based hybrid apps are an option but arguably they aren’t the best fit when it comes to User Experience – at least at the time of writing this post.

Forget all that! – I don’t even want to write HTML5 and JavaScript, I want C#. Yeah!!

Xamarin – Why I love it!

Xamarin let’s you create apps in C# for iOS, Android & Mac. Period.

I had a compelling reason (which I am gonna share with you later) to go write a native android app. So I decided to give Xamarin a try – downloaded the trial version and gave it a shot. And the result – a simple app called TripXpense built in less than 24hrs with no knowledge on Android platform or the way it works! Though it’s a simple app, it would have taken me weeks if I had to build it on Java. Most importantly Xamarin let’s me write in Visual Studio with my favorite plugin resharper running on it. What more can I ask?

Xamarin’s Android API exposes almost 100% of the Andriod’s – that  said you can build a complete android app in C#. I must mention this – Xamarin documentation is a piece of great work from their talented team! They are brilliant!! Honestly, I haven’t even visited the Android SDK Documentation for help.

So what’s the app?

Well it’s TripXpense – a simple app that let’s you add Trips and Expenses. There are only 4 screens and there’s nothing shiny in this app yet because you know it – It’s been just 24hours of the code. If you think you can do better – go fork it from GitHub.

2

Disclaimer: I am just sharing my experience of an Android Development on this new amazing platform that I love. That said this is no expert material.  Refer Xamarin & Android documentation for patterns and right way of doing things. The code works on my PC & comes with no warranty.

Few Android related stuff that you should know!

Project Structure:

image

This is how a project structure of an Android app will look. When you create a new Android application in Visual Studio, Xamarin set’s it up for you by default.

Few things to make a note of – only a few for now.

AndroidManifest.xml

Every Android project must contain this file. The manifest lets you define the metadata of your application like Application Name, Package Name, Required Permissions, Activities etc. This is similar to a App.config or Web.Config files but differs in certain ways. In Xamarin you can easily edit manifest information by going to the properties of the project. Please note that there are other values that are auto generated by Xamarin from the attributes that you define in classes. You can learn more about it from the documentation.

Resources

It’s a good practice to keep non-code resources like images, icons, and constants external to your code. Android expects you to store them in a specific sub folders within the resources folder. Notice 6 different Drawable folders which are kept separated based on the DPI displays. These folder will include respective sized bitmaps & PNG images. Perhaps the most powerful Resource to be noted is the Layouts.

Layouts

Layout is the User Interface – Yes that’s right! Whatever user sees is what is designed inside layout files. These are xml based and have the extension .axml . It decouples the presentation layer – much similar to XAML in Windows Phone.

Here’s an example of a layout:

<?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">
    <Button
        android:id="@+id/MyButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/Hello" />
</LinearLayout>

Activity

Activity is the class responsible for setting the UI content for the users to interact! You can consider this as a code-behind for the Layout written in the resources. So the activity class will contain the presentation logic of your view. It is the class that is referenced by the Android system to do the user interaction. Activities are created or destroyed by the Android system. It’s important to understand the Activity Life Cycle to effectively handle user data in the changing states such as Running, Paused, Backgrounded  & Stopped. For the TripXpense app, I am yet to implement this feature. Here’s an example of an Activity.

namespace HelloXamarin.Android
{
    [Activity(Label = "HelloXamarin.Android", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

           // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
        }
    }
}

All your Activity classes should derive from Activity base class. Notice the MainLauncher = true set in custom attribute – this is to set the starting screen of your app!
OnCreate() is called when the activity is created. It’s always overridden to perform startup initializations such as

  • Creating  Views
  • Initializing variables
  • Binding static data to lists

Notice the SetContentView() – It places your layout on the screen. Layouts can be accessed using the static variable Resources.Layout.<yourLayoutName>.

Now let’s add a Click event handler to the button placed in the Layout. Shall we?

To get the reference of the button placed in the layout use the helper method FindByViewId<T>() and pass the Id of the button you set in the resource. Once you get the handle – just add the event to the Click handler.

[Activity(Label = "HelloXamarin.Android", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        private int count = 0;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

           // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button>(Resource.Id.MyButton);

            button.Click += delegate { button.Text = string.Format("{0} clicks!", count++); };
        }
    }

To navigate to another screen and pass some extra information along, use StartActivity() with an intent that contains the extra information. Extra information is nothing but the data that you want to pass between your screens.

          button.Click += (s, e) =>
                {
                    var intent = new Intent(this, typeof(DetailActivity));
                    intent.PutExtra("userCount", count++);
                    base.StartActivity(intent);
                };

Finally to receive the extra information that was passed from the previous screen you can use Intent.GetStringExtra or other type based methods. Here’s the full code:

    [Activity(Label = "DetailActivity")]
    public class DetailActivity : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.Detail);

            var t = FindViewById<TextView>(Resource.Id.textView1);
            t.Text = string.Format("{0}:{1}","You clicked ",Intent.GetIntExtra("userCount", 0));
        }
    }

Now let’s look at the TripXpense app and few fundamentals of the Xamarin app Development.

TripXpense – built using Xamarin!

tripXpense

TripXpense has 4 screens

  1. Home Screen – that shows list of trips and you can add more
  2. Trip Edit Screen – add and edit trips
  3. Trip Details Screen – displays trip summary and Expenses
  4. Expenses edit screen – add and edit expenses
Cross-Platform development

Xamarin supports cross-platform development in C# but it is not just a write once and run everywhere platform. Because one of its strengths is the ability to implement native user interfaces specifically for each platform. So when you architect your apps make sure you separate the code that is shareable across platforms. Refer Building Cross Platform applications.

Separate reusable code into a core library:

For this app I decided to have my database as xml and created all my classes related to business logic, repository and data access in the core library called TripXpense.Core.  In case I decide to build a Windows Phone, Windows 8 or an iOS app in future, these files don’t have to be duplicated.  And they can be unit tested too! Here’s how it looks:

image

Please note – You cannot reference this library directly as it is not targeted to Android. And you don’t want to do so because you want them to be accessed by other platforms. Instead you need to use Project Linker extension for Visual Studio which will ensure you have the same code in your Android project. Refer Visual Studio Project Setup Walkthrough

Create an Android Project in the same solution and link the Core project using Project linker. Here’s how your Android project will look with a small blue icon below :

image

Finally I created the Screens and necessary layouts in Resources and made my app come alive.

Code on Github

You can download this app from my GitHub repository.  Go play around with it and let me know what you think!

Have any questions? Find me on twitter – @nishanil

Building MVVM & Single Page Apps in JS – TechEd Relive session recap

I had a fantastic time speaking at the Tech-ed relive event organized by B.net User Group! Thanks to everyone who attended and made this fun! My special thanks to the organizers at Bdotnet – Vic, Lohith, Vinod & others for inviting me to speak here!

I spoke on topic “Building MVVM & SPA in JS” where I

Here’s the presentation deck:


Demos

Please click on the below links to download the demos:

If you have any questions write to me na[at]nnish[.]com or find me on twitter @nishanil

-Nish

Demystifying “this” in JavaScript

If you have worked with Object Oriented languages in the past and then moving to JavaScript, one of the first thing that you need to do is to understand the usage of “this” operator.

this” in other languages that are class-based like C++, Java & C# points to the object that holds the current instance of the class. JavaScript too provides a similar concept using the same this keyword, but beware! – there is a significant difference. In JavaScript functions are first-class objects and they aren’t part of anything else. So the object declared by this (termed as function context) is not determined by how the function is declared but by how it’s invoked. It means the same function can have different contexts depending on how it’s called.

This can be explained by a simple example:

 <script type="text/javascript">

        window.firstName = "WindowFirstName";
        window.lastName = "WindowLastName";

       function fullName(){
            return this.firstName + " " + this.lastName;
        }

        var person1 = new Object();
        person1.firstName = "Steve";
        person1.lastName = "Jobs";
        person1.fullName = fullName;

        var person2 = new Object();
        person2.firstName = "Nish";
        person2.lastName = "Anil";
        person2.fullName = fullName;

       alert(fullName());
       alert(person1.fullName());
       alert(fullName.call(person2));

    </script>

 

In the above code sample notice the function fullName() which returns firstName and lastName and how they access the properties using this operator.  Each alert defined here provides a different output and explains the function context in its true sense! Let’s explore each of the outputs –

alert(fullName())

Here fullName() is accessed as top-level function and remember the top-level functions are properties of window so the function context will be the window itself. In this execution the code will look for firstName and lastName in the window object which is actually set on top with values WindowFirstName & WindowLastName! So the output will be:

image

alert(person1.fullName())

 fullName is a property that is defined within persorn1 object which internally holds the reference of the function fullName. So in this case the function context will be of the calling function person2 and hence it returns values of firstName & lastName defined within the object.

image

alert(fullName.call(person2))

In JavaScript you can explicitly control what’s used as the function context by invoking a function via the Function methods call() &apply().

In this case we are invoking the function using the call() method and specifying the first parameter as it’s function context. person2 is passed to the call() method which set’s the function context as person2.  Hence the output:

image

Hope this post explained “this” in JavaScript and why you should care! You can read more on using this at the Mozilla developer Network documentation.

-Nish

Normalize CSS instead of Reset

Previously I wrote about Why Reset CSS and gave you a code snippet that helps you override browser defaults and set consistency across all.  But I later figured out that it was an age old trick and web has changed a lot since then. Now we need more modern HTML5 alternative to the traditional reset.

Normalize.css is a better alternative to reset because it preserves useful browser defaults rather than erasing them. It has CSS that normalizes HTML5 elements, typography, lists, embedded content, forms and tables.

Have a look at this example on how search field is set consistent across browsers:

 <pre>
  input[type="search"] {
    -webkit-appearance: textfield; /* 1 */
    -moz-box-sizing: content-box;
    -webkit-box-sizing: content-box; /* 2 */
    box-sizing: content-box;
}
</pre>

In addition to normalizing it also corrects common bugs for desktop and mobile browsers which is out of scope for resets.

Simplest difference between the two is that – Reset removes all built-in browser styling and Normalize aims to make built-in browser styling consistent across browsers.

So who’s using it?

Twitter Bootstrap, HTML5 Boilerplate, CSS Tricks and many other frameworks use Normalize CSS.

Further Read

Normalize.css has pretty neat inline documentation and there are additional detail and explanation on their wiki page.

There is also a nice article by @necolas on About Normalize.css which will help you understand the details.

- NishAnil on twitter

‘LESS’– a better way to write CSS

css-less-nnish

Are you a programmer like me who thinks design is a planet just outside your universe? Then you know CSS is fun, exciting and easy until your website grows fat with pages and complicated layouts. If you have ever tried fixing a layout in such a page – you know what I mean. Did I talk about fixing a layout? Oh yeah thanks to all the browsers.

Many at times while writing CSS I wished I could write it more programmatically than just styling them. For e.g. If CSS had allowed variable declarations, I could have simply held the values in variables, perform few operations and re-use them in properties. But that’s too much to ask for from a stylesheet language which should just do styling!

After doing couple of research I came across LESS – The dynamic stylesheet language. I spent a few hours re-styling some of my demos with LESS and I am must say I am thoroughly impressed with it. 

Read more on my Infragistics blog ‘LESS’– A dynamic language that simplifies your CSS

Have a feedback? Let me know @nishanil

by Nishanth Anil

Why reset CSS?

css-reset-nnish

Have you noticed inconsistent rendering of HTML elements in different browsers and have got annoyed with it? This is because all the browsers have presentation defaults but none have the same default. For e.g. the way chrome renders an input type is totally different from the way IE does.  But as a web developer you want your web pages to look same(at least close enough) across browsers. One way is to go fix for every browser in CSS files but another way is to simply reset your html tags to default and the paint them again!

Here’s the code for it:

  <pre>html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}</pre>

Note: Remove the <pre> tag from the above code while pasting.

See Original Source here. And here’s an elaborate reason for CSS reset from Meyerweb.

- Nish

@NishAnil on twitter