Galin Iliev's blog

Software Architecture & Development

Calculate distance between locations using latitude and longitude

A couple months ago I had to calculate distance between locations using latitude and longitude... at that time I found a T-SQL sample that did the job but I forgot the site... I was impressed and I translated the code to C# and put in .NET Code library class and then, to make thigs complicated ( and usable in MS SQL 2005 Analisys Services- SSAS ) I've put in SSAS and call it from MDX query..

So far so good... but now I had some doubts about data accuracy and I searched the web again :). I havent; found same piece of code but I found better - and even article that describes the whole thing :)

In order not to forget again ( and to benefit you ) and I osting the code here. I recommend reading the article - Using SQL Server Yukon's .NET CLR Features Practically by Kent Tegels MCDBA, MCSE+I, MCP+SB


T-SQL user function:

CREATE FUNCTION dbo.udfComputeDistance
(
@lat1 float,
@lon1 float,
@lat2 float,
@lon2 float
)
RETURNS float
AS
begin
-- dLong represents the differences in longitudes
-- while dLat is the difference in latitudes
declare @dLong float
declare @dLat float
-- To keep the calculation easier to understand,
-- we have simplified it by computing it by parts.
-- This value temporarily holds the value of the
-- first calculation.
declare @temp float
-- Convert the decimal degrees to radians
set @lat2 = radians(@lat2)
set @lon1 = radians(@lon1)
set @lat1 = radians(@lat1)
set @lon2 = radians(@lon2)
-- Compute the degree differences
set @dLong = @lon2 - @lon1
set @dLat = @lat1 - @lat2
-- Compute the first part of the equation
set @temp = (square(sin(@dLat/2.0))) + cos(@lat2) * cos(@lat1) * (square(sin(@dLong/2.0)))
-- Return the approximate distance in miles
-- Note that 3956 is the approximate median radius of the Earth.
return (2.0 * atn2(sqrt(@temp), sqrt(1.0-@temp)))*3956.0
end


And C# function

private const double PI_OVER_180 = 0.0174532925;
private static double radians(double DecimalDegrees)
{
return DecimalDegrees * PI_OVER_180;
}
public static SqlDouble ComputeDistance(SqlDouble FromLat,
SqlDouble FromLong, SqlDouble ToLat, SqlDouble ToLong)
{
double lat1, lat2, lon1, lon2,
dLong = 0.0, dLat = 0.0, subCalc = 0.0;
lat1 = radians((double)(FromLat));
lon1 = radians((double)(FromLong));
lat2 = radians((double)(ToLat));
lon2 = radians((double)(ToLong));
dLong = (double)(lon2 - lon1);
dLat = (double)(lat2 - lat1);
subCalc = (Math.Pow(Math.Sin(dLat / 2.0), 2.0))
+ Math.Cos(lat2) * Math.Cos(lat1)
* (Math.Pow(Math.Sin(dLong / 2.0), 2));
return ((2.0 * Math.Atan2(Math.Sqrt(subCalc),
Math.Sqrt(1.0 - subCalc))) * 3956.0);
}
[STAThread]
public static void Main(string[] args)
{
Console.WriteLine(
ComputeDistance(40.7539,-96.6428, 41.28692,-96.07023));
Console.ReadLine();
}

 

Two more projects in MS with codenames

ADO.NET blog announced that two projects has been set up inside Microsoft recently - both revealed at MIX 07.

First one has codename "Astoria" and it's goal is

to enable applications to expose data as a data service that can be consumed by web clients within a corporate network and across the internet. The data service is reachable over HTTP, and URIs are used to identify the various pieces of information available through the service. Interactions with the data service happens in terms of HTTP verbs such as GET, POST, PUT and DELETE, and the data exchanged in those interactions is represented in simple formats such as XML and JSON.

The first early release of Astoria will be a Community Tech Preview that you can download, as well as an experimental online service you can access over the internet.

Check out the Astoria webpage at http://astoria.mslivelabs.com for more information and a link to the download.

 

Second one is called "Jasper" and aim at faciliating data-driven development. Developing data-driven applications could be tedios taks as developers have to spend a lot of time developing supporting infrastructure and Data Access Layer insead of focusing on real business problem. There are many O/R Mapping tools that reduce ammount of work by offering DB-classes mapping along with code generation. I personally though MS try to catch up with LINQ to SQL ( a.k.a DLINQ) and Entity Model in Visual Studio Orcas... but it sounds like they aim higher and use Entity Model for:

    • Dynamic generation of data classes so there is no configuration or design time code-gen to carry around.
    • Rich query and O/R capabilities because “Jasper” is built on top of the Entity Framework.
    • Auto-binding capabilities for ASP.NET, WinForms, and WPF to make binding data to a UI simple and automatic.

Learn more about “Jasper” on the MSDN Data Access Incubation Projects site

MS DevDays 2007

Last week I attended at MS DevDays 2007 - the biggest event organized by Microsoft in Bulgaria. It was impressive as there were four tracks and dev track was so popular that MS decided to open another room where dev lectures could be read for second time :) This was good idea as devs were able to listen more lectures....

This is not all... This year I learned some magic words :) Next Visual Studio Team System has codename - it is Rosario

SQL Server team is working hard too on SQL Server Codename Katmai. The interesting part about it is that there will be Entity model build in it?!?! Yep, I suppose this will be the same Entity Framework that was dropped of VS Orcas release... as SQL team target developers too and they work on make our life easier when we develop data-driven applications.

Here are some pics if the event:

 







Thank you, guys for the interesting presentations!

Use ASP.NET to authenticate users in Winform app

ASP.NET Authentication is very nice and could save a lot of time. Yes, although it covers many cases according Murphy laws you'll need that one that is not covered :). Fortunately there is a way to extend ASP.NET Authentication in order to include all you need. Or even build entirely custom autentication module that works fine with ASP.NET login controls.

But when you want to use single authentication for Windows form and Web applications and decide to use built in ASP.NET Authentication then you will have to write a lot code.

In VS 9.0 (codename Orcas) there is a easy way to use ASP.NET Authentication in Windows Forms application. See sceenshot below:
 




The screenshot is from Visual Studio codename Orcas beta 1
More will be covered soon.

C# 3.0 and Orcas chats

There are several upcoming chats regarding C# 3.0, LINQ and Orcas that could be very interesting

April 23, 2007
11:00 - 12:00 P.M. Pacific Time
Additional Time Zones

C# IDE Chat
C# IDE Chat: Code snippets, enhanced IntelliSense, type colorization, refactoring, improved code navigation, metadata as source, Edit and Continue! There are so many great new C# IDE features in Visual Studio 2005 - there's a lot to talk about! Or perhaps you have a question about Visual Studio 2003 or what we're planning for the next version? It's your choice! Join the C# IDE team for a chat completely directed by your questions.

Add to Calendar

May 7, 2007
11:00 - 12:00 P.M. Pacific Time
Additional Time Zones

C# Compiler and Language Chat
 C# Language Chat. Want to know more about anonymous delegates in C# 2.0, or our design rationale for them? Have some questions about our current thinking on C# 3.0 and LINQ? Perhaps you'd like to share your ideas with other C# users or the C# language team. Join the C# team for all that and more!
Add to Calendar

May 21, 2007
11:00 - 12:00 P.M. Pacific Time
Additional Time Zones

C# LINQ to SQL Chat
The LINQ Project is a codename for a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. LINQ to SQL is a component of LINQ which allows access to data stored in relational databases. We’re actively designing and developing this technology - show up and join the LINQ to SQL team to participate in that process or just get a better understanding!

Add to Calendar



For full list of upcoming chats see MSDN Online Chats

Visual Studio "Orcas" and .NET FX 3.5 Beta1 shipped!

Today MS  signed off on the Beta 1 release for Visual Studio “Orcas” and .NET FX 3.5. 

Go and check here.

Visual Studio Code Name “Orcas” Beta 1

Visual Studio code name "Orcas" is the next generation development tool for Windows Vista, the 2007 Office system, and the Web. Beta 1 consists of multiple releases including, Visual Studio Professional Edition, Visual Studio Team Suite and Visual Studio Team Foundation Server, which are available as installation media ISO images you can use to install the products. Alternatively, you can download VPC images with the software pre-installed. In addition, you can download prerelease versions of Visual Basic Express, Visual C++ Express, Visual C# Express, and Visual Web Developer.

For a better download experience, MSDN Subscribers should use MSDN Subscriber Downloads for both installation media ISO images and VPC images.

 

This news came from Soma

Red bits and green bits in Orcas

Assemblies of next version of .NET Framework are divided in two groups - "green bits" and "red bits" as they are called inside Microsoft.

The red bits include all the libraries that shipped before as part of the .NET Framework 2.0 and 3.0 (such as mscorlib.dll and system.dll). To maintain a high assurance of backward compatibility for Visual Studio "Orcas," changes in the red bits have been greatly limited.

The green bits assemblies are the brand new libraries with additional classes that work on top of the red bits assemblies. Most of the classes listed in this column are in the green bits assemblies (such as system.core.dll), with a few involving limited changes in the red bits assemblies.

The CLR's contributions to the new libraries include:

  • A new add-in hosting model, which was discussed in the last two editions of CLR Inside Out
  • Support for the Suite B set of cryptographic algorithms, as specified by the National Security Agency (NSA)
  • Support for big integers
  • A high-performance set collection
  • Support for anonymous and named pipes
  • Improved time zone support
  • Lightweight reader/writer lock classes
  • Better integration with Event Tracing for Windows® (ETW), including ETW provider and ETW trace listener APIs

There are also new crypto classes that covers Suite B set of cryptographic algorithms.

for more info read New Library Classes in "Orcas"

Start/Stop IIS Site with C#

Have you ever had you deal with IIS management using C#? I mean IIS6?

for IIS 6 you had to deal with DirectoryEntry class like this (code got from here):


   1:  try
   2:  {
   3:      const string WebServerSchema = "IIsWebServer"; // Case Sensitive
   4:      string ServerName = "localhost";
   5:      DirectoryEntry W3SVC = new DirectoryEntry("IIS://" + ServerName + "/w3svc");
   6:      foreach (DirectoryEntry Site in W3SVC.Children)
   7:      {
   8:          if (Site.SchemaClassName == WebServerSchema)
   9:          {
  10:              Console.WriteLine(Site.Name + " - " + Site.Properties["ServerComment"].Value.ToString());
  11:          }
  12:      }
  13:  }
  14:  // Catch any errors
  15:  catch (Exception e)
  16:  {
  17:      Console.WriteLine("Error: " + e.ToString());
  18:  }


and once you find your site you had to execute DirectoryEntry.Invoke("Start", null) or DirectoryEntry.Invoke("Stop", null)  in order to start/stop the site.

Not very convinient but works :).

Well with IIS7 there are a good news and bad news... The bad news is this code won't work on IIS7 (and Vista).

The good news is that there is new .NET assembly () for managing IIS. It is located in %WinDir%\System32\InetSrv\Microsoft.Web.Administration.dll. It contains some wrapper classes that makes dev life much easier :)

with it the task above become:

   1:  ServerManager iisManager = new ServerManager();
   2:  iisManager.Sites["NewSite"].Stop(); 

Much prettier huh?! :)

for more info about Microsoft.Web.Administration.dll read CarlosAg blog's entry Microsoft.Web.Administration in IIS 7

Microsoft gives lessons how to design class libraries

MSR Technical Education Series: Designing .NET Class Libraries

Krzysztof Cwalina (co-author of Framework Design Guidelines) recently did a talk for the Microsoft Research Group on great framework design. 

I heard somewhere that .NET Framework started from about 6000 classes in version 1.0 and grew to 18 000 classes in version 3.0. I am not sure how precise are these numbers but they could give rough idea how big is .NET. All these classes should had been carefully designed so watch this video where Krzysztof Cwalina (program manager, .NET Framework Team, Microsoft) esplains how to design such libraries.

The video is more than 3 hours but I am sure it worths.

(via Brad Adams blog)

Sofia.NET UG meeting

Last week I had a talk on monthly meeting of Sofia.NET User group. The meeting was held in Microsoft Bulgaria office.

There was also beer and snacks kindly provided by Microsoft. There was also presents for the atendees :) You can take a look at pictures taken by Ruslan.

As I promised I publish slides and demos so everyone who is interested could play with them :)

Sofia.NET is free professional group so everyone is invited. If you want to become member and attend on our meetings register here.