June 2011 - Posts
My Sela Dev-Days Experience
Today I finished my Sela Dev. Days experience. Sela Dev. Days is a conference which include 5 days, 15 top experts, 25 session, and a whole lot of attendees (around 600 people registered for this week). If you are not familiar with Sela Dev. Days you can go to the conference’s site. In the conference I had three tutorial days in three different subjects:
- ASP.NET MVC 3, EF Code First integration, and Razor: Oh My!
In this one day tutorial I co-operated with Sebastian Pederiva, a senior consultant in Sela. In the day we gave a crash dived into Microsoft Web Platform – including ASP.NET MVC 3, EF, Web Platform Installer, Razor view engine and more. At the beginning session I introduced Microsoft web platform and ASP.NET MVC. Then, I talked about building models and data access layers for MVC applications on top of Entity Framework and in particular with Code First. In the third session I talked about how to work with controllers and about the routing concept in ASP.NET. Sebastian talked about Razor and how to integrate AJAX into MVC applications using the jQuery library. - HTML 5
In this one day tutorial I talked about what to expect out of the coming HTML5 standards, the new HTML5 elements, how to migrate HTML4 applications to HTML5 (here I gave a case scenario and with the help of the attendees we migrated a blog web page to HTML5) and about some of the new HTML5 API such as Geolocation, Web Workers, Web Sockets, Canvas and more. - Entity Framework 4.1 and Code First
In this one day tutorial I co-operated with Ido Flatow, another senior architect in Sela. I delivered four sessions – introduction to ORMs and EF, querying and manipulating data using Entity Framework, Entity Framework internals and Code First. Ido gave a session about Entity Framework in distributed applications.
I want to thank all the attendees that joined me in the days I delivered.
All the demos can be downloaded from here.
Father for the Third Time
I was asked why is my Blog so lonely lately. This is not because I have a writing block…
The answer is in the following pictures:


Three weeks ago Noya, my first daughter, was born and I’m busy with diapers instead of writing lines of code.
I will return writing soon so stay tuned!
Using Reverse Geocoding to Find an Address
I had a request from a colleague of mine to help him with a geocoding problem. The colleague needed to find an
address by a given latitude and longitude which were supplied by a smartphone consumer. The example in this post will show you how you can use Google geocoding API in order to achieve that using C#.
Reverse Geocoding (Address Lookup)
Geocoding refers to translating an address into its location or coordinates. The reverse of it is address lookup which occurs when you have the map location and you want to get an address out of it. In today’s mobile development it is very common to use the smartphone built-in GPS’ in order to make geocoding and reverse geocoding. When you want to make a geocoding request you can use Google’s geocode service in order to make location queries. When you want to make a geocode query you will have to send a Http request to http://maps.googleapis.com/maps/api/geocode/ with xml or Json format and a bunch of parameters in order to get your desired information. For further reading about making geocode requests go to Google Geocoding API documentation.
Reverse Geocoding Example
Here is a console application example of using reverse geocoding in order to find an address:
class Program
{
static string baseUri = "http://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}&sensor=false";
static void Main(string[] args)
{
RetrieveFormatedAddress("51.962146", "7.602304");
Console.ReadLine();
}
public static void RetrieveFormatedAddress(string lat, string lng)
{
string requestUri = string.Format(baseUri, lat, lng);
using (WebClient wc = new WebClient())
{
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
wc.DownloadStringAsync(new Uri(requestUri));
}
}
static void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var xmlElm = XElement.Parse(e.Result);
var status = (from elm in xmlElm.Descendants()
where elm.Name == "status"
select elm).FirstOrDefault();
if (status.Value.ToLower() == "ok")
{
var res = (from elm in xmlElm.Descendants()
where elm.Name == "formatted_address"
select elm).FirstOrDefault();
Console.WriteLine(res.Value);
}
else
{
Console.WriteLine("No Address Found");
}
}
}
As you can see I use a WebClient object to make a request to Google geocoding API with a given latitude and longitude parameters. The returned string is in Xml format (but might be in Json also) which might look like:
<GeocodeResponse>
<status>OK</status>
<result>
<type>street_address</type>
<formatted_address>1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA</formatted_address>
<address_component>
<long_name>1600</long_name>
<short_name>1600</short_name>
<type>street_number</type>
</address_component>
<address_component>
<long_name>Amphitheatre Pkwy</long_name>
<short_name>Amphitheatre Pkwy</short_name>
<type>route</type>
</address_component>
<address_component>
<long_name>Mountain View</long_name>
<short_name>Mountain View</short_name>
<type>locality</type>
<type>political</type>
</address_component>
<address_component>
<long_name>San Jose</long_name>
<short_name>San Jose</short_name>
<type>administrative_area_level_3</type>
<type>political</type>
</address_component>
<address_component>
<long_name>Santa Clara</long_name>
<short_name>Santa Clara</short_name>
<type>administrative_area_level_2</type>
<type>political</type>
</address_component>
<address_component>
<long_name>California</long_name>
<short_name>CA</short_name>
<type>administrative_area_level_1</type>
<type>political</type>
</address_component>
<address_component>
<long_name>United States</long_name>
<short_name>US</short_name>
<type>country</type>
<type>political</type>
</address_component>
<address_component>
<long_name>94043</long_name>
<short_name>94043</short_name>
<type>postal_code</type>
</address_component>
<geometry>
<location>
<lat>37.4217550</lat>
<lng>-122.0846330</lng>
</location>
<location_type>ROOFTOP</location_type>
<viewport>
<southwest>
<lat>37.4188514</lat>
<lng>-122.0874526</lng>
</southwest>
<northeast>
<lat>37.4251466</lat>
<lng>-122.0811574</lng>
</northeast>
</viewport>
</geometry>
</result>
</GeocodeResponse>
I use LINQ to XML in order to check the response status and if it’s OK I retrieve the formatted address value. Pay attention that I make an asynchronous request since I need to relay on a third party server (which is Google geocoding API in my example).
Summary
The post showed how to use a geocode API in order to make an address lookup according to a given location. I hope it will help you when you need to implement such a thing.
How to Configure a Self Referencing Entity in Code First
A few days ago a worker in Sela asked me how to configure a self
referencing entity with EF Code First. In this post I’ll show you how to implement that configuration.
Self Reference Scenarios
There are a lot of scenarios that we will want to implement a self reference between an entity to itself. For example, we do that when we want to create hierarchies in our application - an employee entity that has a self reference to his/her manager is a very common scenario for that. When we want to create that behavior in a database all we have to do is to add a foreign key in the table that point to the table primary key and we are done. But how can we do that in EF Code First?
Configure a Self Reference in Code First
In EF Code First we can use the fluent API in order to configure a self reference. Lets jump into an example that will direct you how to make that configuration.
The first thing is the entity:
public class Employee
{ #region Properties
public int EmployeeID { get; set; } public string FirstName { get; set; } public string LastName { get; set; }
public int? ManagerID { get; set; } public Employee Manager { get; set; }
#endregion
}
As you might notice there is nothing interesting in the entity itself – just a bunch of properties and the reference to the manager which is another employee.
After we have the entity lets create the context:
public class CompanyContext : DbContext
{ #region Properties
public DbSet<Employee> Employees { get; set; }
#endregion
#region Ctor
public CompanyContext()
: base("Company") { }
#endregion
#region Methods
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{ modelBuilder.Entity<Employee>().
HasOptional(e => e.Manager).
WithMany().
HasForeignKey(m => m.ManagerID);
}
#endregion
}
In the context you need to implement the OnModelCreating method in order to configure the self reference. We start the configuration with the HasOptional method that indicate that the employee might have a manager (or else he/she is the CEO). Then, for the manager we configure a many side with the WithMany method. In the end we use the HasForeignKey method to indicate what is the foreign key (which is the ManagerID in the example). That is it.
In order to finish the example I’ve created a database initializer that inserts some data:
public class ExampleInitializer : DropCreateDatabaseIfModelChanges<CompanyContext>
{ #region Methods
protected override void Seed(CompanyContext context)
{ var manager = new Employee
{ FirstName = "emp1",
LastName = "emp1",
};
var emp1 = new Employee
{ FirstName = "emp1",
LastName = "emp1",
Manager = manager
};
var emp2 = new Employee
{ FirstName = "emp2",
LastName = "emp2",
Manager = manager
};
context.Employees.Add(emp1);
context.Employees.Add(emp2);
context.SaveChanges();
}
#endregion
}
and a console application that run the example:
class Program
{ static void Main(string[] args)
{ Database.SetInitializer(new ExampleInitializer());
using (var context = new CompanyContext())
{ var query = context.Employees.Include(e => e.Manager).ToList();
foreach (var employee in query)
{ Console.WriteLine("{0} {1}", employee.EmployeeID, employee.ManagerID); }
}
}
}
Here is a figure of the output:
Summary
Lets sum up, the post includes a running example of how to configure a self reference entity with Code First. I hope it will help you if you get stuck with such a configuration.