Scott Hanselman

Tiny Happy Features #3 - Publishing Improvements, chained Config Transforms and Deploying ASP.NET Apps from the Command Line

August 12, '12 Comments [39] Posted in ASP.NET | ASP.NET MVC | Tiny Happy Features
Sponsored By

(UPDATE: See other Tiny Happy Features)

Publish Profiles are stored with the projectAt some point soon lots of people are going to start writing these epic blog posts about Visual Studio 2012. They will include LOTS of screenshots (some good and some bad), some small code samples and minimal context. I can't speak for other teams; I can only talk about what we worked on. The <AngleBrackets/> folks in Azure Platform and Tools (ASP.NET, IIS, WCF, EF, Azure much and more) have been putting a lot of work into what I sometimes call "Death by a Thousand Tiny Cuts." It's the little irritants that are as frustrating (or more so) as the big missing features.

Rather than a giant super post (although I'll do that at some point) I thought I'd showcase some Tiny Happy Features that the team worked on just because it made life better. Some are large some are small, but all are tiny happy features.

Publishing and Deployment Improvements

Visual Studio 2012 has a number of subtle but significant improvements to publishing. Of course you likely know you can push code to Azure or AppHarbor using Git. You can publish your web app with Web Deploy which I demonstrated at Mix in my talk Web Deployment Made Awesome: If You're Using XCopy, You're Doing It Wrong. You can see a quick closed-captioned video I did of Web Deployment to Azure in just 4 minutes over here.

Visual Studio added web.config transforms a while back so you can have a Web.config along with a Web.debug.config with the changes you want for debug time, and web.release.config for release time. You can add the free SlowCheetah add-on and get transform support for all your config files, not just web.config.

However, things fell down because Web Deploy and Visual Studio didn't have a way to easily represent Dev, Testing, Staging, Production, Whatever. You could have build configurations but they didn't relate to deployments, which doesn't reflect a developer's reality.

Publishing with Environment-specific Configurations

Publish Profiles are either created manually, or now in VS2012 downloaded as .publishsettings from your host and imported into Visual Studio. In Visual Studio 2012 publish profiles are stored along with your code in the Properties folder so they can be checked in and used by others.

Visual Studio 2012 adds deployment config transforms

You can rename a profile whatever you like by changing the name. Here I've named my publish profile "Production."  There's the coolest part.

PublishProfiles live in the Properties folder

I can make a Web.config file with the same name as my Publish Profile and that transform will be run after the build transform.

Even better you can right click on a Transform now and select Preview Transform and see not only the results, but a Diff of the results.

Transformed Web.config ( transforms applied: Web.Release.config, Web.Production.config)

See right there, and in the large image above? It says "Transformed Web.config ( transforms applied: Web.Release.config, Web.Production.config)." Build transforms happen first, then Publish Transforms. Right now you need to create the file with the same name yourself but we'll be adding tooling for this.

This means I can do things in Web.debug.config like changing compilation options while Web.production.config is for changing connection strings, setting log levels, and adding specific Production settings.

Deploying from the Command Line

Deploying your web application from the command line has long been possible but it's been a pretty obscure and frustrating affair. Now that the Publish Profiles can live with the project and Web.config transforms can be chained in you can publish from the command line much easier.

msbuild MySolution.sln /p:DeployOnBuild=true;PublishProfile=Production;Password=poo

If you have a untrusted certificate on the deployment server you haven't added to your local certs you'll need to add AllowUntrustedCertificate=true as an acknowledgement.

I just make a Deploy.bat that looks like this with a %1 for the Profile Name.

msbuild MySolution.sln /p:DeployOnBuild=true;PublishProfile=%1;AllowUntrustedCertificate=true;Password=poo

Then I can just do

Deploy Production

or

Deploy Staging

I've found these outwardly small but impactful changes have made it a lot easier for me to deploy sites. Deployment shouldn't be hard. I stand by my original statement: If you are using XCopy (or Windows Explorer or FileZilla) to deploy your website, you're doing it wrong.

If you are using Web Sites rather than Web Products, head over to the Web Team blog (and subscribe, too) and add your voice to the comments around our teams' plans regarding Website projects and Web Deployment Projects.

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

Tiny Happy Features #2 - ASP.NET Web API in Visual Studio 2012

August 10, '12 Comments [15] Posted in ASP.NET | ASP.NET Web API | Javascript | Open Source | Tiny Happy Features | VS2012
Sponsored By

REST, POX, and WCF compared to RESTtafarians, a guy with a bag on his head and Darth Vader

(UPDATE: See other Tiny Happy Features)

At some point soon lots of people are going to start writing these epic blog posts about Visual Studio 2012. They will include LOTS of screenshots (some good and some bad), some small code samples and minimal context. I can't speak for other teams; I can only talk about what we worked on. The <AngleBrackets/> folks in Azure Platform and Tools (ASP.NET, IIS, WCF, EF, Azure much and more) have been putting a lot of work into what I sometimes call "Death by a Thousand Tiny Cuts." It's the little irritants that are as frustrating (or more so) as the big missing features.

Rather than a giant super post (although I'll do that at some point) I thought I'd showcase some Tiny Happy Features that the team worked on just because it made life better. Some are large some are small, but all are tiny happy features.

There's Enterprise Web Services that use SOAP and WS-*.* and they are great for many transactional or complex scenarios. Then there are lighter weight RESTful web services or "Web APIs" that use JSON, XML and respect all of the goodness and stability that is the HTTP specification.

WCF is alive and well and ASP.NET is alive and well and there are reasons to use each technology. As this article says very well, "The world of SOAP and the world of HTTP services are very different. SOAP allows us to place all the knowledge required by our service in the message itself" vs. "you can use [Web APIs] to create HTTP services that only use the standard HTTP concepts (URIs and verbs), and to to create services that use more advanced HTTP features – request/response headers, hypermedia concepts etc."

Kelly Sommers wrote what I consider the best explanation of REST out there in "Clarifying REST." Whether you want to write RESTful resource-focused HTTP services or just POX or POJ (Plain Old XML or Plain Old JSON) services, you can do both with ASP.NET Web API. It's all part of the ASP.NET open source web stack.

Rick Strahl says that ASP.NET Web API is different than other frameworks because "it was built from the ground up around the HTTP protocol and its messaging semantics. Unlike WCF REST or ASP.NET AJAX with ASMX, it’s a brand new platform rather than bolted on technology that is supposed to work in the context of an existing framework. The strength of the new ASP.NET Web API is that it combines the best features of the platforms that came before it, to provide a comprehensive and very usable HTTP platform."

I encourage you to check out Rick's excellent analysis. Here's the features of ASP.NET Web API Rick likes:

  • Strong Support for URL Routing to produce clean URLs using familiar MVC style routing semantics
  • Content Negotiation based on Accept headers for request and response serialization
  • Support for a host of supported output formats including JSON, XML, ATOM
  • Strong default support for REST semantics but they are optional
  • Easily extensible Formatter support to add new input/output types
  • Deep support for more advanced HTTP features via HttpResponseMessage and HttpRequestMessage
    classes and strongly typed Enums to describe many HTTP operations
  • Convention based design that drives you into doing the right thing for HTTP Services
  • Very extensible, based on MVC like extensibility model of Formatters and Filters
  • Self-hostable in non-Web applications 
  • Testable using testing concepts similar to MVC

ASP.NET Web API

There's some lovely new samples at this Git Repository. Just "git clone https://git01.codeplex.com/aspnet" or download the zip. You can also familiarize yourself with ASP.NET and the Web API at the new http://www.asp.net/webapi site.

By the way, I'll be publishing a bunch (13!) of new videos showcasing Web API plus a lot of other Tiny Happy Features next week on the 15th. Each video will only be 5 minutes long and will be a great way to get up to speed on all the new tech over lunch.

To use the samples, follow the instructions on Henrik's blog post announcing them.

Here's one nice little sample that will perhaps cause you to rethink what you can accomplish with ASP.NET web technologies. It's a console application that hosts ASP.NET Web API. To be clear, there's no IIS involved.

In the setup instructions we have to register a port and user with HTTP.sys so the Operating System knows it's OK for send our little self-hosted app HTTP traffic. If you're familiar with WCF you may have done this before.

Here's the server. It's a Console App, minus error handling for clarity.

class Program
{
static readonly Uri _baseAddress = new Uri("http://localhost:50231/");

static void Main(string[] args)
{
// Set up server configuration
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress);

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

// Create server
var server = new HttpSelfHostServer(config);

// Start listening
server.OpenAsync().Wait();
Console.WriteLine("Listening on " + _baseAddress + " Hit ENTER to exit...");
Console.ReadLine();
server.CloseAsync().Wait();
}
}

That code sets up a route, starts the self-hosting process, and waits. Here's a controller at http://localhost:50231/Contact that will ECHO whatever contact you HTTP POST to it as content-type JSON. Note that Contact is a C# type as a parameter to Post().

public class ContactController : ApiController
{
public Contact Post(Contact contact)
{
return contact;
}
}

If I want, I can do a POST from another command line using curl and send some JSON into the server.

POSTing JSON from CURL to ASP.NET Web API

Here's the actual command line. The JSON is echo'ed back.

C:\>curl -X POST -H "Content-Type: application/json" -d "{ Name: 'Scott Guthrie', Age: 67}" http://localhost:50231/api/Contact

That's from the command line but I can also use System.Net.Http.HttpClient to make a call from .NET if I like:

HttpClient client = new HttpClient();

Contact contact = new Contact {
Name = "Henrik",
Age = 100
};

// Post contact
Uri address = new Uri(_baseAddress, "/api/contact");
HttpResponseMessage response = await client.PostAsJsonAsync(address.ToString(), contact);

// Check that response was successful or throw exception
response.EnsureSuccessStatusCode();

// Read result as Contact
Contact result = await response.Content.ReadAsAsync<Contact>();

Console.WriteLine("Result: Name: {0} Age: {1}", result.Name, result.Age);

See how the C# Contact object moves back and forth between the JSON world and C# world easily? That's the JSON.NET open source library making that happen.

JSON and JavaScript is really dynamic, though, and often it's a hassle to try to "deserialize" really dynamic JSON objects into strongly-typed .NET structures. JSON.NET and ASP.NET Web API's model binding offer a happy medium - a middle ground - called JToken.

public class ContactController : ApiController
{
public JToken Post(JToken contact)
{
return contact;
}
}

Check out the watch window as the JSON comes in:

Using JToken to catch a JSON payload

Using JToken gives me a dynamic container but also a DOM-like navigation model. But if that's not dynamic enough for me, why can't my method's parameter just take a "dynamic."

C# is statically typed, sure, but that doesn't mean I can't statically type something dynamic. ;)

Again, note the watch window.

Using dynamic to catch JSON post payloads

See how JSON is moving around the system without any impedance mismatch. The power of C# isn't slowing down the flexibility of JavaScript and JSON.

It makes me happy when things work as they should.

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

Tiny Happy Features #1 - T4 Template Debugging in Visual Studio 2012

August 10, '12 Comments [67] Posted in Tiny Happy Features | VS2012
Sponsored By

(UPDATE: See other Tiny Happy Features)

At some point soon lots of people are going to start writing these epic blog posts about Visual Studio 2012. They will include LOTS of screenshots (some good and some bad), some small code samples and minimal context. I can't speak for other teams; I can only talk about what we worked on. The <AngleBrackets/> folks in Azure Platform and Tools (ASP.NET, IIS, WCF, EF, Azure much and more) have been putting a lot of work into what I sometimes call "Death by a Thousand Tiny Cuts." It's the little irritants that are as frustrating (or more so) as the big missing features.

Rather than a giant super post (although I'll do that at some point, I thought I'd showcase some Tiny Happy Features* that I or another passionate member of the team worked on just because it made life better. Some of these features might not be obvious or easily noticed. Actually it'll be better that you notice the absence of a tiny cut than the inclusion of a new shiny drag and drop toy. It's all part of a larger goal to make the experience of making Web Applications in Visual Studio enjoyable.

T4 Template Debugging

I've long said that T4 is one of the best kept "secret" features of Visual Studio. T4 (the Text Template Transformation Toolkit) doesn't have a whole pile of people working on it, but developers like Gareth Jones really care about it and we really like it in the Web team. Lots of our projects use and have used T4 to generate code. In Visual Studio 2012 Gareth worked with Tim Malone so Tim could make a T4 debugger! Be sure to check out the T4 Team Blog.

Sure, T4 fans have always wanted built-in T4 Syntax Highlighting, but in this case, there were already a great T4 SyntaxHighlighting solution or three good options and there was no FREE debugger. Until now.

T4 in Visual Studio 2012 has Debugging!

You can now right-click on a T4 templates and Debug T4 template. I've got a breakpoint there on a line within the T4. My own T4 is syntax highlighted with the Tangible Editor.

There's the Debug T4 Template menu

When I start debugging I can set breakpoints and watches and step through just like any other language.

Debugging a T4 template

Notice here in the Immediate Window I'm looking at this.GenerationEnvironment. I can see the generation AS it happens in this variable.

Viewing T4 output

If you like T4 and you want them to know, leave a comment below and I'll use your comments to bludgeon convince management that we should continue to invest.

* Ya, some features aren't Tiny, but some are refinements and I like saying Tiny Happy Features. Sue me.

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
Page 1 of 1 in the Tiny Happy Features category

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