Displaying your position in Bing maps

Using HTML5, it is possible to find the coordinates of your location. The coordinates can be used to display a Bing map with your position pinned to it. The post explains how to do this.

Create a new ASP.NET MVC application. Using HTML5, the latitude and longitude of the current position can be found as follows.


    $(function init() {
        debugger;
        var geo = window.navigator.geolocation;
        watchId = geo.watchPosition(successCb, failureCb);
    });


    function successCb(position) {
        var lat = position.coords.latitude;
        var lon = position.coords.longitude;
        showMap(lat, lon);
    }

    function failureCb(msg) {
        alert(msg);
    }

    function showMap(lat, lon) {
        alert(lat + "-" + lon);
    }

Using Bing Maps, this position can be plotted in a map. First, we need to get a Bing Maps Account key. The following video provides instructions on how to do this: http://www.microsoft.com/en-us/showcase/details.aspx?uuid=7b4206fa-69e1-4c6e-ad10-c8685f5268c9

Bing maps has an AJAX control that is used to show maps in a HTML page: http://www.bingmapsportal.com/ISDK/AjaxV7

The AJAX control can be referenced using the following script:


<script type="text/javascript" 
src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0">
</script>

 With a few lines of code, it is possible to display the map:


function showMap(lat, lon) {
        map = new Microsoft.Maps.Map(document.getElementById('SDKmap'), {
        credentials: 'Bing Account Key', 
        center: new Microsoft.Maps.Location(lat, lon), zoom: 12 });
        map.entities.clear();
        var pushpin = new Microsoft.Maps.Pushpin(map.getCenter(), null);
        map.entities.push(pushpin);
    }

In the above code, SDKmap is the div element which will display the map. The center of the map is your current position. This is further indicated by a pushpin which will locate your position in the map. 

Permalink | No Comments | Leave your comment
 

Deploying a data-tier application in SQL Azure

A data-tier application (.dacpac) is used to create / update database schema. A data-tier application can be deployed in SQL Azure using SQL Server Management Studio (SSMS). There are some scenarios when a data-tier application needs to be deployed programatically.

SQL Azure exposes a Management API using a REST interface: http://msdn.microsoft.com/en-us/library/gg715283.aspx

This interface does not have any API to create or update database or deploy a dacpac.

While searching forums, I found a good thread that explains how to deploy dacpac using Powershell: http://social.msdn.microsoft.com/Forums/en/ssdsgetstarted/thread/4ac3392b-c09f-4146-93ff-0124efc875ab

I have to deploy the dacpac programatically from a worker role using C# code. Executing a powershell script is not a good option because the script requires SQL Powershell Snap-in to execute. The SQL assemblies are not natively available within the worker role. To overcome this limitation, I referenced the SQL assemblies and changed CopyLocal to true. The referenced assemblies are: Microsoft.SqlServer.Smo, Microsoft.SqlServer.Management.Sdk.Sfc, Microsoft.SqlServer.Management.Dac, and Microsoft.SqlServer.ConnectionInfo.

The first step is to connect to the SQL Azure instance and create the DacStore as follows:


string connStr = "Server=tcp:gdpr9zr3i0.database.windows.net;Database=master;User ID=vijay;Password=Pass@word1;Trusted_Connection=False;";
SqlConnection conn = new SqlConnection(connStr);
ServerConnection srvConn = new ServerConnection(conn);
srvConn.Connect();
DacStore store = new DacStore(srvConn);

After the DacStore is created, the dacpac is loaded. The dacpac should be stored as a embedded resource. For some reason, an exception is thrown if the dacpac is loaded from a blob in the storage account. So, the embedded resource option works well for loading the dacpac:


Assembly assembly = this.GetType().Assembly;
Stream stream = assembly.GetManifestResourceStream(this.GetType(), "RetailDb.dacpac");            
DacType dac = DacType.Load(stream);

Finally, the dacpac is installed in the appropriate database using the following code:


string dacName = "RetailDb";
DatabaseDeploymentProperties properties = new DatabaseDeploymentProperties(srvConn, dacName);
store.Install(dac, properties, true);

I believe that the future versions of SQL Azure Management API will have methods to deploy a dacpac. In the meantime, the above code snippet will help deploy a dacpac programatically.
 

Permalink | No Comments | Leave your comment
 

Interesting Ads

I have made a few changes to the blog. The most prominent change is the new Metro-styled menu on the top right corner. I have used the colors from the Metro color wheel. I have also used a font similar closer to the Metro font - Segoe WP.

The Most Popular Tile is a new feature which allows you to view the most-viewed post that is available on the blog. The view count next to the post is only approximate. Whenever a post is viewed even in the home page or the categories page, the view count is incremented. There was also a bug until recently which incremented the view count when comments were fetched.

Watch out for the ads in the top left corner!

Watch out for the ads in the top left corner. The ads are relevant to the content in the page. Most of the ads are informative. Some of the ads are useful. In one of the ads from APRESS, there was a free coupon to download a eBook on developing Metro apps using HTML5 and Javascript. So, the ads are interesting and useful.

Click on the Ads, if it is interesting. It is one way to donate money to the the development of LiteBlog.

Permalink | No Comments | Leave your comment
 

Learn HTML5 in 5 minutes

HTML5 is an evolving web standard. It has good adoption across browsers - IE (10), Firefox, Chrome, Safari, Opera. To see the level of compliance in your browser, visit http://html5test.com. In this post, I will quickly illustrate the basic features of HTML5.

HTML5 introduces new semantic tags like article, section etc which help define the HTML document more logically. An example of HTML5 document is shown below:


<article>
 <hgroup>
  <h1>Title of the page</h1>
  <h2>Subtitle</h2>
 </hgroup>
 <section>
  <h1>Virgin Gorda</h1>
  <p>The Baths at Virgin Gorda are truly one of the most picturesque places in the Caribbean.<p>
 </section>
</article>

HTML5 introduces new input tags - email, telephone, date, number. Email allows only valid email addresses to be entered. Telephone accepts a pattern and allows only text following that pattern. Date shows a calendar when clicked on the textbox. Number allows only integers to be entered within a defined range.


<input type="email" name="email" required placeholder="Enter your email:"/>
<input type="tel" name="tel" required placeholder="Enter telephone" pattern="\([\d]{3}\) [\d]{3}-[\d]{4}"/>
<input type="date" name="bday" required placeholder="Enter birthday"/>
<input type="number" name="age" min="5" max="15" required placeholder="Enter age"/>

HTML5 has a canvas tag. Within the canvas tag, a graphics context can be obtained which can be used to draw shapes and strings. The following script draws a rectangle within the canvas:


<canvas id="mycanvas" height="250" width="250" style="border: 2px solid #f00"></canvas>

function draw2 () {
    var canvas = document.getElementById("mycanvas");
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "red";
    ctx.fillRect(20, 20, 50, 50);
}

HTML5 supports vector graphics using SVG (as opposed to bitmap operations in canvas). The following markup draws a rectangle, circle and some text using SVG.


<svg width="300" height="300" style="border: 2px solid red;">
<text style="font-size: 30; stroke: blue;" x="10" y="170">
    Hello SVG World
</text>
<rect x="5" y="50" width="150" height="30" style="fill: yellow;" />
<circle cx="20" cy="50" r="20" style="fill:red;" />
</svg>

HTML5 has rich support for styles using CSS 3. For eg, a rounded border can be rendered using the following styles - webkit- for Safari, Chrome, -moz- for Firefox, -o- for Opera, -ms- for IE:


div
{
    -moz-border-radius: 20px;
    -webkit-border-radius: 20px;
    -ms-border-radius: 20px;
    -o-border-radius: 20px;
}

HTML5 supports CSS animations. The following style animates the height for a duration of 5 seconds:


div#formPanel > p:hover
{
    height: 50px;
    -webkit-transition-property: height;
    -webkit-transition-duration: 5s;
    -webkit-transition-timing-function: ease; 
}

Geo-location is another HTML5 standard supported within the browsers. The following script gets the latitude and longitude of the current position and shows it on Virtual Earth:


if (window.navigator != null) {
    var geo = window.navigator.geolocation;
    watchID = geo.watchPosition(successCb, failureCb);
}

function successCb(position) {
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;
    showMap(lat, lon);
}

HTML5 has good multi-media support. The audio and video tags in HTML5 embed audio and video respectively:


<video src="@Url.Content("~/Content/Wildlife.wmv")" width="400" 
height="300" style="border: 2px solid #f00" controls preload="false"> 
<audio src="@Url.Content("~/Content/Maid.mp3")" width="400"
 height="300" style="border: 2px solid #f00" controls>

LocalStorage, IndexedDB, WebWorkers, and WebSockets are other interesting features in HTML5. Local storage provides more storage within the browser - much more than what is available with cookies. IndexedDB allows a database to embedded locally. WebWorkers allows browsers to run long processes without affecting the UI. WebSockets allow bi-directional socket communication with the server, the most popular being chat and gaming applications.

Permalink | No Comments | Leave your comment
 

Silverlight in Windows 8

I stumbled upon a link that talks about the end of Flash and Silverlight: http://debuggerdotbreak.wordpress.com/2011/11/11/the-bell-tolls-for-flash-and-silverlight-isnt-far-behind/

I do not think that Silverlight is dead yet. There are a lot of developers with WPF / XAML skills who are comfortable building Silverlight apps. It is preferrable to use Silverlight for line-of-business (LOB) applications within the Windows desktop environment. But, there are some conflicting messages about Windows 8.

The metro UI in Windows 8 is primarily targetted for the tablet users. Windows 8 cold boots in 4 seconds. Metro itself seems to be really good. But, what is bad for Silverlight developers is that Metro is based upon HTML 5 and not Silverlight. The Metro UI in Windows 8 has a browser that does not support any plugins including Silverlight. If you want to experience Silverlight apps in Windows 8, you will have to click on the desktop tile, and use the browser from there. So, using Silverlight for consumer applications is not a good idea. But for business apps, it is still a very good choice.

The other thing that is somewhat confusing is that Windows 8 does not run apps built for Windows phone. If you buy a mobile device and a tablet both running Windows, the chances are that you may have to buy two versions of the same app - one for the tablet and another for the mobile. This can lead to a slightly different user experience. Also, from a developers perspective, developers have to write different implementations for the mobile and the tablet.

This is early days as Windows 8 is available for developers to preview. I am sure a lot will change before Windows 8 goes live. Silverlight applications will run from the browser on the desktop tile. Also, Silverlight Out of browser applications will run as a tile from the Metro UI. So, Silverlight will live for sometime. I am looking forward for the next release of Silverlight - Silverlight 5 for more directions on its future.

 

Permalink | No Comments | Leave your comment
 

Service throttling issues in WCF hosted in Windows 7

My development environment is WCF 4 / IIS 7.5 / Windows 7 Professional. I have a WCF service with a single operation that sleeps for 2 seconds. My goal is to run 100 concurrent requests and ensure that all the requests complete within 2.1 seconds.

I started tinkering with service throttling. A service can have a service behavior which has throttling properties defined. So, I set the following parameters:


<serviceThrottling maxConcurrentInstances="100"
maxConcurrentCalls="100" maxConcurrentSessions="100" />

I went into perfmon and check the ServiceModelService => TimeOutService => Instances counter. It was showing as 10.

I assumed that there was some problem with the processModel. So, in machine.config, I changed the processModel to:


<processModel autoConfig="false"
minIOThreads="100" minWorkerThreads="100"
maxIOThreads="100" maxWorkerThreads="100" />

In perfmon, the instances counter was showing as 10. So, I went and checked the .NET CLR LocksAndThreads => w3wp => Total logical threads. This counter was showing somewhere between 30 and 40.  Again, very confusing.

After searching for more information, I found this forum post which suggests that Windows 7 has some limitations on performance tuning: http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/449c17ca-1518-49f7-a58e-c043f0751bce/ . I wish I had checked this post earlier!

Permalink | No Comments | Leave your comment
 

Good articles in DNK

Here are some good articles in DNK for this month:
http://blogs.dotnetkicks.com/best-of-dnk/2011/11/02/best-net-articles-of-october-2011-fresh-off-the-presses/

I have been working on an interesting assignment involving Exchange web services (EWS). If you want to get started using EWS Managed API SDK, here is how you can:
http://blogs.dotnetkicks.com/vijayst/2011/11/getting-started-with-ews-managed-api-sdk/

I have been working on Silverlight and MVVM for the past few weeks. PRISM is an implementation of MVVM pattern. Here is the project in Codeplex:
http://compositewpf.codeplex.com/

Permalink | No Comments | Leave your comment
 

Data validations in Silverlight RIA applications

After a lot of reading, I have finally sort of figured out how to do data validations in Silverlight applications that use WCF RIA services.

Data validations should be performed both on the Silverlight application (that runs on the browser) as well as WCF RIA Service layer that runs on the web server. As of now, RIA applications support DataAnnotations as the main way of validating data. When a RIA service is created (say. CategoryService), a CategoryService.metadata.cs is also created. Within this file, a partial Entity class (Category) is defined. This is the place where you put all your data annotations.

When a Silverlight app is built, the Silverlight side entity classes are generated. This includes the data annotations defined in the server. Also, the class is derived from Entity abstract class which implements INotifyDataErrorInfo interface.

CustomValidation attributes are used whenever a validation requires access to the database. Here is a golden blogpost which describes exactly how it works: http://jeffhandley.com/archive/2010/05/26/asyncvalidation-again.aspx

CustomValidation when triggered from the Silverlight side is asynchronous. If you look at the above post, the service returns a Sucess. And then, if it finds any error, it asynchronously updates the ValidationErrors for the Entity. If the user does a Submit or Save before the async operation completes, the same validation should be performed at the server using the same CustomValidation attribute. Again, the above post is just amazingly cool as it explains how to do it.

There are other things you have to handle. The SubmitChanges of the DomainContext is asynchronous. So, any failures or success should be handled asynchronously in the callback method.

Validations using Data Annotations (in Silverlight or service) raise exceptions. In the Silverlight side, the framework knows how to invalidate the control state. When validations fail in the server, you will have to add the error to the ValidationErrors collection of the Entity class. This will invalidate the control.

While using data annotations, you will have to somehow let the ViewModel or the Entity know that there are errors. This is not automatically done.

Final tip: Do not try to roll your own custom framework using IDataErrorInfo or INotifyDataErrorInfo. It costs a lot of money. And you will have to do it at the service layer also.

Permalink | No Comments | Leave your comment