Friday, February 25, 2011

Quote of The Day - 2011-02-25

I think that it's extraordinarily important that we in computer science keep fun in computing. When it started out, it was an awful lot of fun. Of course, the paying customers got shafted every now and then, and after a while we began to take their complaints seriously. We began to feel as if we really were responsible for the successful, error-free perfect use of these machines. I don't think we are. I think we're responsible for stretching them, setting them off in new directions, and keeping fun in the house. I hope the field of computer science never loses its sense of fun. Above all, I hope we don't become missionaries. Don't feel as if you're Bible salesmen. The world has too many of those already. What you know about computing other people will learn. Don't feel as if the key to successful computing is only in your hands. What's in your hands, I think and hope, is intelligence: the ability to see the machine as more than when you were first led up to it, that you can make it more.

- Alan J. Perlis (April 1, 1922-February 7, 1990)

Thursday, February 24, 2011

Quote of The Day - 2011-02-24

Imagination is more important than knowledge. - Albert Einstein

Monday, February 21, 2011

GeoCoding with C# and Google Geocoding API V3

Geocoding is the process of finding associated geographic coordinates (often expressed as latitude and longitude) from other geographic data, such as street addresses, or zip codes (postal codes). (read more in wikipedia)

Today I'll give a short example of C# application in which we will use the newest version of Google Geocoding API V3. You can compare it with similar C++ geocoding example.

When you perform a geocoder request, you can specify which output type to use. The available options are JSON, XML, KML and CSV. We will be requesting and handling XML data.

If you are searching for example with JSON output format I have written one here.

For example, if you wanted to find the coordinates of house located at 1600 Amphitheatre Parkway, Mountain View, CA, you would request the following URL: (http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false).

The response will be processed with XPath and coordinates will be printed to console.

The full working example is in the following code:

using System;
using System.Net;
using System.Xml.XPath;

namespace GeoCoderApiV3App1
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false";
            
            WebResponse response = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                response = request.GetResponse();
                if (response != null)
                {
                    XPathDocument document = new XPathDocument(response.GetResponseStream());
                    XPathNavigator navigator = document.CreateNavigator();
                    
                    // get response status
                    XPathNodeIterator statusIterator = navigator.Select("/GeocodeResponse/status");
                    while (statusIterator.MoveNext())
                    {
                        if (statusIterator.Current.Value != "OK")
                        {
                            Console.WriteLine("Error: response status = '" + statusIterator.Current.Value + "'");
                            return;
                        }
                    }
                    
                    // get results
                    XPathNodeIterator resultIterator = navigator.Select("/GeocodeResponse/result");
                    while (resultIterator.MoveNext())
                    {
                        Console.WriteLine("Result: ");
                        
                        XPathNodeIterator formattedAddressIterator = resultIterator.Current.Select("formatted_address");
                        while (formattedAddressIterator.MoveNext())
                        {
                            Console.WriteLine(" formatted_address: " + formattedAddressIterator.Current.Value);
                        }
                        
                        XPathNodeIterator geometryIterator = resultIterator.Current.Select("geometry");
                        while (geometryIterator.MoveNext())
                        {
                            Console.WriteLine(" geometry: ");
                            
                            XPathNodeIterator locationIterator = geometryIterator.Current.Select("location");
                            while (locationIterator.MoveNext())
                            {
                                Console.WriteLine("     location: ");
                                
                                XPathNodeIterator latIterator = locationIterator.Current.Select("lat");
                                while (latIterator.MoveNext())
                                {
                                    Console.WriteLine("         lat: " + latIterator.Current.Value);
                                }
                                
                                XPathNodeIterator lngIterator = locationIterator.Current.Select("lng");
                                while (lngIterator.MoveNext())
                                {
                                    Console.WriteLine("         lng: " + lngIterator.Current.Value);
                                }
                            }
                            
                            XPathNodeIterator locationTypeIterator = geometryIterator.Current.Select("location_type");
                            while (locationTypeIterator.MoveNext())
                            {
                                Console.WriteLine("         location_type: " + locationTypeIterator.Current.Value);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                Console.WriteLine("Clean up");
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
            }
            
            Console.WriteLine("Done.");
            Console.ReadLine();
        }
    }
}

Saturday, February 19, 2011

W3C: HTML5 Spec Due in 2014 - link

Read here...

Quote of The Day - 2011-02-19

Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

Martin Fowler

Urban Sql injection - (link)

here

Monday, February 14, 2011

How Generate Database from NHibernate mapping files

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    ...
    <session-factory>
        ...
        <property name="hbm2ddl.auto">create</property>
    </session-factory>
    ...
</hibernate-configuration>

If you define <property name="hbm2ddl.auto">create</property> in session-factory section of NHibernate configuration database schema would be generated for you by NHibernate. But you still have to create empty database before that.

Thursday, February 10, 2011

Funny discussion on downsides of using Dependency Injection – (StackOverflow link)

It seams that DI pattern introduction can be dangerous for your career because ....

Wednesday, February 9, 2011

NHibernate Criteria using substring SqlFunction projection with in clause

I was playing with new NHibernate release (3.0.0 GA) and all of a sudden I felt an urge to check if one of bugs I have stumbled upon in 2.2 version is fixed. A quick example and few moments after - O happy day!!! This bug is fixed in 3.0.0 GA version.

Thank you awesome NHibernate developers.

P.S. Source code
using System;
using System.Collections.Generic;
using System.Reflection;

using NHibernate;
using NHibernate.Cfg;
using NH3Tests.SimpleModel;
using NHibernate.Criterion;

namespace NH3Tests
{
    public class Program
    {
        static ISessionFactory factory;

        public static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();

            IList<Room> rooms = null;
            using (ISession session = OpenSession())
            {
                ICriteria query = session.CreateCriteria<Room>l;()
                    .Add(Expression.In(
                        Projections.SqlFunction("substring",
                            NHibernateUtil.String,
                            Projections.Property("Code"),
                            Projections.Constant(1),
                            Projections.Constant(2)),
                        new string[] { "A1", "A2" }));

                rooms = query.List<Room>();
            }

            Console.WriteLine("Done.");
        }

        public static ISession OpenSession()
        {
            if (factory == null)
            {
                Configuration c = new Configuration();
                c.AddAssembly(Assembly.GetCallingAssembly());
                factory = c.BuildSessionFactory();
            }
            return factory.OpenSession();
        }
    }
}

POCO and mapping file:

using System;
using System.Collections.Generic;

namespace NH3Tests.SimpleModel
{
    public class Room
    {
        private int _id = 0;
        private string _code = null;
        private string _description = null;

        public Room()
        { 
        }

        public int Id
        {
            get { return _id; }
            set { _id = value; }
        }

        public string Code
        {
            get { return _code; }
            set { _code = value; }
        }

        public string Description
        {
            get { return _description; }
            set { _description = value; }
        }
    }
}
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true">
  <class name="NH3Tests.SimpleModel.Room, NH3Tests" table="room" lazy="false">
    <id name="Id" access="field.camelcase-underscore"  column="room_id">
      <generator class="native" />
    </id>
    <property name="Code" access="field.camelcase-underscore"  column="code"/>
    <property name="Description" access="field.camelcase-underscore" column="description"/>
  </class>
</hibernate-mapping>

And config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="hibernate-configuration"
    type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
    <section name="log4net"
    type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
  </configSections>
  <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
      <property name="connection.provider">
        NHibernate.Connection.DriverConnectionProvider
      </property>
      <property name="connection.driver_class">
        NHibernate.Driver.SqlClientDriver
      </property>
      <property name="connection.connection_string">
        Server=(local);database=NH3Tests;Integrated Security=SSPI;
      </property>
      <property name="dialect">
         NHibernate.Dialect.MsSql2008Dialect
      </property>
      <property name="show_sql">true</property>
      <property name='proxyfactory.factory_class'>NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
    </session-factory>
  </hibernate-configuration>
   <log4net>
    <appender name="ConsoleAppender"
    type="log4net.Appender.ConsoleAppender, log4net">
      <layout type="log4net.Layout.PatternLayout, log4net">
        <param name="ConversionPattern" value="%m\n" />
      </layout>
    </appender>
    <root>
      <priority value="INFO" />
      <appender-ref ref="ConsoleAppender" />
    </root>
  </log4net>
</configuration>

And room table:
CREATE TABLE [dbo].[room](
 [room_id] [int] IDENTITY(1,1) NOT NULL,
 [code] [nvarchar](16) NOT NULL,
 [description] [nvarchar](256) NULL,
 CONSTRAINT [PK_room] PRIMARY KEY CLUSTERED 
(
 [room_id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

Tuesday, February 8, 2011

Exploration of JAVA 2.2250738585072012e-308 bug (link)

This is update of this post.

The guy how found this bug takes a closer look on this meter.

Monday, February 7, 2011

SCOPE_IDENTITY() returns incorrect value - Microsoft SQL Server 2005/2008/2008 R2 (x86, x64)

As you probably know SCOPE_IDENTITY() is broken.
Effects versions: Microsoft SQL Server 2005/2008/2008 R2 (x86, x64). Bug is still not fixed thought it was submitted tow years ago (on 2/15/2008 4:2, 0:09 PM). Here is workaround.

Thursday, February 3, 2011

Worlds worst hacker - link and video

Read here...

Surprise with SQL Server Management Studio and default Login database

I have taken offline one of my databases on my development SQL Server. However it turns out that my login was set to use that database as its default. Now when ever I try to do anything in object explorer it tries to connect using my default database and fails. It is completely stupid. I think program should let user chose new value if default one is not valid anymore.

The only working solution I have found is the following:
1. connect to SQL Server Management Studio by using the 'options' button in the connection dialog and selecting 'master' as the database to connect to.
2. execute the following query to change default database of login
exec sp_defaultdb @loginame='login', @defdb='master'

Wednesday, February 2, 2011

100 years of IBM (link)



Title says it all.

Java Hangs When Converting 2.2250738585072012e-308 - link

Some guy discovered that JAVA JRE/JDK hangs when converting 2.2250738585072012e-308 number.

class runhang {
public static void main(String[] args) {
  System.out.println("Test:");
  double d = Double.parseDouble("2.2250738585072012e-308");
  System.out.println("Value: " + d);
 }
}

class compilehang {
public static void main(String[] args) {
  double d = 2.2250738585072012e-308;
  System.out.println("Value: " + d);
 }
}

PHP interpreter has the same bug.

<?php $d = 2.2250738585072011e-308; ?>

I have test and it seems that this number has no effect on .NET framework tried (NET frameworks 2.0-4.0).

namespace FloatingDecimal
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Test:");
            double d1;
            Double.TryParse("2.2250738585072012e-308", out d1);
            double d = 2.2250738585072012e-308;
            Console.WriteLine("Value: " + d + " other: " + d1);
        }
    }
}

Python interpreter is not effected too (tried version 3.1.1).

>>> d = 2.2250738585072012e-308
>>> d
2.2250738585072014e-308
>>> d = float("2.2250738585072012e-308")
>>> d
2.2250738585072014e-308

UPDATE:

Jython is effected...