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.

    http://www.google.com/apis/download.html

  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.

    https://www.google.com/accounts/NewAccount?
    continue=http://api.google.com/createkey&
    followup=http://api.google.com/createkey

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

    https://www.google.com/accounts/Login?continue=http%3A%2F%2Fapi.google.com%2Fcreatekey&followup=http%3A%2F%2Fapi.google.com%2Fcreatekey

  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

      http://api.google.com/GoogleSearch.wsdl

      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.

      com.google.api.GoogleSearchService s = new TestGoogle.com.google.api.GoogleSearchService();
      com.google.api.GoogleSearchResult 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;
      dtResults.Rows.Add(dr);
      }
      dataGridView1.DataSource = dtResults;

This is the running application

Source is taken from: http://www.c-sharpcorner.com/UploadFile/mem_1910/1st08162006033511AM/1st.aspx

Advertisements

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.

Overview:

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:

http://chart.apis.google.com/chart?chs=250×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:

http://chart.apis.google.com/chart?cht=<chart_type>&chd=<chart_data>&chs=<chart_size>&...additional_parameters...

All URLs start with http://chart.apis.google.com/chart? 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

http://chart.apis.google.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World

http://chart.apis.google.com/chart?
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.)
cht=p3
The chart type: here, a 3D pie chart.
chs=250x100
The chart size (widthheight), in pixels. See the maximum values here.
chd=t:60,40
The chart data. This data is in simple text format, but there are other formats.
chl=Hello|World
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.

Reference:

1:- http://code.google.com/apis/chart/docs/making_charts.html

For using google chart wizard:

2:-http://code.google.com/apis/chart/docs/chart_wizard.html

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

Recently I got a chance to work on Google Analytics API integration with Asp.net 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 = “https://www.google.com/analytics/feeds/data&#8221;;
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(”
“);
Response.Write(“Total Visits : ” + ss);
Response.Write(”
“);
}

Output

1.gif

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.

Reference:http://www.c-sharpcorner.com/uploadfile/ravi_panara/498/default.aspx?login=true&user=sharadmishr@gmail.com

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

Introduction

This article will show you how to implement the open source Google Map control for .NET hosted at http://googlemap.codeplex.com/
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 http://googlemap.codeplex.com/ 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:

http://code.google.com/apis/maps/signup.html

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” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml”&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 = point.lat();
document.getElementById(“lngValue”).value = point.lng();
document.forms[0].submit();
}
}

function setFocus(controlName) {
document.getElementById(controlName).focus();
}
</script>
</head>
<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” />
</div>
<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”>
</cc1:GoogleMap>
</div>

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

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
mapControl.Markers.Clear();

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;
mapControl.Markers.Add(marker);
}
}

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”>
</cc1:GoogleMap>

Now let’s see what this function does:

function getLatLongValues(overlay, point) {
if (point) {
document.getElementById(“latValue”).value = point.lat();
document.getElementById(“lngValue”).value = point.lng();
document.forms[0].submit();
}
}

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 point.lat() 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)
{
CheckForClickLocation();
}
}

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
mapControl.Markers.Clear();

// 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.Markers.Add(marker);

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:

http://eggheadcafe.com/FileUpload/-1672755420_GoogleMapTutorial.zip

Source taken from: http://www.eggheadcafe.com/tutorials/aspnet/c265b2b7-45a0-49c5-a6b9-589d015e60d9/working-with-googlemap-control-in-aspnet.aspx