jQuery UI autocomplete with ASP.NET Web API

jQuery UI autocomplete enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering.

Step 1 : Getting Web Api Ready

Lets first create a web api method that will return a list of item (Artists) using the search term query sent from the autocomplete textbox. In this post I am not using database, instead I’ll be using List to keep this example as simple as possible.

Below is how I have defined my Artist class

public class Artist
{
    public int Id { get; set; }
    public int Name { get; set; }
}    

Next I have created a Web Api GET method that will use the search term entered in the autocomplete textbox and with a little help of LINQ will return a list of matching results.

using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace Autocomplete.Controllers
{
    public class ArtistApiController : ApiController
    {

        public List<Artist> ArtistList = new List<Artist>
        {
            new Artist{Id = 1, Name = "Sonu Nigam"},
            new Artist{Id = 2, Name = "Sunidhi Chauhan"},
            new Artist{Id = 3, Name = "Shreya Goshal"},
            new Artist{Id = 4, Name = "Mohit Chauhan"},
            new Artist{Id = 5, Name = "Nihkil Dsouza"},
            new Artist{Id = 6, Name = "Kailash Kher"},
            new Artist{Id = 7, Name = "Atif Aslam"},
            new Artist{Id = 8, Name = "Ali Zafar"},
            new Artist{Id = 9, Name = "Shafaqat Ali"},
            new Artist{Id = 10, Name = "Shankar Madahevan"}
        }; 


        // GET api/values
        public IEnumerable<Artist> Get(string query)
        {
            return ArtistList.Where(m => m.Name.Contains(query)).ToList();
        }
    }
}   

Our server side code is ready ! Time to test it out.

autocomplete test

Step 2 : Client side code

Include jquery-ui.js and jquery.ui.css in your html

<script type="text/javascript" src="~/Scripts/jquery-1.7.1.min.js" ></script>
<script type="text/javascript" src="~/Scripts/jquery-ui-1.8.20.min.js" ></script>
<link href="~/Content/themes/base/jquery.ui.all.css" rel="stylesheet" />

<div id="body">
    <label for="autocomplete-textbox">Search : </label>
    <input type="text" id="autocomplete-textbox" />
</div>

<script type="text/javascript">
$(document).ready(function (){
$('#autocomplete-textbox').autocomplete({
    source: function (request, response) {
        // prepare url : for example '/api/artistapi?query=sonu
        var autocompleteUrl = '/api/artistapi' + '?query=' + request.term;
        $.ajax({
            url: autocompleteUrl,
            type: 'GET',
            cache: false,
            dataType: 'json',
            success: function (json) {
                // call autocomplete callback method with results  
                response($.map(json, function (data, id) {
                    return {
                        label: data.Name,
                        value: data.Id
                    };
                }));
            },
            error: function (xmlHttpRequest, textStatus, errorThrown) {
                console.log('some error occured', textStatus, errorThrown);
            }
        });
    },
    minLength: 2,
    select: function (event, ui) {
        alert('you have selected ' + ui.item.label + ' ID: ' + ui.item.value);
        $('#autocomplete-textbox').val(ui.item.label);
        return false;
    }
});
});
</script>

One thing to note here is that inside the success method I have used the following code :

response($.map(json, function (data, id) {
    return {
        label: data.Name,
        value: data.Id
    };
}));

data.Id and data.Name is used because in the ajax response (as shown below) data is returned in this format.

autocomplete ajax response

Step 3 : Test & Output :

autocomplete output

Hope this helps :)

Select Date Range using Jquery DatePicker.js and DatePick.js

The jQuery UI Datepicker is a highly configurable plugin that adds datepicker functionality to your pages. DatePick.js is a similar plugin is formed using the basis as jQuery UI Datepicker. It is made available as a separate plugin because the jQuery UI version desired simplified functionality.

1. Select Date Range using Datepick.js [Demo on Jsfiddle] [Demo on Datepick.js Website]

Html:

<p>
    <span class="demoLabel">Date range:</span>
    <input type="text" id="rangePicker" size="20" />
</p>

Jquery:

$(function(){
   $('#rangePicker').datepick({ 
        rangeSelect: true
    });
});

Output: datepick range selection

2. Select Date Range using Datepicker.js [Demo on Fiddle] [Demo on Jquery UI Website]

Html:

<label for="from">From</label>
<input type="text" id="from" name="from" />

<label for="to">to</label>
<input type="text" id="to" name="to" />     

Jquery:

$(function() {
    $( "#from" ).datepicker({          
      onClose: function( selectedDate ) {
        $( "#to" ).datepicker( "option", "minDate", selectedDate );
      }
    });
    $( "#to" ).datepicker({
      defaultDate: "+1w",  
      onClose: function( selectedDate ) {
        $( "#from" ).datepicker( "option", "maxDate", selectedDate );
      }
    });
});

Output: date picker range

Adsense Dashboard – Best adsense app for android

Google AdSense is a program run by Google Inc. that allows publishers in the Google Network of content sites to serve automatic text, image, video, and rich media adverts that are targeted to site content and audience.

Android Dashboard provides a heads-up overview over critical AdSense performance metrics, including CPM, CTR, page views, clicks, and estimated revenue, in easily-digestible form.

adsense dashboard

Includes a desktop widget showing today’s vital statistics.

Screenshot_2013-04-10-10-37-00

Uses Google’s AdSense Management API to provide a secure, read-only view of your data. Supports phones with large screens, tablets, and now Google TV (for those that want an always-on dashboard for their office).

adsense horizontal

Download now from Google Play Store or scan this QR code with your android to start with your installation :

download adsense dashboard

Know a better app ? Please share your thoughts and feedback using the comment section below.

Cheers !

HTC First Announced, releasing on April 12 for $99.99

  • Ready for a new phone? Get the HTC First for $99

    The HTC First is the best Home experience possible. There’s no setup—just turn it on, log into Facebook, and see your friends. Available in matte black, white, red and pale blue with a 4.3″ screen, 5 megapixel rear-facing camera and LTE capability. Exclusively at AT&T. Available April 12 in the US. Buy Now.

  • Already have an Android? Download Home for free.

    Get Facebook Home on your own Android in 3 steps. Add the Messenger and Facebook apps for the full experience. Facebook Home for Android will be available for download from the Google Play Store on certain devices, including the HTC One X, HTC One X+, Samsung Galaxy S III and Samsung Galaxy Note II.

htc first pic 1

htc first pic 2

How to take screenshot with Sony Xperia series phones ?

Note : I recently bought myself a Sony Xperia ION.

There are two ways to take screenshot with Sony Xperia series smartphones.

Method 1 (Applicable to Gingerbread) : If the phone has not been upgraded to the ICS (Ice Cream Sandwich) OS, hold down the POWER button and on the option screen is a TAKE SCREENSHOT option

Method 2 (Applicable to Android 4.0 ICS and above) : Hold down the VOLUME DOWN button and the POWER button.

Below is a screenshot from my Xperai ION. (Click on it to zoom) Screenshot_2013-04-05-12-11-24

Hope this helps :)

A list of top and most useful WordPress Plugins

This post has a list of some of the best WordPress Plugins out there. I have been using each of these plugins on this blog for over 2 years, please feel free to share and add plugins I may have missed out using the comment section. Cheers !

Essentials

  • Akismet : Akismet checks your comments against the Akismet web service to see if they look like spam or not.

  • WP-Markdown : Allows Markdown to be enabled in posts, comments and bbPress forums.

  • Disqus Comment System : The Disqus comment system replaces your WordPress comment system with your comments hosted and powered by Disqus.

  • W3 Total Cache : Easy Web Performance Optimization (WPO) using caching: browser, page, object, database, minify and content delivery network support.

  • WordPress Backup to Dropbox : Keep your valuable WordPress website, its media and database backed up to Dropbox in minutes with this sleek, easy to use plugin.

  • WordPress SEO by YOAST : Improve your WordPress SEO: Write better content and have a fully optimized WordPress site using the WordPress SEO plugin by Yoast.

  • Contact Form 7 : Just another contact form plugin. Simple but flexible.

  • Flare : Flare is a simple yet eye-catching social sharing bar that gets you followed and lets your content get shared via posts, pages, and media types..

Analytics and Adsense

  • Google Analytics for WordPress : Track your WordPress site easily and with lots of metadata: views per author & category, automatic tracking of outbound clicks and pageviews.

  • Woopra : This plugin adds Woopra’s real-time analytics to any WordPress installation.

  • Feedjit Live Traffic Feed : Feedjit lets you see friends and visitors as they arrive on your blog or website. Know when your best friends read about your latest adventure. Be alerted when your most important clients view your latest product offering. Feedjit lets you know, right now, who is visiting your site. Simply add the Live Traffic Feed and instantly start seeing who is visiting your site as they arrive.

  • Traffic Counter Widget : TCW lets your users know how much traffic you have on your blog. It counts pages visited, hits and unique IPs on your blog and shows it in a widget.

Others

  • Executable PHP widget : Like the Text widget, but also allows working PHP code to be inserted.

  • WP Easy Uploader : Easily upload any type of content without the need for FTP. You can even upload plugin and theme archives, and the files will be extracted for you.

  • WPtouch : WPtouch: A simple, powerful & elegant mobile theme for your website.

  • Yet Another Related Posts Plugin : Display a list of related entries on your site and feeds based on a unique algorithm. Now with thumbnail support built-in!

  • Broken Link Checker : This plugin will check your posts, comments and other content for broken links and missing images, and notify you if any are found.

  • Bottom of Every Post : This plugin adds some content to the bottom of every post. That is all. No extra crap.

  • Smart Archives Reloaded : Easily display posts grouped by year and month, in one or more elegant formats

Further Reading : Tips And Tricks HQ : List of the Best and Must Use WordPress Plugins