Intergrating with google Search API Monday, Sep 27 2010 

Google created a search API web service that allow us to search billions of web pages from our own applications, those web services can be exposed from any programming environment such as .Net or java.

So the following are the needed steps for integrating with this service and small .Net sample .

  1. You can download the Developers Kit which contains .net and java samples and the wsdl file from the following Url.

  2. You must have google account ‘gmail’ in order to get the license key for using this API. So if you don’t have an account you should go to the following link and create one.

    or if you already have one just sign in and an email message containing the license  key will be sent to you .

  3. After you get the license key you can start develop the application which we will mention in the following steps.

    • Open Visual Studio .Net 2003 or 2005
    • Choose new project and select the type and your preferred language ‘ we will choose win app with C# in our example’
    • Right click in the solution explorer and choose add web reference and write the following url  in the appeared dialog

      And choose add reference as in the picture.

    • Put in the form a textbox and change its ID to Txt_Text for the search and put a button and change it’s ID to Btn_Search
    • Drag and drop a datagrid if you are using 2003 or datagridview if 2005 .
    • Write the following code under the Btn_Search _Click event. s = new; r = s.doGoogleSearch(“put your lisence key her “, Txt_Text.Text, 0, 10, false, “”, true, “”, “”, “”);
      int estimatedCount =r.estimatedTotalResultsCount;

      DataTable dtResults = new DataTable();
      dtResults.Columns.Add(new DataColumn(“Title”, typeof(string)));
      dtResults.Columns.Add(new DataColumn(“Summary”, typeof(string)));
      dtResults.Columns.Add(new DataColumn(“URL”, typeof(string)));
      for (int i = 0; i < 10; i++)
      DataRow dr = dtResults.NewRow();
      dr[0] =  r.resultElements[i].title;
      dr[1] =  r.resultElements[i].snippet;
      dr[2] = r.resultElements[i].URL;
      dataGridView1.DataSource = dtResults;

This is the running application

Source is taken from:


Working with Google Chart Tuesday, Sep 21 2010 

Getting Started

The quickest way to make a chart for your web page is to use our new chart wizard. Copy and paste the URL generated by the wizard into your web page inside an<img> tag.

For more advanced users, for chart types or features not supported by the wizard (such as candlestick charts), or for a deeper understanding of how the API works, read the rest of this page.


The Google Chart API returns a chart image in response to a URL GET or POST request. The API can generate many kinds of charts, from pie or line charts to QR codes and formulas. All the information about the chart that you want, such as chart data, size, colors, and labels, are part of the URL. (For POST requests, it’s a little different, but don’t worry about that now).

To make the simplest chart possible, all your URL needs to specify is the chart type, data, and size. You can type this URL directly in your browser, or point to it with an <img> tag in your web page. For example, follow this link for a pie chart:×100&chd=t:60,40&cht=p3&chl=Hello|World

The preceding link is an example of a basic Chart API URL. All Chart URLs have the following format:<chart_type>&chd=<chart_data>&chs=<chart_size>&...additional_parameters...

All URLs start with followed by the parameters that specify chart data and appearance. Parameters are name=valuepairs, separated by an ampersand character (&), and parameters can be in any order, after the ?. All charts require at minimum the following parameters: cht (chart type), chd (data), and chs (chart size). However, there are many more parameters for additional options, and you can specify as many additional parameters as the chart supports.

Let’s examine the URL above in more detail:

Yellow pie chart,40&chl=Hello|World
This is the base URL for all chart requests. (However, see Improving Performance on Pages with Many Charts below for an optional variation for pages with multiple charts.)
The chart type: here, a 3D pie chart.
The chart size (widthheight), in pixels. See the maximum values here.
The chart data. This data is in simple text format, but there are other formats.
The slice labels.
Parameters are separated by an ampersand. Note: When embedding an URL in HTML, for example as the src attribute of an <img> tag, you should replace the & between parameters with the characters&amp; This includes when you generate page HTML with PHP or some other language. However, when typing a URL in the browser, or when calling a URL in code, for example when fetching a URL in PHP or Perl, you should use the & mark.

Copy and paste this URL in your browser and try making a few changes: add additional values to the data (don’t forget to add a comma before each new data value). Add new labels (put a | mark before each new value). Make the chart bigger.



For using google chart wizard:


Google Analytics API integration with ASP.Net Tuesday, Sep 21 2010 

Recently I got a chance to work on Google Analytics API integration with application.

I searched lot through net but dint satisfied with the result and finally after doing lots of R&D and taking ideas and collecting information’s from different sites I have decided to put such kind of code under one roof. So here is the code for those who wants GA data in their application.

You must be having google account to login to let google track your web site visits and traffics [such kind of job has been handled by SEO team for the page ranking procedure].

Instead of taking much time I am directly shifting to coding part for the same. Just start with the initial code snippet.

// set username and password of your google analytics account account.
string userName = “”;
string passWord = “”;
const string dataFeedUrl = “;;
AccountQuery query = new AccountQuery();
AnalyticsService service = new AnalyticsService(“AnalyticsSampleApp”);
if (!string.IsNullOrEmpty(userName))
service.setUserCredentials(userName, passWord);
string str = “”;
AccountFeed accountFeed = service.Query(query);
foreach (AccountEntry entry in accountFeed.Entries)
str = entry.ProfileId.Value;

Once you get through with GA credential process you can start doing your stuff.

Following code snippet helps you to get total no of visits of your site, you can set the date range to retrieve the data in-between.

DataQuery query1 = new DataQuery(dataFeedUrl);
query1.Ids = str;
query1.Metrics = “ga:visits”;
query1.Sort = “ga:visits”;
query1.GAStartDate = DateTime.Now.AddMonths(-1).AddDays(-2).ToString(“yyyy-MM-dd”);
query1.GAEndDate = DateTime.Now.AddDays(-3).ToString(“yyyy-MM-dd”);
query1.StartIndex = 1;
DataFeed dataFeedVisits = service.Query(query1);
foreach (DataEntry entry in dataFeedVisits.Entries)
string st = entry.Title.Text;
string ss = entry.Metrics[0].Value;
_intVisists = Int32.Parse(ss);
Response.Write(“Total Visits : ” + ss);



This is the output for your kind consideration that i have tested for my site.

The attached ZIP is a full test solution where you can find complete source code for finding overall pageviews, bounce rate, countrywise visitors etc.. and also attached required DLL for the same.


Working with GoogleMap Control in ASP.NET Wednesday, Sep 8 2010 


This article will show you how to implement the open source Google Map control for .NET hosted at
The final result of the step-by-step guide on implementing the control can be seen on the image below:

Looks nice and simple. What this application will allow you to do is to search for any city or address (addresses are best tested with some US addresses like “25th Avenue New York”) and zoom in on the location and placing a marker on the given location. Let’s move on.

Downloading and adding the GoogleMap control to your project

First things first, we need to download the control from Codeplex and reference it either inside our page or globally inside the web.config file. To download the control go to and click the Download button on the right of the page. You will be redirected to a new page where you will be asked whether or not you agree to the terms of the licence. Click I Agree and download will begin. It’s a small file so it should be finished quickly. Once the download is complete open up the folder where you saved the file and unpack the control by using Winrar or some other similiar unpacking tool. Open up the unpacked folder and you will be presented with 2 files: Artem.GoogleMap.pdb and Artem.GoogleMap.dll.

Create a new web application in your Visual Studio and add a new folder named Bin. Now right click the newly created folder and select “Open folder in Windows Explorer”. This will open the newly created folder. Copy the above mentioned files to this folder and close Windows Explorer.

Now, there are 2 ways to reference the control inside your project. 1st is to globally register the control in every page of the project by using the web.config file and 2nd is to register the control under Page declaration only on the Page where you will use the control. Since this application consists of only 1 page I will use the 2nd approach. This is what the Register control declaration looks like on the page:

<%@ Register Assembly=”Artem.GoogleMap” Namespace=”Artem.Web.UI.Controls” TagPrefix=”cc1″ %>

Of course, you can change the TagPrefix if you want but there’s no need to. The 2nd step to be able to test the map locally is to Sign Up for the Google Maps API Key. This can be done really easily by visiting the following URL:

Note however that this requires you to have a Google account to register. When asked to enter your website’s URL just enter localhost so at the end it looks like http://localhost

When you’ve done this you will be sent to another page and you will see your Google Maps API Key on the top of the page. Save it somewhere so you have it for future reference.

Page markup and Javascript

<%@ Page Language=”C#” AutoEventWireup=”true”  CodeFile=”Default.aspx.cs” Inherits=”_Default” %>

<%@ Register Assembly=”Artem.GoogleMap” Namespace=”Artem.Web.UI.Controls” TagPrefix=”cc1″ %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “”&gt;

<html xmlns=””&gt;
<head runat=”server”>
<title>Google Map Tutorial</title>
<link href=”css/default.css” rel=”stylesheet” type=”text/css” />
<script type=”text/javascript”>
function getLatLongValues(overlay, point) {
if (point) {
document.getElementById(“latValue”).value =;
document.getElementById(“lngValue”).value = point.lng();

function setFocus(controlName) {
<body onload=”setFocus(‘txtCity’);”>
<form id=”form1″ runat=”server”>
<div class=”pagewrapper”>
<div id=”header”>
City name or address: <asp:TextBox ID=”txtCity” runat=”server”></asp:TextBox>
<asp:Button ID=”btnSearch” runat=”server” Text=”Go” onclick=”btnSearch_Click” />
<cc1:GoogleMap ID=”mapControl” runat=”server” OnClientClick=”getLatLongValues” Width=”100%” Height=”740px” Zoom=”3″ Latitude=”10″Longitude=”10″ Key=”PUT YOUR MAPS API KEY HERE”>

<asp:HiddenField ID=”latValue” runat=”server” />
<asp:HiddenField ID=”lngValue” runat=”server” />

As you can see the markup is rather simple. We have a header div which hosts the txtCity TextBox and a btnSearch button and underneath that we got the GoogleMap control itself. The important to note on the map is the OnClientClick event. This is what we will use to read where the user clicked on the map by using Javascript and then submitting these values to codebehind. As you can see we also have 2 asp:HiddenField controls which I will use to read the clicked location. As you can see we have 2 Javascript functions in the page, 1 is purely cosmetical (setFocus) and I’m only using it to set the focus to a particular control whenever I need that (in this case setting the focus on txtCity control on onload event of the body) and the other is there to capture the map clicked event and store the location of the mouse click and submit the form afterwards.

Codebehind and Javascript explained

Now what happens with the code so far? When the page is loaded the focus is set on the txtCity control. You enter the name of the ctiy but the Go button does nothing. Let’s add the btnSearch_Click event. This is what it looks like:

protected void btnSearch_Click(object sender, EventArgs e)
// First clear old markers since this is a new search

if (txtCity.Text != “”)
mapControl.Address = txtCity.Text;
mapControl.Zoom = 15;

// add a new search marker
GoogleMarker marker = new GoogleMarker(mapControl.Address);
marker.Title = mapControl.Address;
marker.Clickable = false;

As you can see the moment you click the Go button first we clear the map of all the currently present markers and then check if the text inside the txtCity control isn’t empty. We assign the Address property of the mapControl GoogleMap control and we also set the zoom level of the control. Further down we instantiate a new GoogleMarker (requires you to reference Artem.Web.UI.Controls on the page), set it’s location to the current address of the mapControl, we set it’s title and Clickable status (I’ve set mine to false because I don’t want to display anything when you click the marker). At last we call the mapControl.Markers.Add(marker) method which adds this marker to the control’s marker collection and therefore displays it on the map as well.The other overload for marker instantiation allows you to pass the lat and long values instead of address to position the marker which we will see in the next example. Ok we got the search part working. Let’s move on to the map clicking part which is handled by Javascript.

If you take a look at the GoogleMap control in our Page markup code you will see that we’ve set the OnClientClick property to a getLatLongValuesJavascript function:

<cc1:GoogleMap ID=”mapControl” runat=”server” OnClientClick=”getLatLongValues” Width=”100%” Height=”740px” Zoom=”3″ Latitude=”10″ Longitude=”10″ Key=”PUT YOUR MAPS API KEY HERE”>

Now let’s see what this function does:

function getLatLongValues(overlay, point) {
if (point) {
document.getElementById(“latValue”).value =;
document.getElementById(“lngValue”).value = point.lng();

As you can see the function takes in 2 parameters, the overlay parameter and the point parameter. The point parameter is the one we’re interested in. It hold the lat and long values in it. So we first check if point is different than undefined and if it is we take the values of both and point.lng() and store them in the 2 asp hidden fields on the bottom of the page. Afterwards we submit the form which causes Postback to occur. Now let’s switch to the codebehind to see what goes on there:

protected void Page_Load(object sender, EventArgs e)
if (IsPostBack)

As you can see on Page_Load I’m checking if the Page is posted back and if it is I’m calling the CheckForClickLocation() method in my page. Let’s see how that looks like:

private void CheckForClickLocation()
// clear the marker

// add new marker only if both hidden fields have a value
if (latValue.Value != “” && lngValue.Value != “”)
GoogleMarker marker = new GoogleMarker(Convert.ToDouble(latValue.Value), Convert.ToDouble(lngValue.Value));
marker.Clickable = false;

mapControl.Latitude = marker.Latitude;
mapControl.Longitude = marker.Longitude;
mapControl.Zoom = 13;

As you can see here we’re first clearling the current markers on the map and then we’re checking if latValue and lngValue hidden fields have any value in them (remember postback can occur by a button we have on the page as well in which case there was no actual map click). In case we have values in these 2 hidden fields we instantiate a new GoogleMarker object passing the values of the latValue and lngValue hidden fields converted into a double which is what the marker requires. We disable the clickable property because we don’t need it and add the marker to the mapControl’s Markers collection. After this is done we change the current Latitude and Longitude of the mapControl to the newly clicked location (note that I’m using marker.Latitude and marker.Longitude which also saves me from converting the values to double again), we set the zoom level to 13 and now the mapControl is centered on the newly clicked location where the marker is displayed as well.

Now if some of you wonder what happens if a postback by a button occurs and there are values in hidden fields as well? Well in case you’re familiar with Page lifecycle you will know that this won’t present any problem because what happens is that when a button is clicked and a postback occurs the Page_Load event fires before (this is important) the button click event and even though the markers were added in a Page_Load event they were deleted afterwards by the button click event.

Source Code and Conclusion

As you have seen in this article, using GoogleMap control in your ASP.NET website or application isn’t hard at all. I hope you enjoyed reading this guide and if you got any comments or questions feel free to ask them and I will try to answer you as best as I can. Download the source code used in this guide below:

Source taken from: