Galin Iliev's blog

Software Architecture & Development

Microsoft ASP.NET Futures May 2007

Have you asked yourself "What do I want from ASP.NET?", "How web development would look like in 2, 4, 6 years from now?", "Is the Silverlight silver bullet in web development?"... Well who knows... but there is CTP of what Microsoft is working on in ASP.NET area and it is called Microsoft ASP.NET Futures (May 2007) Release.

ASP.NET Futures includes a number of new, innovative solutions that help developers become more productive and enables them to create better user experiences for their customers. Features include:

ASP.NET AJAX Futures

The new release includes support for managing browser history (Back button support), selecting elements by CSS selectors or classes, and information on accessing “Astoria” Web data services.

Silverlight Controls for ASP.NET

You can integrate the rich behavior of Microsoft® Silverlight™ into your Web application by using two new ASP.NET server controls: a Media server control that enables you to easily integrate media sources such as audio (WMA) and video (WMV) into your Web application, and a XAML server control that enables you to reference your own XAML and associated JavaScript files.

Dynamic Data Controls for ASP.NET

Dynamic data controls are a set of ASP.NET server controls that obtain database schema information at run time, provide default display formats according to common user expectations, and enable you to easily customize those formats. Watch a video showing how to build a task list application using the Dynamic Data Controls from the ASP.NET Futures Release.

Download video with demo

ASP.NET Application Services

New services for ASP.NET enable you to add search to your ASP.NET Web applications, using a commercial search engine’s API (such as Windows Live Search) and custom search providers. You can also publish custom and dynamic sitemaps that are configured to assist search engine crawlers. A new service lets you capture JavaScript errors and report them to server-based ASP.NET code.

Dynamic Languages Support in ASP.NET

In ths release, support for dynamic languages in ASP.NET expands on the earlier support for IronPython for ASP.NET. Support for dynamic languages in ASP.NET is built on the Dynamic Language Runtime (DLR), a new platform currently under development at Microsoft. The DLR simplifies hosting dynamic languages on the Common Language Runtime.

Two dynamic languages are now hosted on the DLR: IronPython and Managed JScript.

Via Somasegar's WebLog

I almost forgot :)  There are quickstarts @ http://quickstarts.asp.net/futures/ as well as not bad documentation

Hello "Jasper"

I wrote about the couple new projects that was announced by Microsoft recently and I’ve installed “Jasper” and I had some free time this weekend to play with it.

You may ask What is Jasper? The answer comes from documentation: 

Microsoft® Codename “Jasper” is a set of components aimed at fulfilling the need for a rapid and iterative development experience for data. With “Jasper”, you are able to just point at a database and immediately begin coding against its data using intuitive, domain-specific data classes. No configuration and no source code generation are required. Jasper works with existing application frameworks (including ASP.NET, WinForms, and WPF) and existing, real-world databases.

First thing I noticed is the first CTP comes with samples in Visual Basic and IronPython which is not the best way to impress C# fans J I haven’t given up and I kept investigating and I am going to share with you my findings.

Working with Jasper is very similar to LINQ to SQL. Everything is done through DynamicContext class and using it’s methods GetQuery,  AcceptAllChanges, CreateQuery and many others . The difference is that in LINQ to SQL there is a class that extend DataContext class but in Jasper  DynamicContext class is compiled in MS assemblies. If you play with it you’ll notice there aren’t any properties that represents tables in underlying database. But this is code snippet from samples that comes with Jasper:

Dim connectionString As String

Dim context As Object

 

connectionString = _ ConfigurationManager.ConnectionStrings("Northwind").ConnectionString

context = DynamicContext.CreateDynamicContext(connectionString)

 

'*** get Customer table by late binding

Dim query As Query = context.Customers

 

'*** bind to grid

ResultsGrid.DataSource = query

ResultsGrid.DataBind()

Do you see the row that ends with context.Customers? On this row the content of Customers table is got and can be used in lines below to be bound to GridView control.  As we said the class DynamicContext is same for all applications and the tables are got using late binding because the Jasper data classes are generated dynamically at runtime when DynamicContext.CreateDynamicContext() is called.

 Late binding could be painful in C# and it seems this is reason not having samples in C# for nowJ.

I will cover another feature in Jasper – dynamic queries. There is very easy way to construct queries in Jasper. All you have to do is using Microsoft.Jasper.Query class and it’s methods  Select, OrderBy, Where, Union ( and many others ):

Dim query As Query = context.Customers

query = query.Where("it.Country = 'USA'")

query = query.OrderBy("it.CompanyName")

query = query.Select("it.CustomerID, it.CompanyName, it.City")

 

Dynamic queries are doubtful from architecture standpoint as they could harm the design and easy mess DAL code with business logic. This is why I recommend avoiding dynamic queries when possible or use them very carefully.

This blog entry contains very little code but I can assure you this is enough to get Customer table content and display it in Grid control on ASP.NET page. J

You can get Jasper from Microsoft Downloads.

And don’t forget the prerequisites:

1)      Microsoft Visual Studio® Codename “Orcas” Beta 1.  Install details can be found at http://msdn2.microsoft.com/en-us/vstudio/aa700831.aspx.

2)      Microsoft SQL Server™ 2005.  The Microsoft SQL Server 2005 Express Edition can be found at http://www.microsoft.com/downloads/details.aspx?familyid=220549b5-0b07-4448-8848-dcc397514b41&displaylang=en.

3)      (Optional) Microsoft Iron Python 1.1.  The install can be found at  http://www.codeplex.com/IronPython/Release/ProjectReleases.aspx?ReleaseId=2573.

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!

LINQ modules

If you're C# developer you probably have heards about C# 3.0, LINQ, LINQ to SQL, LINQ to XML, LINQ to Entities and so on... Are you confused about these LINQ to XXXX stuff? Have you asked yourself how these modules are related?!

This is very good diagram posted in in June issue of MSDN Magazine by Anson Horton (PM in C# team):

Read full C# 3.0 overview.

Databases tips

I have been dealing with MS SQL Server 2005 and Microsoft SQL Server 2005 Analysis Services as well as Reporting services to display results to end users.

It was amazing how many issues are in the fields of databases. I developed projects on my dev box with snapshot of database (biggest table contains aprox 200,000 rows) and I though it was done. Unfortunately I was not able to deploy in production because of following reasons:

  • cube and dimensions processing was extremely slow - this was solved with playing with indecies
  • Memory error: The operation cannot be completed because the memory quota estimate (1678MB) exceeds the available system memory  - this was on 4xCPU and 4GB RAM on 32bit Windows 2003 std. This was solved with limiting SQL Server serive memory to 2GB and set /3GB startup switch in windows.
  • then came:  Arithmetic overflow error converting expression to data type int. This was tough also because I had to wait 2:30 hours before I get the error. then I make changes and try again... this was very, very long loop. For fully understand it check SQL Server Books and as resolution check Barnabas Kendall's blog entry.

there are  some good points in Barnabas Kendall's blog entry like:

I don’t enjoy reading documentation (lack of plot and character development),   :):)

  • Create the view with the SCHEMABINDING option.
  • Define the view to pre-aggregate the data (this is where the performance enhancement comes from). For example, I have a view that splits up the year, month, day, and hour of a click, groups by client, and also returns a total. I can also reuse this view to get totals by hour, day, month, year, or all time.
  • Don’t use COUNT, use COUNT_BIG.
  • Don’t use AVG; use SUM and COUNT_BIG. Beware of integer overflows in your final query; SUM always wants to make an INT. Why isn’t there a SUM_BIG? You can get around this by using CAST or CONVERT in your final query.
  • Make a clustered unique index on the view. This forces the database engine to persist the values to disk rather than calculating them on the fly, which is what leads to five-minute queries. I am surprised to learn that you don’t need to put all the values of the table in the index, just the ones necessary to make a clustered unique index.
  • When querying the view, use the NOEXPAND hint.


I would like to add: All aggregate functions return result depending on input parameter's type- if input column is of type int and result would be if type int:

select sum(numbers) from dbo.TestTable

And if you use SUM of multiple rows all that contains values like 2,000,000,000 you will end up with Arithmetic overflow error

In order to change result type this:

select sum(cast(numbers as bigint)) from dbo.TestTable


I employed some of these techniques and started the process again. I am keeping my fingers crossed...