Finding Microsoft File Transfer Manager

Earlier today, Microsoft released Windows 8 Beta. Of course, when I was downloading it, I had to leave and head to another building. So, I paused my download in the Microsoft File Transfer Manager. However, I couldn’t find it easily again. I finally found a blog post saying it was called TransferMgr.exe. I searched my machine and found it at “C:\Windows\Downloaded Program Files\TransferMgr.exe”. Be sure to look for it there first in the event of needing it.

Bring Back Visual Studio 11 Installation Customization

Earlier today Microsoft released Visual Studio 11 Beta as a general release. One of the first things you may notice is that the installation customization of VS11 Beta has been removed. If you are installing VS11 on Windows 8 Beta, you’re looking at consuming around 20GB of disk.

So Microsoft already released the beta so their mind is made up, right?

Not exactly. The team is constantly looking at feedback on the http://visualstudio.uservoice.com website. One of the items that I’ve submitted is to bring back the customization. You can use up to three (3) of your User Voice votes for Visual Studio by voting for this item below:

We want to Bring Back Visual Studio 11 Installation Customization Options

Thanks in advance for your support!

Using Data Annotations in the .NET Framework

Starting with .NET 4 or MVC3, a developer could use a data annotation on a property to force data validation. This is extremely powerful especially for MVC developers. The same data annotations can also be used when building custom modules for Orchard CMS.

The annotations built into the framework include the following:

  • Required – Allows you to mark a property as being required.
  • StringLength – Allows a maximum string length to be specified for a property.
  • Range – Validates the value of the specified property is between a range of values.
  • RegularExpression – Allows you to specify a regular expression to validate the content against. A comprehensive list of regular expressions can be found at http://regexlib.com/.

In addition to these above, custom annotations can be built by inheriting from the base class ValidationAttribute.

An example of a custom data annotation is shown below. This sample asks for a start and an end date to be specified as strings. The assumption is that these strings will be in a correct date format. A property value will be specified as a string. The property value must be between the two dates specified.

public class DateRange : System.ComponentModel.DataAnnotations.ValidationAttribute
{
    public string StartDate { get; set; }
    public string EndDate { get; set; }

    public DateRange() {
        this.StartDate = new DateTime(1900, 1, 1).ToString();
        this.EndDate = new DateTime(2099, 1, 1).ToString();
    }

    public override bool IsValid(object value) {
        var valueToString = value as string;
            
        if (!string.IsNullOrEmpty(valueToString)) {
            DateTime dateTimeResult;
                
            if (DateTime.TryParse(valueToString, out dateTimeResult)) {
                return ((dateTimeResult >= DateTime.Parse(this.StartDate)) && (dateTimeResult <= DateTime.Parse(this.EndDate)));
            }

            return false;
        }
        return true;
    }
}

Notice that in the code snippet above, I’m allowing null or empty strings to be passed in. Keep in mind that the Required annotation already checks for nulls or empty strings.


To use the DateRange annotation, simply add it to a property in the model like below:

[DateRange(StartDate="1/1/2012", EndDate="12/31/2012", ErrorMessage="The date must be during the 2012 calendar year.")]
public string EventDate { get; set; }

Additional data annotations can be downloaded from a project started by Scott Kirkland at http://dataannotationsextensions.org/.

Resolving an SmtpException stating ‘Too many messages for this session’

Have you ever noticed an exception being thrown by your application stating something like the following:


System.Net.Mail.SmtpException: Service not available, closing transmission channel. 
The server response was: #4.x.2 Too many messages for this session

This has been an issue since early versions of the System.Net.Mail namespace. The SmtpServer object never included a Dispose() method that properly shutdown the connection to the server. So, even if you are creating new objects, the GC never disposed of the original thus causing this exception.


There are two workarounds for this exception as document on the Connect website:


  1. Upgrade to the .NET Framework 4.0 or later. This version of the framework now includes a Dispose() method that properly closes the connection to the server. Anytime you are connecting to the server to send a message, you should dispose the object afterwards.

  2. If you are using older versions of the framework (.NET Framework 3.5 or earlier), you can set the MaxIdleTime property to 0 and the ConnectionLimit to 1 on the SmtpClient’s ServicePoint object. For example, your code may look like the following:

var client = new SmtpClient("hostname");
client.ServicePoint.MaxIdleTime = 0;
client.ServicePoint.ConnectionLimit = 1;
...
client.Send(new MailMessage(...));

// at this point, the connection will get closed 
// since the ServicePoint idle time is now 0.

Hope this helps to solve any issues you’ve had with this.

TECHbash 2012: A Free Technology Conference in Northeastern Pennsylvania

Ever want to check out the latest technologies but have been too busy dealing with kids, co-workers, or angry birds? Now’s your chance. Push everything aside and get ready to attend the coolest conference in town. Well, it’s not in a town. Pennsylvania only has one of those. Rather, it’s at Luzerne County Community College in Nanticoke, PA. If you’re not familiar with Nanticoke, it’s a small township just south of the City of Wilkes-Barre and approximately 30 minutes south of Scranton, Pennsylvania. While the registration page is not available for TECHbash 2012 just yet, it doesn’t mean that you can’t prepare for the event. It’s really, really important that you do the following. It’s confusing so I’ll outline things for you:

  1. If you are a potential speaker, visit http://techbash.com/news/call-for-speakers-2012. There are a few things we’ll need from you such as your first born, some DNA, your bank account information, … or maybe just a short bio, mugshot, topics, and short description of each proposed talk. But, don’t take my word for it, click the link above and see the “official” post.

  2. If you are a potential sponsor, visit http://techbash.com/news/sponsors-wanted. You’ll find additional information about the event and a method for obtaining the sponsorship packet.

  3. If you are looking to just attend, learn some cool stuff, pick up some swag (software, shirts, etc.) and meet new people, we have nothing for you yet. I know. That’s horrible. Your pumped up, but can’t do anything. Well, that’s not entirely true. If you want to know when TECHbash 2012 registration will be available, you can sign-up for the notification list here: http://techbash2012.kickofflabs.com/. In addition, besides just adding a reminder, you’ll get a special referral code. Whatever attendee gets the most people to add a reminder using their specific referral code will win a super cool prize.

Thanks for taking the time to learn more. On behalf of .NET Valley and the TECHbash coordination team, we look forward to seeing you at TECHbash 2012.

Using HTML 5 Geolocation, Google Maps to Generate Driving Distance

HTML5 will introduce many new and exciting features including the addition of geolocation. Geolocation allows a device to determine a global position of the device (latitude and longitude), it’s accuracy (horizontal accuracy and vertical accuracy), altitude, and speed. The Geolocation feature in HTML 5 is already supported by most mainstream browsers. According to research performed by Mark Pilgrim, the following browser support Geolocation:

IE Firefox Safari Chrome Opera iPhone Android
9.0+ 3.5+ 5.0+ 5.0+ 10.6+ 3.0+ 2.0+

There are a few “gotchas” to keep in mind when using Geolocation:

  1. The browser may not support the HTML 5 geolocation API. Many older browsers relied on custom built APIs for relaying geolocation information to applications. Google Gears, now deprecated, is an example of an API that some browsers have implemented.
  2. The user must opt-in to the HTML 5 geolocation call for each website they visit. In Internet Explorer, the notification bar appears like:

    image
  3. The geolocation call may timeout. This is usually caused by a poor Internet connection or that the current area is not reporting (due to a lack of information) the geolocation yet. For more information on how HTML5 Geolocation works, click here to view the top response to the thread on  StackOverflow.com.

Now that we’ve covered some of the information, let’s focus on the goal for this post. Our goal is to generate the driving distance between two locations. I’ve used this method to let potential TECHbash (see image below as an example) attendees know how far away they are from the conference center. Storefronts may want to implement something similar if they’d like to offer a special offering to local shoppers or from shoppers traveling further away.

image

Above: Small UI update to show current distance from the TECHbash conference.

Let’s start by focusing on obtaining our current geolocation position.

Implementing HTML5 Geolocation

When using the HTML5 geolocation API, we must write some JavaScript. We can use the API in conjunction with JavaScript libraries such as jQuery. The geolocation API call is pretty simplistic. It accepts a callback method, an exception method (optional), and additional options (optional). While it is not required to pass in a callback method to handle errors, it is highly recommended.

navigator.geolocation.getCurrentPosition(callback,error,options);

The callback method, which will return a Position object, will contain a timestamp and coordinate information including the latitude, longitude, altitude, accuracy (horizontal accuracy), altitudeAccuracy (vertical accuracy), heading (direction degrees), and speed (meters per second). Only the latitude, longitude, and accuracy properties are guaranteed to have values.

The error callback method, which will return a PositionError object, will contain a code and a message. The code can be a value of 1 (permission denied), value of 2 (position unavailable), value of 3 (timeout), or value of 0 (unknown error). A message will be supplied from the browser regarding the error.

The additional options object is an object with defined properties. At the time that this was published, the options object, PositionOptions object, has three properties. They are enableHighAccuracy, timeout, and maximumAge.

The final piece of our HTML5 Geolocation implementation is to use an open source JavaScript library called Modernizr. Modernizr is a library that allows developers to take advantage of new HTML5 and CSS3 features while still supporting older browsers such as IE6, Firefox 3.5, and others. We’ll use a function in Modernizr to check for HTML5 Geolocation support.

Now that we’ve covered that, let’s see what we have in place so far:

function getCurrentPosition() {
	if (Modernizr.geolocation) {
		navigator.geolocation.getCurrentPosition(locationSuccess,locationError);
	} else {
		// TODO: Decide what to do when the browser doesn't support Geolocation
	}
}

function locationSuccess(position)
{
	var latitude = position.coords.latitude;
	var longitude = position.coords.longitude;
	// TODO: We have to finish this method
}

function locationError(err)
{
	// TODO: We need to complete our error handling
	if (err.code == 1) { // user won't grant permission }
	if (err.code == 2) { // position is currently unavailable }
	if (err.code == 3) { // a timeout has occurred }
}

Before we tweak this anymore, let’s move onto the Google Maps API.


Implementing the Google Maps API


Much like every other JavaScript library or API, the Google Maps library is constantly changing. At the time of this post, the current Google Maps API was version 3.5. You can add the library to your page by including the script like so:

<script src="http://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script>

The sensor parameter is required. If you will be using a GPS to provide the sensor information to the Google Maps, then set this value to true. We will not in our case so we’ll set it to false.


The portion of the API that we are most concerned with for our implementation is the DirectionsService. We’ll create a DirectionsRequest to send over to Google with a series of parameters. The two major parameters are our two endpoints. We can send these endpoints as a string or as a LatLng object. The other required parameter is the travelMode. Since most attendees will be driving, we’ll using the travelMode for driving. Our request will look like so:

// TODO: Pass actual values into the lat and lon variables below
var start = new google.maps.LatLng(lat, lon);
var end = "1333 S Prospect St, Nanticoke, PA 18634";
var request = {origin:start, 
	        destination:end, 
	        travelMode:google.maps.DirectionsTravelMode.DRIVING};

Next, we need to handle the response from Google. To do this, we’ll call the route function of DirectionsService and obtain the response. If the response’s status code is OK, we’ll be able to process the response as expected. This is shown below.

directionsService.route(request, function(response, status) {
	if (status == google.maps.DirectionsStatus.OK) {
		distance  = response.routes[0].legs[0].distance.value;
	} else {
		// TODO: Handle the Google Maps exception
	}
});

Finally, let’s tie in the rest of the Google Maps API stuff.

var directionsService = new google.maps.DirectionsService();

function calculateRoute(lat, lon) {
	var distance = 0;
	var start = new google.maps.LatLng(lat, lon);
	var end = new google.maps.LatLng(41.195647, -75.992499);
	var request = {origin:start, destination:end, travelMode: google.maps.DirectionsTravelMode.DRIVING};
	
	directionsService.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			distance  = response.routes[0].legs[0].distance.value;
		} else {
			// TODO: Handle the Google Maps exception
		}
	});
	
	return distance;
}

Now that we’ve tied in the Google Maps API, let’s integrate this call into our HTML5 Geolocation script.


Putting it all Together


In our original locationRequest function, we grabbed the latitude and longitude values from the current position of the machine. So let’s add our call to the Google calculateRoute and combine that with a basic HTML5 page. Here is the final result:

<!DOCTYPE html>
<html>

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>The total distance between here</title>
</head>

<body>
	<div>
		The total distance between here and <a href="http://techbash.com">TECHbash 2012</a> is: 
		<span id="distance"></span> miles.
	</div>

	<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js" 
		type="text/javascript"></script>
	<script src="http://ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.0.6-development-only.js" 
		type="text/javascript"></script>
	<script src="http://maps.googleapis.com/maps/api/js?sensor=false" 
		type="text/javascript"></script>
	<script type="text/javascript">
		function getCurrentPosition() {
			if (Modernizr.geolocation) {
				navigator.geolocation.getCurrentPosition(locationSuccess,locationError);
			} else {
				// TODO: Decide what to do when the browser doesn't support Geolocation
			}
		}
		
		function locationSuccess(position)
		{
			var latitude = position.coords.latitude;
			var longitude = position.coords.longitude;

			calculateRoute(latitude, longitude);
		}
		
		function locationError(err)
		{
			// TODO: We need to complete our error handling
			if (err.code == 1) { 
				// user won't grant permission 
			}
			if (err.code == 2) { 
				// position is currently unavailable 
			}
			if (err.code == 3) { 
				// a timeout has occurred 
			}
		}
	
		var directionsService = new google.maps.DirectionsService();
		
		function calculateRoute(lat, lon) {
			var distance = 0;
			var start = new google.maps.LatLng(lat, lon);
			var end = new google.maps.LatLng(41.195647, -75.992499);
			var request = {origin:start, destination:end, 
				travelMode: google.maps.DirectionsTravelMode.DRIVING};
			
			directionsService.route(request, function(response, status) {
				if (status == google.maps.DirectionsStatus.OK) {
					distance  = response.routes[0].legs[0].distance.value;
					duration = response.routes[0].legs[0].duration.value;
					$("#distance").html(Math.round(distance / 1609.344));
				} else {
					// TODO: Handle the Google Maps exception
				}
			});
			
			return distance;
		}
		
		$(document).ready(function() { getCurrentPosition(); });
	</script>
</body>

</html>

Conclusion


You can learn more about the HTML5 Geolocation by using one of the resources below:



You can learn more about Google’s Maps API by visiting the Google Maps API docs.

ASP.NET MVC 4 Beta Released

The ASP.NET MVC 4 Beta and ASP.NET Web API Beta have just been released. You can visit the asp.net, msdn.microsoft.com, or Microsoft Download Center to download the latest bits.

ASP.NET MVC 4 includes many new features including, but not limited to:

  • New Web API support built in
  • New project templates such as the mobile project template.
  • Support for Mobile apps
  • Support for Recipes (similar to, but not quite, like recipes in the Orchard CMS)
  • Support for Async methods (think new async features)

Be sure to check out both. I’ll be posting more on it later on.

ASP.NET MVC 4 and Web API Beta Released

The ASP.NET MVC 4 Beta and Web API Beta have just been released. You can visit the asp.net, msdn.microsoft.com, or Microsoft Download Center to download the latest bits.


ASP.NET MVC 4 includes many new features including, but not limited to:


  • New project templates such as the mobile project template.
  • Support for Mobile apps
  • Support for Recipes (similar to, but not quite, like recipes in the Orchard CMS)
  • Support for Async methods (think new async features)

The Web API allows API’s to be built using WCF and REST.


Be sure to check out both. I’ll be posting more on it later on.