Google custom search in c#

Google custom search in c#

Rate this article

Share this article

Read google custom search in c# for more information.

Custom Search API: Searches over a website or collection of websites

This page contains information about getting started with the CustomSearch API using the Google API Client Library for .NET.google custom search in c#

C# – How to use Google Custom Search API?

Google search engine has a market share of over 60%. For some advanced features, such as searching metadata or relevant info of an object, we maybe want to integrate search results of Google search engine instead of inventing our own one. In this post, I would like to write down the steps on how we can consume Google Custom Search API in .Net. The code itself is pretty short. However, because of lacking documentation it’s really time-consuming to find out how the code should be, where to get the API Key or Search Engine ID for authentication. These all settings stuff drive me crazy because they locate on different control panels.
Please note that Custom Search Engine is a free API edition. For CSE users, the API provides 100 search queries per day for free. If you need more, you may sign up for billing in the Developers Console. Additional requests cost $5 per 1000 queries, up to 10k queries per day.

Code

For consuming Google Custom Search API, luckily we don’t have to write our own code for reading/writing REST object. Google has also provided a Nuget package Google.Apis.Customsearch.v1 for .NET client. In your project, just simply add a reference to it over Nuget.

private static void Main(string[] args)
{
    const string apiKey = "AIzaSyAt8AkrmkiLVghrcKA3lFh37R79rSG0NsE";
    const string searchEngineId = "003470263288780838160:ty47piyybua";
    const string query = "expertrec";
    var customSearchService = new CustomsearchService(new BaseClientService.Initializer {ApiKey = apiKey});
    var listRequest = customSearchService.Cse.List(query);
    listRequest.Cx = searchEngineId;
 
    Console.WriteLine("Start...");
    IList<Result> paging = new List<Result>();
    var count = 0;
    while (paging != null)
    {
        Console.WriteLine($"Page {count}");
        listRequest.Start = count * 10 + 1;
        paging = listRequest.Execute().Items;
        if (paging != null)
            foreach (var item in paging)
                Console.WriteLine("Title : " + item.Title + Environment.NewLine + "Link : " + item.Link +
                                  Environment.NewLine + Environment.NewLine);
        count++;
    }
    Console.WriteLine("Done.");
    Console.ReadLine();
}

We have to initialize an instance of CustomsearchService with the API key. Using this instance for generating a query of keyword expertrec over Cse property. This query requires a Search Engine ID, so remember to set its Cx property by this value. In the end just simply call Execute() to get the search result.

Build a fully customizable Search without any coding

Add Google custom search in asp.net MVC website

  1. Create a new project of MVC in visual studio
  2. Add below code in _Layout.cshtml
    <div style="width:300px; text-align:right; margin-bottom:10px;">
        <input type="text" value="Search" style="width:200px;"
                id="q" name="q" onblur="if(this.value == '') this.value=this.defaultValue;"
                onfocus="if(this.value == this.defaultValue) this.value = '';"
                onkeypress="return SubmitOnEnter(this, event);" class="form-control" />
        <input type="button" value="Search" onclick="SiteSearch();" style="padding:4px; margin:0px;" class="form-control" />
    </div>
     
    <script type="text/javascript">
        function SubmitOnEnter(searchBox, event) {
            var keyCode;
            if (window.event) {
                keyCode = window.event.keyCode;
            }
            else if (event) {
                keyCode = event.which;
            }
            else {
                return true;
            }
            if (keyCode == 13) {
                // This is for Enter Key
                SiteSearch();
                return false;
            }
            else {
                return true;
            }
        }
     
        function SiteSearch() {
            document.location.href = "/GoogleSearch/SearchPosts?q=" +
                EncodeText(document.getElementById('q').value); // Here we should use url encode for the user input
        }
     
        function EncodeText(value) {
            var returnValue = "";
            var x = 0;
            var regex = /(^[a-zA-Z0-9_.]*)/
            while (x < value.toString().length) {
                var match = regex.exec(value.substr(x));
                if (match != null && match.length > 1 && match[1] != '') {
                    returnValue += match[1];
                    x += match[1].length;
                }
                else {
                    if (value[x] == ' ') {
                        returnValue += '+';
                    }
                    else {
                        var charCode = value.charCodeAt(x);
                        var haxValue = charCode.toString(16);
                        returnValue += "%" + (haxValue.length < 2 ? '0' : '') + haxValue.toUpperCase();
                    }
                    x++;
                }
            }
            return returnValue;
        }
    </script>
  3. dd new “GoogleSearchController” Controller and add below code snippet with Action named with “SearchPosts”
    using System.Web.Mvc;
     
    namespace GoogleSearch.Controllers
    {
        public class GoogleSearchController : Controller
        {
            // GET: /GoogleSearch/SearchPosts/q
     
            public ActionResult SearchPosts(string q)
            {
                return View();
            }
        }
    }
  4. Add View for this controller and add below code snippet.
    @{
        ViewBag.Title = "SearchPosts";
    }
    
    <h2>Search Posts</h2>
    
    
    <script>
        (function () {
            var cx = '004190376073915964254:jgkqwbmrfpe';
            var gcse = document.createElement('script');
            gcse.type = 'text/javascript';
            gcse.async = true;
            gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
                '//www.google.com/cse/cse.js?cx=' + cx;
            var s = document.getElementsByTagName('script')[0];
            s.parentNode.insertBefore(gcse, s);
        })();
    </script>
    <gcse:searchresults-only></gcse:searchresults-only>

Add routing to get proper search engine enabled URL by adding below code snippet in RouteConfig.cs as below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace GoogleSearch
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
               name: "SearchMovie",
               url: "GoogleSearchController/{action}/{q}",
               defaults: new { controller = "GoogleSearchController", action = "SearchPosts", q = UrlParameter.Optional }
           );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

Alternative

You can now run the code to check out the search. If you want to skip the hassle and set up a search with just a few clicks, then try out ExpertRec.

  1. Signup at https://cse.expertrec.com/?platform=cse
  2. Enter your website’s URL and wait for the crawl to complete
  3. Add the code snippet to your website to take the search live
Are you showing the right products, to the right shoppers, at the right time? Contact us to know more.
You may also like