Google Spell Checker Api Asp.Net C#


In this article you will learn how to use the Google Spell Checker API in Asp.Net C# apps

Download the complete source code from here

The API is very simple,  spell checking is done through a XML http post to the following url

https://www.google.com/tbproxy/spell?lang=en:

Request XML structure

<?xml version=”1.0encoding=”utf-8?>
<spellrequest textalreadyclipped=”0ignoredups=”0ignoredigits=”1ignoreallcaps=”1>
<text>Hotal</text>
</spellrequest
>

The folloing are the Response XML from Google API

<?xml version=”1.0encoding=”UTF-8?>
<spellresult error=”0clipped=”0charschecked=”12>
<c o=”0l=”5s=”0″>
Hotel Hotly Total Ital Hots</c>
<
/spellresult
>

Tag Description
o The offset from the start of the text of the word
l Length of misspelled word
s Confidence of the suggestion
text Tab delimited list of suggestions

See the complete code here

using System;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

public static class SpellChecker
{
 public static String DidYouMean(string word)
 {
 string retValue = string.Empty;
 try
 {
 string uri = "https://www.google.com/tbproxy/spell?lang=en:";
 using (WebClient webclient = new WebClient())
 {
 string postData = string.Format("<?xml version=\"1.0\" encoding=\"utf-8\" ?><spellrequest textalreadyclipped=\"0\" ignoredups=\"0\" ignoredigits=\"1\" "
 + "ignoreallcaps=\"1\"><text>{0}</text></spellrequest>",word);

 webclient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
 byte[] bytes = Encoding.ASCII.GetBytes(postData);
 byte[] response = webclient.UploadData(uri, "POST", bytes);
 string data = Encoding.ASCII.GetString(response);
 if (data != string.Empty)
 {
    retValue = Regex.Replace(data, @"<(.|\n)*?>", string.Empty).Split('\t')[0];
 }
 }
 }
 catch (Exception exp)
 {

 }
 return retValue;
 }
 }

protected void Page_Load(object sender, EventArgs e)
{
    string word = SpellChecker.DidYouMean("Hotal");
    if(word != string.Empty)
    {
         labMessage.Text = "<font style='font-size:12px;color:red;'>Did you mean </font><b>" + retValue + "</b>";
    }
}

You can Download the complete source code from here

Hope this help and If you have any comments, please feel free to write your feedback.

Thanks
Deepu

Advertisements

Multiple file uploading in Silverlight


In this article I am going to explain how we can upload multiple files in Silverlight 3.0 using OpenFileDialog class

Click here to download the article

Open VS 2008 and create a new Xaml file called MultiFileUploader.xaml. Copy paste the below markup.

<Canvas Width=”640″>

<TextBlock Canvas.Left=”300″ HorizontalAlignment=”Center” Canvas.Top=”150″ x:Name=”txtProgress”  Foreground=”Green” Width=”120″/>

<Button Canvas.Left=”300″ HorizontalAlignment=”Center” Canvas.Top=”180″ Click=”FileUpload_Click” Width=”100″ Height=”25″ Content=”Select Files”/>

</Canvas>

In above Xaml I have placed two controls ie Button and Textbox.  Button control for selecting files and Texbox control,
shows the total file count which is uploaded in the server.

Code behind for MultiFileUploader.xaml.cs

int totalFilesToUpload = 0;
int totalFilesUploaded = 0;

private void FileUpload_Click(object sender, RoutedEventArgs e)
 {
 this.txtProgress.Text = string.Empty;

 OpenFileDialog oFileDialog = new OpenFileDialog();
 oFileDialog.Filter = "All Image Files ( JPEG,GIF,BMP,PNG)|*.jpg;*.jpeg;*.gif;*.bmp;*.png|JPEG Files ( *.jpg;*.jpeg )|*.jpg;*.jpeg|GIF Files ( *.gif )|*.gif|BMP Files ( *.bmp )|*.bmp|PNG Files ( *.png )|*.png";
 oFileDialog.FilterIndex = 1;
 oFileDialog.Multiselect = true;

 string data = string.Empty;

 if (oFileDialog.ShowDialog() == true)
 {
 foreach (var file in oFileDialog.Files)
 {
 using (System.IO.Stream fileStream = GetFileData(file.OpenRead()))
 {
 StreamResourceInfo oStreamResource = new StreamResourceInfo(fileStream, null);

 byte[] array = new byte[oStreamResource.Stream.Length];

 oStreamResource.Stream.Read(array, 0, (int)oStreamResource.Stream.Length);

 data = Convert.ToBase64String(array);

 WebClient oWebClient = new WebClient();

 string fileName = Guid.NewGuid().ToString().Replace("-", "") + file.Extension;

 oWebClient.UploadStringAsync(new Uri("http://localhost:50848/FileUpload.ashx?file=" + fileName), null, data, fileName);

 oWebClient.UploadProgressChanged += new UploadProgressChangedEventHandler(oWebClient_UploadtxtProgressChanged);

 totalFilesToUpload += 1;

 data = string.Empty;
 }
 }
 }

 }

 System.IO.MemoryStream GetFileData(System.IO.Stream oFileStream)
 {
 oFileStream.Seek(0, System.IO.SeekOrigin.Begin);
 byte[] data = new byte[oFileStream.Length];
 oFileStream.Read(data, 0, (int)oFileStream.Length);
 return new System.IO.MemoryStream(data);
 }

 void oWebClient_UploadtxtProgressChanged(object sender, UploadProgressChangedEventArgs e)
 {
 totalFilesUploaded += 1;

 txtProgress.Text = !string.IsNullOrEmpty(txtProgress.Text) ? (int.Parse(txtProgress.Text) + e.BytesSent).ToString() : e.BytesSent.ToString();

 if (totalFilesUploaded == totalFilesToUpload)
 {
 txtProgress.Text = totalFilesUploaded + " files uploaded successfully (" +  txtProgress.Text + " bytes sent )";
 }
 }

The next step I am going to create a receiver application which can convert the stream object to image file and save to server. I am creating a GenericHandler  file to achieve this task (You can do it in Aspx page also).

using System;
using System.Web;
using System.IO;

namespace SilverlightApplicationDemo.Web
{
    public class FileUpload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            var fileName = context.Request["file"];
            string data;
            using (StreamReader sr = new StreamReader(context.Request.InputStream))
            {
                data = sr.ReadToEnd();
                byte[] array = Convert.FromBase64String(data);
                using (FileStream fs = new FileStream(context.Server.MapPath("~/images/") + fileName, FileMode.Create))
                {
                    fs.Write(array, 0, array.Length);
                }
            }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

Note :  I have hard-coded the FileUpload url as (http://localhost:50848/FileUpload.ashx). Don’t forget to replace with your file  upload URL.

Hope this help and If you have any comments, please feel free to write your feedback.

You can download the entire article from here

Thanks
Deepu

Yahoo Geocoding API Service in Asp.Net 3.5 C# using WebClient class (Asynchronously)


In this article I am going to explain how to consume yahoo Geocoding API service in Asp.Net C# using web client Asynchronous method.
If you are working with maps you may require latitude and longitude to show the address in map. Yahoo!s APIs is the awesome tool provides APIs for many of the services Maps, Music, Search, Search Marketing, Shopping, Travel etc…

Click here to download the entire article

Assume you have a list of locations in your database and need to pull Geo-coder (latitude and longitude) from yahoo API service  in Asynchronous manner.. (per day you can query 5000 request from a single ip address). Geocoding service is a free service you have to register in order to use it. http://developer.yahoo.com/maps/rest/V1/geocode.html

So lets create a simple class called Location with two properties LocationId,Address.

public class Location
{
public int LocationId { get; set; }
public string Address { get; set; }

public static List<Location> GetLocationList()
{
List<Location> oAddressList = new List<Location>
{
new Location{ LocationId = 1, Address = "1001 Emerald Heights Ct, Reston VA 20191"},
new Location{ LocationId = 2, Address = "1001 University Ave, West Des Moines, IA 50266"},
new Location{ LocationId = 3, Address = "701 First Ave Sunnyvale,CA"},
};
return oAddressList;
}
}

I have hard coded three different addresses you can change this with your database logic.  The next step is to create a new aspx page and make sure if you are using asynchronous call you have to add Async=”true” in the page header of the Aspx page.

Task List in the aspx page.

1) Add Async=”true”  in the page header.
2)
Get the locations list from the business object / database.
3) Initializing yahoo application id (http://developer.yahoo.com/maps/rest/V1/geocode.html).
4) Construct url for geocode service (make sure you are sending address in encode format using Server.UrlEncode method).
4) Consume Geo-code service using web client class with Asynchronous manner.
5) Send Address information along with a custom token, AddressId (so that I can update geocode information to database for the particular address).
5) Download result xml from yahoo api service.
6) Parse the xml content and get Latitude and longitude

In the Page_Load Method

protected void Page_Load(object sender, EventArgs e)
 {
string YAHOO_API_SIGNATURE = "YD-9G7bey8_JXxQP6rxl.fBFGgCdNjoDMACQA--";

 string YAHOO_API_URL = "http://local.yahooapis.com/MapsService/V1/geocode?appid=" + YAHOO_API_SIGNATURE + "&street=";

 string url = string.Empty;

 var oGeoCoderList = Location.GetLocationList();

 foreach (Location location in oGeoCoderList)
 {
 WebClient oWebClient = new WebClient();

 oWebClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(DownloadDataCompleted);

 url = string.Concat(YAHOO_API_URL, Server.UrlEncode(location.Address));

 oWebClient.DownloadDataAsync(new Uri(url), location.LocationId);
 }
}

Code Explanations

Initializing yahoo application id

string YAHOO_API_SIGNATURE = “YD-9G7bey8_JXxQP6rxl.fBFGgCdNjoDMACQA–“;

Initializing yahoo web service API URL.

string YAHOO_API_URL = “http://local.yahooapis.com/MapsService/V1/geocode?appid=&#8221; + YAHOO_API_SIGNATURE + “&street=”;

Get location list from business object or database.

var oGeoCoderList = Location.GetLocationList();

Create a webclient object

WebClient oWebClient = new WebClient();

Create event handler (DownloadDataCompleted) this event get fired when an asynchronous data download operation complete.

oWebClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(DownloadDataCompleted);

Append location address with yahoo api url.

url = string.Concat(YAHOO_API_URL, Server.UrlEncode(location.Address));

DownloadDataAsync method downloads resources as System byte array.

oWebClient.DownloadDataAsync(new Uri(url), location.LocationId);

Loop through the location list and send address information to yahoo service along with a custom token, AddressId (so that I can update laster to database for the particular address).

 void DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
 {
 try
 {
 if (e.Error == null) //make sure there is no error.
 {
 byte[] byteContent = e.Result;

 string result = System.Text.Encoding.ASCII.GetString(byteContent);

 if (!string.IsNullOrEmpty(result))
 {
 int addressId = (int)e.UserState;

 var xml = XElement.Parse(result);

 xml = StripXMLNameSpace(xml);

 if (xml != null)
 {
 XElement xelement = (XElement)xml;
 string latitude = (from geoCodeService in xelement.Descendants("Result").Descendants("Latitude")
 select geoCodeService.Value).Take(1).SingleOrDefault<String>();

 string longtitue = (from geoCodeService in xelement.Descendants("Result").Descendants("Longitude")
 select geoCodeService.Value).Take(1).SingleOrDefault<String>();

 UpdateLocation(addressId, latitude, longtitue);
 }
 }
 }
 else
 {
 //log your error information here.
 }
 }
 catch (Exception exp)
 {
 //log system exception here
 }
 }

 void UpdateLocation(int addressId, string latitude, string longtitue)
 {
 //implement your update logic here....
 }

 XElement StripXMLNameSpace(XElement root)
 {
 return new XElement(
 root.Name.LocalName,
 root.HasElements ?
 root.Elements().Select(el => StripXMLNameSpace(el)) :
 (object)root.Value
 );
 }

Once we retrieve the information from yahoo service the above method will convert the result system byte array to string using System.Text.Encoding.ASCII.GetString method and also get the user defined object which we already passed to the method and remove the xmlns:name space  from the XML result and getting the values of latitude and longitude from the nodes. In my upcoming articles  I would like to explain how to integrate Google (MAPS & Street View) and Virtual Earth (with multiple address location)

Hope this help and If you have any comments, please feel free to write your feedback.

You can download the entire article from here or copy paste this URL

http://www.4shared.com/file/241083617/7919b1a7/YahooApiGeoCoder.html

Thanks
Deepu