Steve Trefethen
Contact me
About Me View my LinkedIn profile

Powered by discountASP.NET
referal ID: sdtref
Why recommend discountASP.NET?
Need consulting?
Need Consulting?

Spread Thunderbird

Disclaimer

The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

TestComplete Keyword Testing Online Training

I will be presenting a three day webinar April 12-14th 2010 from 9am-1pm PST on AutomatedQA's TestComplete. The cost is $499/person and you can register on Falafel Software's website here. For detailed information on this training click here.

Using Google Maps for Geocoding in C# Part 2: Deserializing to a class

December 02 2008 3:32PM

In my previous post, I illustrated how to geocode a city state combination using Google’s Map API and a comment was asked why not deserialize to a class. Well, I could have done that but in the app I’m playing around with that wasn’t really necessary although there is more useful data than just the coordinates so here’s part two.

Once you have the XML data you can construct a C# class that would allow for deserializing to an object. Generating the C# classes is straight forward and requires you to run XSD.EXE (installed with VS.NET) on the XML file to generate an .xsd file. Next, run XSD.EXE again on the .xsd with /classes to generate C# classes. Below is the output from the command line of XSD.EXE and you’ll notice I got an error the first time around (for the work around keep reading):

[c:\temp]"\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin"\xsd geo.xml
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 2.0.50727.42]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'C:\temp\geo.xsd'.

[c:\temp]"\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin"\xsd geo.xsd /cl
asses
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 2.0.50727.42]
Copyright (C) Microsoft Corporation. All rights reserved.
Schema validation warning: The 'urn:oasis:names:tc:ciq:xsdschema:xAL:2.0:Address
Details' element is not declared. Line 23, position 22.

Warning: Schema could not be validated. Class generation may fail or may produce
 incorrect results.

Error: Error generating classes for schema 'geo'.
  - The element 'urn:oasis:names:tc:ciq:xsdschema:xAL:2.0:AddressDetails' is mis
sing.

If you would like more help, please type "xsd /?".

To work around the above error I deleted the value of the xmlns attribute on the <AddressDetails> node then reran the above commands resulting in this C# file.

Finally, to deserialize the XML I used the following code which is a modified version of the function from my previous post (with minimal error checking I might add). Btw, here is a page that discusses .NET XML serialization:

private string GeoCode(string city, string state, string country, string zip)
{
    string url = "http://maps.google.com/maps/geo?output=xml&key=<your_API_key>&q=" + System.Web.HttpUtility.UrlEncode(city + " " + state);
    WebRequest req = HttpWebRequest.Create(url);
    WebResponse res = req.GetResponse();
    StreamReader sr = new StreamReader(res.GetResponseStream());
    try
    {
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(kml));
        using (System.IO.StringReader reader = new System.IO.StringReader(sr.ReadToEnd()))
        {
            kml item = (kml)serializer.Deserialize(reader);
            if(item.Items.Count() > 0 && item.Items[0].Placemark.Count() > 0 && item.Items[0].Placemark[0].Point.Count() > 0)
                return item.Items[0].Placemark[0].Point[0].coordinates;
            else 
              return "";
        }
    }
    finally
    {
        sr.Close();
    }
}
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags: , ,

Using Google Maps for Geocoding in C#

December 01 2008 9:05AM
Recently, I wanted to find out how to programmatically find the longitude and latitude given a city and state. From my previous work using Google Maps I knew this was possible. I did some digging and found Google Maps API supports a particular URL for geocoding a specific location. The URL looks like this:
http://maps.google.com/maps/geo?output=xml&key=<your_google_api_key>&q=<city_state>
Simply specify your Google API Key and your URL encoded city and state and you will get a result similar to the following (for "scotts valley ca"):
<?xml version="1.0" encoding="UTF-8" ?>
<kml xmlns="http://earth.google.com/kml/2.0"><Response>
  <name>scotts valley ca</name>
  <Status>
    <code>200</code>
    <request>geocode</request>
  </Status>
  <Placemark id="p1">
    <address>Scotts Valley, CA, USA</address>
    <AddressDetails Accuracy="4" xmlns="">
      <Country>
        <CountryNameCode>US</CountryNameCode>
        <CountryName>USA</CountryName>
        <AdministrativeArea>
          <AdministrativeAreaName>CA</AdministrativeAreaName>
          <Locality>
            <LocalityName>Scotts Valley</LocalityName>
          </Locality>
        </AdministrativeArea>
      </Country>
    </AddressDetails>
    <Point>
      <coordinates>-122.0120480,37.0555750,0</coordinates>
    </Point>
  </Placemark>
</Response>
</kml>
Hint: For illustration purposes this works without using an API Key although you should review Google’s Maps TOS.

Getting Geocode Information Programmatically

I wrote the following C# function (which lacks error checking) to fetch the above XML response from the Google Maps service. As you can see I’m using a simple regular expression to locate and return the actual coordinates.

private string GeoCode(string city, string state)
{
    string url = "http://maps.google.com/maps/geo?output=xml&key=<your_API_key>&q=" + System.Web.HttpUtility.UrlEncode(city + " " + state);
    WebRequest req = HttpWebRequest.Create(url);
    WebResponse res = req.GetResponse();
    StreamReader sr = new StreamReader(res.GetResponseStream());
    try
    {
        Match coord = Regex.Match(sr.ReadToEnd(), "<coordinates>.*</coordinates>");
        if(!coord.Success) return "";
        return coord.Value.Substring(13, coord.Length - 27);
    }
    finally
    {
        sr.Close();
    }
}

This turned out to be a lot less painful than I had originally thought it might be all thanks to Google’s Maps service. Have you done anything similar/easier/better?
[Update: Dec, 2 2008] Using Google Maps for Geocoding in C# Part 2: Deserializing to a class
[Update: Dec, 16 2008] Status codes returned by this service.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags: , ,

Screenshots on the iPod Touch and other enhancements in v2.0

July 15 2008 6:11AM
iPod Touch screen shot feature in v2.0
With the release of v2.0 firmware for the iPhone/iPod Touch Apple added a much needed feature which is the ability to take screenshots. If you hold the home button down and press and release the power button the screen will blank out for a split second giving the illusion of a photo being taken, a very nice touch. The screenshot is stored in your photos and easily accessible. When you reconnect to Windows you’ll first see this prompt:

Windows AutoPlay dialog for importing iPod Touch pictures

If you select the highlighted option you’ll see the following prompt:

Vista’s Importing Pictures and Video dialog

Which will allow you to quickly grab these screenshots for use in things like blog posts.  :-)

Keyboard Improvements

There are a number of other nice features in the v2.0 firmware like this minor but super useful change in keyboard layout (below left). Notice the spacebar is 1/3 size and the @ symbol and the period are provided for things like email addresses. The screenshot on the right illustrates the new password handling where the last character that you typed stays on screen for a second before switching to a dot which makes it easier to correctly enter passwords (notice the spacebar in this case is full size).

image   image

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

Setting Subsonic's connectionstring at runtime

July 02 2008 6:51PM

I’m a fan of the Open Source project SubSonic, spearheaded by Rob Conery of Microsoft, which describes itself thusly:

A Super High-fidelity Batman Utility Belt. SubSonic works up your DAL for you, throws in some much-needed utility functions, and generally speeds along your dev cycle.

I’ve seen a few questions on the Internet about setting the SubSonic connectionstring at runtime and thought I’d post what I’ve done. SubSonic includes a tool to generate a DAL for you which picks up settings from your .config file which provides the connectionstring among other things. I’m using SubSonic in a plugin to CruiseControl.NET for EDI processing and here the portion of my ccservice.exe.config file related to SubSonic:

<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <section name="SubSonicService" type="SubSonic.SubSonicSection, SubSonic" requirePermission="false"/> </configSections> <connectionStrings> <add name="Velocity2" connectionString="Data Source=db;Initial Catalog=db;Persist Security Info=True;" providerName="System.Data.SqlClient" /> </connectionStrings> <SubSonicService defaultProvider="Velocity"> <providers> <clear/> <add name="Velocity" type="Subsonic.SqlDataProvider, SubSonic" connectionStringName="Velocity2" generatedNamespace="VelocitySubSonic" includeTableList="AR_*,CORE_*,EDI_*,II_*,IN_*,SA_*" excludeProcedureList="WMS_InsertImportQueue" /> </providers> </SubSonicService> ...

One of the things I wanted to do is override the connectionstring using a property on my CCNET plugin. To do that I implemented a property like this:

[ReflectorProperty("connectionString")] public string ConnectionString { get { return m_connectionstring; } set { m_connectionstring = value; SubSonic.DataService.GetInstance("Velocity").SetDefaultConnectionString(value); } }
The instance name comes from the name used in the config file above then simply call SetDefaultConnectionString and voila the SubSonic connectionstring is now set at runtime.
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags: ,

Switching back to My Yahoo classic

June 29 2008 11:42PM

On Thursday, Yahoo rolled out changes to my.yahoo.com updating the layout of the page with a beta version. One of the items that seemingly got lost was the link to switch back to the classic layout. I’ve played with the new layout and still prefer the old classic style that I’ve used for years now. Fortunately, at least for the time being, you can still switch back to the classic layout using this URL.

Btw, send feedback to Yahoo about the New Yahoo Mail.

[Update: July 9th 2008] Well that was short lived, below is a message from my current Yahoo page. Thanks a lot Yahoo.
image
[Update: July 9th 2008 8:30am] I posted a comment last night to this Yahoo blog post asking James, a My Yahoo! Product Lead, why he provided a link to switch back to classic knowing it would last only a week and the comment was deleted. I had included a link to the post I wrote about why Yahoo has frustrated me and indicating that this decision to kill Yahoo Classic was simply yet another reason. I guess that was just too over-the-top.
[Update: July, 14th 2008] Now that we’ve all be forced over to the new page I’m now getting hundreds of search engine hits on this post. Looks like I’m not the only one who like the "Classic" style.
[Update: July 15th 2008] According to one commenter Yahoo is now deleting requests to support the Classic mode from their web site properties though this page is still alive at least for now. I’m now getting 100’s Internet search hits for this post so this is a pretty popular subject. Feel free to digg this post and see if we can shine a little more attention on this.
[Update: January 25th 2009] How I replaced Yahoo.

[Update: August 11th 2009] I get enough email about this that I decided to record a video that illustrates the technique people posted here on how to switch back. Sadly, I no longer use Yahoo other than to forward an old email address I still keep alive but that's it.
[Update: November 7th 2009] Removed the video as it didn't slow the rate of email I get about people's Yahoo's problems.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

SQL Server Index Nightmare

June 18 2008 6:21AM

The other day I discovered one of the MSSQL tables I’m using heavily at the moment had 214 indices! There were about 20 with sensible names and the rest were all named similar to _dta_index_SA_OrderHeader_5_499519046__K1_2_6_9_13. I mentioned this issue to John Waters in the office today which elicited a nice laugh until I sent him this screenshot:

SQL Manager 2008 Lite

While I’m not exactly new to MSSQL I’m no expert though fortunately Falafel has a few experts on staff and John’s one of them. He dug into the problem answering the what, where and how to deal them, feel free to click through if that’s what you need.

Had I not blogged back in February asking about MSSQL tools this problem would likely have gone undetected for a lot longer. Microsoft’s Management Studio doesn’t show these so called Hypothetical Indices so you have no way of knowing your table/DB is being impacted by them. Ironically, they’re created by the Index Tuning Wizard. Anyway, one commenter to my post mentioned EMS Database Management Solutions (a mouthful notwithstanding whatever EMS stands for) SQL Manager 2008 for which there is a freeware download. SQL Manager’s treeview provides a wealth of information including counts for things like indices which allowed me to easily stumble upon the problem.

All in all, there were 500+ of these indices hanging around but thanks to SQL Manager no longer!

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags: ,

System.Runtime.InteropServices.COMException loading a project into VS.NET 2008

June 12 2008 6:14PM

Recently, based on comments to this post I decided to turn Vistas UAC back on in "silent mode" using TweakUAC. Doing so allows me to run Windows Live Mesh to support folder synchronization which I’m now using to backup my blog content. The downside is that after making this change I started getting System.Runtime.InteropServices.COMException errors when loading a large application into VS.NET 2008.

System.Runtime.InteropServices.COMException
After a bit of head scratching I thought to change my VS.NET shortcut to launch with "Run as Administrator" enabled which resolved the error. Now, back to work!

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags: