Scott Hanselman

ASP.NET MVC DisplayTemplate and EditorTemplates for Entity Framework DbGeography Spatial Types

September 4, '12 Comments [28] Posted in ASP.NET | ASP.NET MVC
Sponsored By

UPDATE: Be sure to read the whole post including the refactoring update at the end via a Pull Request from Dave Ward.

I was trying to write a blog post about something totally different and was using this small EntityFramework 5 Code First model:

public class TouristAttraction
{
public int TouristAttractionId { get; set; }
public string Name { get; set; }

public DbGeography Location { get; set; }
}

The little bit I added

You'll notice I'm using the DbGeography spatial type with Latitude and Longitude. This support is new in Entity Framework 5. For a more complex example I might want to make a custom type of my own or split things up into a double lat and double long, but for this little app I just wanted a few fields and a map.

However, when I was scaffolding things out, of course, DbGeography was left in the cold. It wasn't scaffolded or included. When I added a map, there was no model binder. When I started making more complex views, there was no EditorFor or DisplayFor template support. So, rather than finishing the thing I was trying to do (I'll finish that project later) I became slightly obsessed focused with getting some kind of basic system working for DbGeography.

First, I scaffolded out a standard Entity Framework controller for "TouristAttraction" and changed nothing. The goal was to change nothing because DbGeography should just be treated like any other complex type. My prototype should be easily changeable for any other database or map system. There shouldn't be any Controller hacks to get it to work.

There's basically a DisplayTemplate and an EditorTemplate to show and edit maps. There's a model binder to handle DbGeography, and a small helper extension to get the client id for something more easily.

There's also some supporting JavaScript that I'm sure Dave Ward will hate because I'm still learning how to write JavaScript the way the kids write it today. Refactoring is welcome.

Creating and Editing

When creating a TouristAttraction you type the name then click the map. Clicking the map puts the lat,long in a text box (that could be hidden, of course).

Creating a location with a clickable Google Map

I simply added a Google Map to the Layout:

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

then on the Create.cshml used an EditorFor just like any other field:

<fieldset>
<legend>TouristAttraction</legend>

<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Location)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Location)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>

There is an EditorTemplate called DbGeography, the name of the type by convention. If the type is "Foo" and the file is EditorTemplates/Foo.cshtml or DisplayTemplates/Foo.cshtml you can use EditorFor() and DisplayFor() and the whole app gets the benefits.

@model System.Data.Spatial.DbGeography
@Html.TextBox("")
@if (Model != null) {
<script>
$(function () {
maps.markerToSet = new google.maps.LatLng(@Model.Latitude, @Model.Longitude);
});
</script>
}
@{ string textbox = Html.ClientIdFor(model => model).ToString(); }
<div id="map_canvas" data-textboxid="@textbox" style="width:400px; height:400px"></div>

This EditorTemplate needs to support Create as well as Edit so if Model isn't null it will set a variable that will be used later when the map is initialized in an Edit scenario.

Next steps would be to make a generated map id for the div so that I could have multiple maps on one page. I'm close here as I'm sticking the "friend" textbox id in a data- attribute so I don't have to have any JavaScript on this page. All the JavaScript should figure out names unobtrusively. It's not there yet, but the base is there. I should also put the width and height elsewhere.

You'll notice the call to ClientIdFor. At this point I want the name of the textbox's client id but I don't know it. I don't want to make an EditorTemplate that only works hard-coded for one type so I need to get the generated value. I have an HtmlHelper extension method:

public static partial class HtmlExtensions
{
public static MvcHtmlString ClientIdFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
return MvcHtmlString.Create(
htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression)));
}
}

This won't work unless you are sure to add your HtmlExtensions full namespace to the web.config in the Views folder under namespaces. That will let Razor see your HtmlHelper Extension method.

NOTE: Make sure you add a reference to System.Data.Entity to your MVC View's web.config in order to have a @model like I have above.

<compilation ... >
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</assemblies>
</compilation>

When you click the map it fills out the text box. I've also got some initial values in here as well as the addListenerOnce which is used later in DisplayFor to load a read-only" map when viewing a record's details.

function maps() { }
maps.mapInstance = null;
maps.marker= null;
maps.mapInstanceId = "map_canvas";
maps.markerToSet = null;

function initialize() {
var latlng = new google.maps.LatLng(40.716948, -74.003563); //a nice default
var options = {
zoom: 14, center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
maxZoom: 14 //so extents zoom doesn't go nuts
};
maps.mapInstance = new google.maps.Map(document.getElementById(maps.mapInstanceId), options);

google.maps.event.addListener(maps.mapInstance, 'click', function (event) {
placeMarker(event.latLng);
});

google.maps.event.addListenerOnce(maps.mapInstance, 'idle', function (event) {
if (maps.markerToSet) {
placeMarker(maps.markerToSet);
var bound = new google.maps.LatLngBounds();
bound.extend(maps.markerToSet);
maps.mapInstance.fitBounds(bound);
}
});
}

function placeMarker(location) {
if (maps.marker) {
maps.marker.setPosition(location);
} else {
maps.marker = new google.maps.Marker({
position: location,
map: maps.mapInstance
});
}

if (maps.marker) { //What's a better way than this dance?
var textboxid = $("#" + maps.mapInstanceId).data("textboxid");
$("#" + textboxid).val(maps.marker.getPosition().toUrlValue(13));
}
}

$(function () {
initialize();
});

When I've filled out a new location and hit SAVE the lat,long is POSTed to the controller which I want to "just work" so I made a Model Binder to handle the DbGeography type.

I add it (actually its provider in case I add to it with other Entity Framework types) to the ModelBinderProviders collection in Global.asax:

ModelBinderProviders.BinderProviders.Add(new EFModelBinderProvider());

The ModelBinder itself tries to be generic as well. I must say I see FAR too many CustomModelBinders out there with folks calling into Request.Form digging for custom strings. That's not reusable and it's just wrong.

public class DbGeographyModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
string[] latLongStr = valueProviderResult.AttemptedValue.Split(',');
string point = string.Format("POINT ({0} {1})",latLongStr[1], latLongStr[0]);
//4326 format puts LONGITUDE first then LATITUDE
DbGeography result = valueProviderResult == null ? null :
DbGeography.FromText(point,4326);
return result;
}
}

public class EFModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(Type modelType)
{
if (modelType == typeof(DbGeography))
{
return new DbGeographyModelBinder();
}
return null;
}
}

At this point, DbGeography is model bound and I don't have to change the controller. Now, again, I am NOT using a ViewModel here but I would on a larger application so be aware. I'd likely make a custom model binder for that hypothetical ViewModel and it would to be married to a database technology like this one is.

You can see in the database that I've got the points stored as "geography" types and they are round tripping just fine.

Entity Framework v5 Code First and VS2012 support for SQL Server's geography types

I threw this ASP.NET MVC 4 sample up on GitHub in https://github.com/shanselman/ASP.NET-MVC-and-DbGeography. You'll need VS2012 to play.

Again, please forgive my 3am hacking and poor JavaScript but I hope you get the idea and find it useful. I think this has the potential to be packaged up into a NuGet or perhaps useful as an EntityFramework and ASP.NET MVC sample.

IMPORTANT NOTE: In order to save lots of space space with samples I didn't check in binaries or include the packages folder with dependencies. Make sure that you have given NuGet permission to download missing packages during a build if you want to build this sample.

Be sure to click "Allow NuGet to download missing packages during build"

I've enabled NuGet Package Restore in the project by right clicking on the Solution node and clicking "Enable NuGet Package Restore." This will cause NuGet to download the missing packages on build, so be aware as there will be a pause on the first build when NuGet updates the package.

UPDATE #1

My buddy Dave Ward took a look at the code and submitted a pull request that improves some of the JavaScript and makes it more the way "the kids are writing JavaScript these days."

Dave has finished up a number of things for me. First, he's made things generic enough so one can have multiple maps on a page. He has also tidied up my JavaScript.

He starts by removing any inline script from the DisplayTemplats and EditorTemplates and instead uses the TextBox itself to hold the data. This, of course, is just one of several "duh" moments for me and a reminder that using HTML elements to hold data is kind of what they're for. It also brings up an interesting debate about views and models. I did think about using KnockoutJS for this but thought it overkill.

@model System.Data.Spatial.DbGeography
@if (Model != null) {
@Html.TextBox("", Model.Latitude + "," + Model.Longitude, new { @class = "editor-for-dbgeography" })
} else {
@Html.TextBox("", "", new { @class = "editor-for-dbgeography" })
}
Dave also introduces CSS classes as markers for the text boxes to identify them as editors for a DbGeography. That's editors, plural, since the primary limitation of my implementation was that there could be only one.

Dave now keys off the text boxes rather than a div. He initializes any of these text boxes (for display or editor) and dynamically adds the Google Map after each.

$('.editor-for-dbgeography, .display-for-dbgeography').each(initialize);

He pulls the lat,long out of the text box and creates the map. When the text box changes he set a marker and pans the map to the new location.

It's surprisingly readable.

(function() {
// Method signature matching $.fn.each()'s, for easy use in the .each loop later.
var initialize = function(i, el) {
// el is the input element that we need to initialize a map for, jQuery-ize it,
// and cache that since we'll be using it a few times.
var $input = $(el);

// Create the map div and insert it into the page.
var $map = $('<div>', {
css: {
width: '400px',
height: '400px'
}
}).insertAfter($input);

// Attempt to parse the lat/long coordinates out of this input element.
var latLong = parseLatLong(this.value);

// If there was a problem attaining a lat/long from the input element's value,
// set it to a sensible default that isn't in the middle of the ocean.
if (!latLong || !latLong.latitude || !latLong.longitude) {
latLong = {
latitude: 40.716948,
longitude: -74.003563
};
}

// Create a "Google(r)(tm)" LatLong object representing our DBGeometry's lat/long.
var position = new google.maps.LatLng(latLong.latitude, latLong.longitude);

// Initialize the map widget.
var map = new google.maps.Map($map[0], {
zoom: 14,
center: position,
mapTypeId: google.maps.MapTypeId.ROADMAP,
maxZoom: 14
});

// Place a marker on it, representing the DBGeometry object's position.
var marker = new google.maps.Marker({
position: position,
map: map
});

var updateMarker = function(updateEvent) {
marker.setPosition(updateEvent.latLng);

// This new location might be outside the current viewport, especially
// if it was manually entered. Pan to center on the new marker location.
map.panTo(updateEvent.latLng);

// Black magic, courtesy of Hanselman's original version.
$input.val(marker.getPosition().toUrlValue(13));
};

// If the input came from an EditorFor, initialize editing-related events.
if ($input.hasClass('editor-for-dbgeography')) {
google.maps.event.addListener(map, 'click', updateMarker);

// Attempt to react to user edits in the input field.
$input.on('change', function() {
var latLong = parseLatLong(this.value);

latLong = new google.maps.LatLng(latLong.latitude, latLong.longitude);

updateMarker({ latLng: latLong });
});
}
};

var parseLatLong = function(value) {
if (!value) { return undefined; }

var latLong = value.match(/-?\d+\.\d+/g);

return {
latitude: latLong[0],
longitude: latLong[1]
};
};

// Find all DBGeography inputs and initialize maps for them.
$('.editor-for-dbgeography, .display-for-dbgeography').each(initialize);
})();

The next step will be to bundle this all up in a NuGet. Any ideas on a clear name? AspNet.Net.Mvc.SpatialTemplates?

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Pinning Useful and Obscure Stuff to the Windows 8 Start Menu

August 29, '12 Comments [83] Posted in Tools | Win8
Sponsored By

imageThere were a lot of good comments on my post Windows 8 productivity: Who moved my cheese? Oh, there it is. I've continued to explore ways to remove clicks from my life and shorten keystroke chains. A number of folks said they didn't like this thing or that thing because they felt something used to be 2 clicks and now it's 3 or it used to be 1 and now it's 8. It's good to be reminded that you can customize almost everything in Windows. You can make scripts and batch files to your heart's content, and most importantly, any shortcut to nearly anything can be pinned to both the Taskbar and the Start Menu. Here's some examples just to make the point.

Folders

Let's say that you want to quickly get to the folder where you download stuff. You can make the Downloads folder available on the Taskbar as well as the new Start menu.

Pin to a Taskbar icon

You can drag any folder to your Explorer Taskbar icon and pin it. Here the menu is visible when right-clicking on the Explorer icon. You can also pin (promote) links from the Frequent section as well.

Downloads is Pinned to the Explorer Taskbar

Pin to the Windows 8 Start Menu Screen

You can also take any icon or folder from the desktop and right-click to Pin to Start.

Pin to Start

Now my Downloads folder is on my Start and can be opened in one click/touch after pressing the Windows key.

Download is pinned to Start

Pinning other Shortcuts of all Kinds

Once you know you can pin stuff, you can make custom shortcuts and pin other stuff. Right click anywhere and make a new Shortcut. This is a generic pointer to whatever you like.

New Shortcut

You can change the properties of a shortcut like I have here. I've got a shortcut to shutdown with -t 0 added to the parameters so the system will shutdown immediately.

NOTE: You CAN make these shortcuts if it will make you happy but in the case of Shutdown, I just press the Power Button.

shutdown.exe -s -t 0

Now just right click the new shortcut and pin it to either the Taskbar or Start. If you're tidy, and I am sure you are, why not customize the icon?

Shutdown Icon customized

And now my new Shutdown icon looks like this. There you go, one-click shutdown. Happy? ;)

A magical Shutdown Icon on my Start Menu

Pinning Custom Actions like Sleep and Restart

You can of course make more complex shortcuts to do things like Sleep your computer with other commands.

Shutdown Computer

Shutdown.exe -s -t 00

Restart Computer

Shutdown.exe -r -t 00

Lock Workstation

Rundll32.exe User32.dll,LockWorkStation

Hibernate Computer

rundll32.exe PowrProf.dll,SetSuspendState

Sleep Computer

rundll32.exe powrprof.dll,SetSuspendState 0,1,0

NOTE: You CAN make these shortcuts if it will make you happy but in the case of Sleep, I just close the lid on my laptop.

Pin Internet Explorer 10 Desktop in the Start Menu

Now that you have figured out how to make crazy shortcuts then Pin them. Hopefully this is as empowering to you as it is to me.

As a Web Developer I have a bunch of Web Browsers pinned to both Start and the Taskbar. However, the Internet Explorer icon in the Start Menu goes to the full screen IE10 and sometimes I want the Desktop IE10.

Desktop IE10

If you refer to this old old old Windows XP Knowledge Base Article you'll see that they show a number of ways you can make Internet Explorer shortcuts. Of course, the easiest one is the one you should do. ;)

NOTE: You can also make a more "real" Internet Explorer link with this "%windir%\explorer.exe shell:::{871C5380-42A0-1069-A2EA-08002B30309D}" as a new Shortcut if you like.

Go to c:\program files\internet explorer and right click on iexplore.exe and pin it. Alternatively you can Copy, then Paste Shortcut, then Rename the shortcut. I named mine "Internet Explorer (Desktop)."

Get iexplore.exe and pin it, then rename

Now I've got two choices! Just like I like it.

Both IE10 metro and IE10 Desktop are both pinned to my Start Menu

Pinning Web Sites and Customizing IE10 Pinned Site Icons

You can pin Web Sites from within IE10 using the menu in the lower right corner. That's also the same context menu that includes Jump Lists. Jump Lists can be added easily with just <meta> keys in your HTML.

Context Menu in Full Screen IE10

If your favicon.ico has a 32x32 version that is the resolution of Icon that will be used for your pinned site. The background color for the icon comes from the main color of the icon.

My giant forehead is now pinned to your Start Menu

If you want a different icon or color, you can set those with Meta Tags as well. Hm, my giant head isn't big enough. I'll add a 144x144 PNG.

<meta name="msapplication-TileImage" content="/blog/images/hanselman-144.png" />

There we go. Much clearer. I can also control the background color with msapplication-TileColor if I want using a #rgb color.

You can have a high-res 144x144 PNG if you like

I've pinned all sorts of stuff. Apps, Links, Folders, Browsers, Custom Tasks, Libraries and more. No, I didn't actually pin my face. Oh, and that days app is "Save The Date."

All sorts of pinning

Have fun customizing!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Windows 8 productivity: Who moved my cheese? Oh, there it is.

August 25, '12 Comments [169] Posted in Win8
Sponsored By

Keep Calm and Use Your Keyboard - @robertmclawsDisclaimer: I don't work for the Windows Team. I installed Windows 8 on my home desktop (this giant multi-monitor epic beast) with my personal MSDN account and wrote this on my own time. This blog is mine and the opinions inside are also mine. I also installed it on my MacBook Pro.

I finally pulled the trigger and upgraded a few machines to Windows 8. I have three main machines, my formerly "Ultimate Developer PC 2.0" whose video card gets slower by the year, my almost-retina-but-just-two-months-late Mac Book Pro, and my Lenovo W520.

I am a web guy SO much more than a desktop guy so if you look in my Taskbar on any of my machines you'll see mostly web browsers, text editors and shells. I live off my taskbar and I'm ALL about HotKeys. If I can avoid touching my mouse at all I will. I spoke to Brad Wilson on this week's podcast about his experience with Windows 8 as well.

Who moved my cheese?

People don't like it when you move their cheese. They are just trying to get through the maze, they have it all under control and then, poof, someone moved their cheese. Now it's a huge hassle to find it again. Change a hotkey or the case of the menus and all heck breaks loose.

The installation process was straightforward and everything still worked when it was done, so that was a relief. I upgraded from Windows 7 Ultimate to Windows 8 Pro. There's fewer SKUs in Windows 8 now, basically just Windows 8, Windows 8 Pro (for super users) and Windows RT (for Tablets).

However, once it's installed, it's initially confusing but I have been using it every day all day since it was released and have got myself productive again. Here's what I ran into and how I realized that there's less reason to freak out than I originally thought.

The Windows 8 Login/Lock Screen

There's a bunch of folks who have said that you have to "swipe up" or "slide away" from the Login or Lock screen to log in. Some websites have even suggested you disable the lock screen. That is stupid and wrong *cough* NBCNews *cough* and you shouldn't turn off the lock screen. Just press any key. Or just start typing. Or click the mouse. Or ANYTHING. You don't have to "swipe up" to log in just click or press anything.

Shut down or Sleep a Windows 8 Machine

Shutdown your Windows 8 MachineIt's initially confusing as to how you shut down your machine. For laptops - at least my Lenovo and MacBook - you really never need to shut it down. I just close the lid.

If I really want to force a shut down, log out, or force sleep I just press Ctrl-Alt-Delete and press the Power button in the lower right corner. To lock the machine, just Windows Key+L.

You can also hit Win+I and press power. There's actually several ways to shut it down. You can even ALT-F4 from the Desktop if you like.

ALT-F4 from the Desktop shuts down Windows

Here's another crazy idea for shutting down your PC or Laptop - Press the Power Button.

Run Power User or Administrative Tools - WinKey+X is EVERYTHING

For the first week the most frustrating thing about Windows 8 was getting to anything that was power-user-like. I was literally pissed at my computer because I was so used to clicking the Start Menu, then right clicking on My Computer in order to do things like Device Manager, etc. For things like the Event Viewer or Admin Command Prompts I was pressing Start, then typing "Event" and hitting enter. It was fine but it wasn't as fast as it should be.

Then I discovered the Number 1 most powerful Windows 8 shortcut for the Power User. It's Windows Key+X.

image

This hotkey used to be the "Mobility Center" and was really only ever used when I wanted to put my machine into Presentation Mode. Now it's a Power User's dream.

Note that everything is pre-underlined. Want an Admin Command prompt? Win+X, A. Event Viewer? Win+X, V. You get the idea.

You can also get to the Win+X menu by moving the mouse to the lower left-corner and right-clicking!

Windows Key Hotkeys are your life

All the usual stuff works and you should know this already. If you don't, picking up a few of these will save you seconds many times a day and that adds up. Force yourself not to use the mouse.

  • Win+E - Explorer
  • Win+R - Run
  • Win+Break - System Info
  • Win+D - Desktop (I use this constantly if I get trapped outside the Desktop world)
  • Win+Plus or Win+Minus (no shift) - Magnifier/Zoom In and Out
  • Win+F - Find Files
  • Win+Print Screen – Put a PNG in the Pictures folder
  • Alt-Tab - Switch between Apps
  • Win-Tab - Switch between Full Screen Apps

Explorer Win-Keys for pinned apps

I'm consistently shocked at how many Windows "experts" don't use the Windows Key + "a number" hotkeys. Just press Windows+1 to launch the first thing in your taskbar, all the way up to Windows+0 for the 10th item.

No this is not how I arrange my taskbar.

There are a few new ones as well worth learning...

New Windows 8 "Win-Key" Hotkeys to move faster

You've likely already figured out that to launch something from the keyboard you press Windows, type part of the name of the app, then press Enter. If you press Ctrl-Shift-Enter it will run that same app as Admin.

Turns out that the keyboard works for most everything, even menus you wouldn't suspect it does. When you get a menu up you can always use the keyboard or hotkeys to move around it.

If you learn just three hotkeys, learn:

  • Win+W - Search Control Panel and Settings stuff
  • Win+F - Search Files
  • Esc - Yes, escape. No joke. If you hit the Windows Key, you can hit Escape to go back.

Once you have those, add these:

  • Win+C - Charms (right side menu) then arrows to move and enter to launch.
  • Win+K - Devices
  • Win+I - Settings in any app plus brightness, network and other useful system features
  • Win+Arrows - Snap desktop apps to the sides
  • Win+(period) - Alternate sides to "snap" Metro Apps. Add shift to reverse it.
  • Win-X - Admin Stuff. I'm mentioning it twice because it's THAT useful.
  • Win+PageUp or Win+PageDn - Move full screen apps to other monitors. Super useful for News apps and Readers. The Start Screen can be moved as well.

Better File Operation (File Copy/Move) Dialogs

The file copy dialogs are reason enough to upgrade. No joke, especially when you expand them for details. You get sparklines, throughput, time remaining that makes sense, as well as stop and pause.

Windows 8 has an epic stacked File Operation Dialog

Awesome Task Manager

The Task Manager is epic. I keep it open a LOT. Back in the day I used to have a monitor dedicated to it. The whole point of the Task Manager is to answer those "what the hell is going on" questions. In Windows 7 and before all you could basically do was sort by CPU descending and complain. Now I can see the difference between Apps, Background Stuff, Services, etc.

Right now, for example, the disk is doing something. Here's the Task Man...

Apps in Task Manager

I'll sort by Disk, and I see it's Indexing a bunch of new files I copied.

Processes in Task Manager

I can see what apps are slowing down my startup, and disable them:

Startup in Task Manager

I can finally see services and stop them:

Services in Task Manager

Install Hyper-V

For the developer or power user this one feature is reason enough to upgrade to Windows 8. For the longest time I had a laptop that ran only Windows Server 2008 because I wanted to have a really good Virtual Machine solution with a HyperVisor. On my desktop I used Virtual Box. Now Windows 8 Pro (a client OS!) has Hyper-V which is huge.

Press WinKey+W, type "Add Feature" and select Hyper-V.

image

If you want, you can check your Windows 7 machine now and see if your system is 64-bit and supports SLAT and the newer CPU features you'll need. Download CoreInfo and from an Admin Command Prompt run "coreinfo -v." You want to see a star where it says "Supports SLAT." Either way, you'll know as Hyper-V won't let you install if you don't meet the requirements.

C:\WINDOWS\system32>coreinfo -v

Coreinfo v3.05 - Dump information on system CPU and memory topology
Copyright (C) 2008-2012 Mark Russinovich
Sysinternals - www.sysinternals.com

Intel(R) Core(TM) i7 CPU X 980 @ 3.33GHz
Intel64 Family 6 Model 44 Stepping 2, GenuineIntel
HYPERVISOR - Hypervisor is present
VMX * Supports Intel hardware-assisted virtualization
EPT * Supports Intel extended page tables (SLAT)

Having a great Virtual Machine solution on the client has been great for me as I do a lot of screencasts and install a lot of beta stuff. I've got Ubuntu (which installs and works immediately because of the Hyper-V drivers are in Linux out of the box) running along side a few Windows 7 VMs, a Windows Server 2008 and a Windows XP VM.

Other nice features have been the ability to mount a VHD or ISO out of the box.

Show More Tiles

I have a 30" monitor in the middle of two 24" monitors. When I first looked at the Windows 8 Start Screen I thought "this is not using all my pixels." Then I found out that you can tell the Start Screen to use show more Tiles on high resolution (large) monitors.

Press Win+I (or go to Settings) and click Tiles:

Show More Tiles

Now I got those pixels working for me and the Start Menu felt nicer on a giant monitor.

I've filled a 30

Also, take a moment and "Ctrl+Scroll" (zoom out) from the Start Screen. From here you can right click on groups of icons and name them. I've cropped and zoomed in here...I can basically have sections, zoom out to see headings then click to zoom in. I can also drag these groups around which makes large moves easier.

Lots of Icons, Zoomed out and Named in Groups

Multi-Monitor Taskbars

I've been a multi-monitor guy for years and blogged about taskbar utilities that deal with Windows 7's lack of a good multiple monitor solution. Sadly for Ultramon, I haven't needed his excellent utility as it's handled the way I like it in Windows 8.

Multiple Monitor Taskbars in Taskbar Properties

See there where it says "Close all windows on this display?" Windows 8 it full of little improvements like that to irritations from previous OS versions.

Close all windows on THIS display

The Explorer Ribbon

On my large monitor, I like the Ribbon. Best part is - again, I'm a keyboard person - if I hit Alt, it lights up with the letters I need for hotkeys. Here's before...

Windows 8 Ribbon in Explorer

And after...

Explorer Bar Hotkeys

Don't like it? Hide it and move on. Look mom, no gnashing of teeth.

Hidden Explorer Bar

Conclusion

Maybe I'm too relaxed but after a few days and some hotkeys I've found Windows 8 to be Windows 7+1. Works fine, no crashes, lots of improvements. I spend most of my desktop time in Windows apps, all of which work. I keep News apps or Video apps in full screen on other monitors and I do move the Start Screen around but generally the whole thing has been a non-issue.


Sponsored Ad: DevExpress Webinar: ROI for 3rd party tools. Is it more cost effective to build or purchase developer tools? In this webinar Jeffrey Hammond, Forrester Research, will walk you through an ROI calculation model and help you consider how you might evaluate your future tools investments. Register Today!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Your words are wasted

August 19, '12 Comments [77] Posted in Blogging
Sponsored By

Photo by KrisOlin used under CC - http://www.flickr.com/photos/krisolin/6861197374It needs to be said again, perhaps this time more strongly. Your Blog is The Engine of Community. Dammit.

Blog More

You are not blogging enough. You are pouring your words into increasingly closed and often walled gardens. You are giving control - and sometimes ownership - of your content to social media companies that will SURELY fail. These companies are profoundly overvalued, don't care about permalinks, don't make your content portable, and have terms of service that are so complex and obtuse that there are entire websites dedicate to explaining them.

I've presented at a number of "town hall" style meetings and often presented (for YEARS now) talks on "Social Media for Developers" where I've said "Every developer should have a blog." Put yourself out there and make it findable. And still you tweet giving all your life's precious remaining keystrokes to a company and a service that doesn't love or care about you - to a service that can't even find a tweet you wrote a month ago.

Where are people writing?

My friend Jon Udell is asking "Where have all the bloggers gone?" and watched both he and his wife's "Blog's Heartbeat" reduce to an almost comatose level. Tim Bray notices this pattern as well.

Now more companies and consortiums are popping up claiming to be "reimagining writing" or "rethinking publishing" or take the concept of a simple "draft post" and, according to Svbtle "[allow] ideas to start abstractly, to ruminate for a while, and then, as I work on them, to become more and more concrete until they’re ready to be published as articles." So, reinventing drafts? Regardless, Svbtle and it's new design has since attracted a who's who of Silicon Valley thinkers and is now on its way to becoming the digirati's Economist, except with bylines.

Here's the thing though, it's still RSS. It's just a blog.

Own Your Words

I've been blogging here for over 10 years. On my domain, running my software pushing out HTML when you visit the site on any device and RSS or ATOM when you look at it with Google Reader (which 97% of you do.) I control this domain, this software and this content. The feed is full content and the space is mine. Tim nails it so I'll make this super clear. If you decide to use a service where you don't control your content, you're renting.

Own your space on the Web, and pay for it. Extra effort, but otherwise you’re a sharecropper. - Tim Bray

In a time where we are all gnashing our teeth about Twitter's API changes that may lock out many 3rd party developers, Google Plus's lack of content portability or lack of respect for the permalink, as well as the rise of country club social networks pay-for social networks like http://app.net we find ourselves asking questions like:

  • Why doesn't someone make a free or cheap social network for the people?
  • Why can't I control my content?
  • Why can't I export everything I've written?
  • Who owns what I type?
  • Why isn't there an open API for my content?
  • Why can't I search posts over a month old?
  • Why can't I have this or that username?
  • Why am I not verified?

All these questions are asked about social networks we don't control and of companies who don't have our best interests at heart. We are asking these questions in 2012? Read those bullets again. These were solved problems in 1999.

You want control? Buy a domain and blog there.


Sponsored Ad: DevExpress Webinar: ROI for 3rd party tools. Is it more cost effective to build or purchase developer tools? In this webinar Jeffrey Hammond, Forrester Research, will walk you through an ROI calculation model and help you consider how you might evaluate your future tools investments. Register Today!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Installing HTTPIE (HTTP for Humans) on Windows - Great for ASP.NET Web API and RESTful JSON services

August 17, '12 Comments [38] Posted in ASP.NET | Open Source | Web Services
Sponsored By

Recently in on a post on the RESTful ASP.NET Web API framework I used curl to post JSON to an HTTP endpoint:

curl -X POST -H "Content-Type: application/json" -d "{ Name: 'Scott Guthrie', Age: 67}"

Curl is lovely and should be in your c:\utils folder and more importantly in your PATH. I have a UTILS folder in my Dropbox and in the PATH on all my machines. Whenever I find a useful no-install utility I put it in there.

Curl is great but it's still confusing enough to me that I don't use it enough. It's slightly obscure command-line switches are keeping me from using it on a regular basis.

For HTTP work there is a better utility called HTTPie at http://httpie.org. (It has nothing to do with IE (Internet Explorer)). For Mac and Linux folks who use Python all the time, it's easy to install, you just

pip install -U httpie

For Windows folks who don't use Python it's a little harder to install, but it's worth it and I recommend you take a moment and set it up. You'll wonder how you lived without it.

Installation of HTTPIE

First, go download Python. I got the x86 version of Python 3.2.3 cause it was the latest and I didn't think I needed the x64 one.

I then added c:\python32 and c:\python32\scripts to my path. I do this by hitting WinKey+Break, then Advanced, then Environment.

Add Python and Python/Scripts to your PATH

Second, download CURL. Yes, I realize the irony, but it's still a VERY useful tool. I downloaded the 7.27 binary SSL Win32 version, unblocked it, unzipped it and put it in C:\UTILS so it was automatically in my PATH.

Third, run this from an Administrator command prompt. Note again that it needs both curl.exe and python.exe in the PATH to run as it is. This should run without incident.

curl http://python-distribute.org/distribute_setup.py | python

Then run

curl -k https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python

This should end with "successfully installed pip."

Pip is a Python package manager.

Finally, run

pip install -U https://github.com/jkbr/httpie/tarball/master

I'm recommending you install the development edge build of HTTPie rather than just "pip install httpie" as the developer is actively fixing Windows issues and just recently helped me with one.

So, to sum up what you need to run, in four lines, assuming curl.exe, python.exe and python scripts are all in your PATH.

curl http://python-distribute.org/distribute_setup.py | python
curl -k https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python
curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python
pip install -U https://github.com/jkbr/httpie/tarball/master

Running HTTPie

You'll know it works if you can run "http" from the command line and get this output:

C:\Users\scottha\Desktop> http
usage: http-script.py [--help] [--version] [--json | --form] [--output FILE]
[--pretty | --colors | --format | --ugly]
[--print OUTPUT_OPTIONS | --verbose | --headers | --body]
[--style STYLE] [--stream] [--check-status]
[--auth USER:PASS] [--auth-type {basic,digest}]
[--verify VERIFY] [--proxy PROXY] [--allow-redirects]
[--timeout SECONDS] [--traceback] [--debug]
[METHOD] URL [ITEM [ITEM ...]]
http-script.py: error: too few arguments

Here's where the fun happens. The syntax is VERY intuitive. Here I post some JSON to an endpoint that will echo it back.

C:\> http POST http://localhost:50231/api/Contact name=scott age:=100
HTTP/1.1 200 OK
Content-Length: 26
Content-Type: application/json; charset=utf-8
Date: Fri, 17 Aug 2012 21:59:51 GMT
Server: Microsoft-HTTPAPI/2.0

{
"age": 100,
"name": "scott"
}

It's just like using HTTP itself, except from the command line. The best part is that it will take name=value for strings and name:=value for non-strings and turn it into JSON!

HTTPie supports any HTTP Verb, FORM data, raw JSON, and lots of other features. Here's another example:

C:\>http PUT api.example.com/person/1 name=John age:=29 married:=false hobbies:='["http", "pies"]'
PUT /person/1 HTTP/1.1
Accept: application/json
Content-Type: application/json; charset=utf-8
Host: api.example.com
User-Agent: HTTPie/0.2.7dev

{
"age": 29,
"hobbies": [
"http",
"pies"
],
"married": false,
"name": "John"
}

There's lots more examples here https://github.com/jkbr/httpie/ and I encourage you to check it out. I'll leave you with a lovely PowerShell screenshot showing that HTTPie also does syntax highlighting at the command line!

HTTPie is HTTP for Humans and Syntax Highlights as well

Awesome. Expect to see this tool in all my Web API and JSON demos. Go get it and star it at GitHub.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.