Dan Maharry

DDD Southwest Session Notes 3 : Defensive Programming 101

by

The third session of my day at DDD Southwest was a talk by Niall Merriganentitled Defensive Programming 101. Or, as it turned out, “Top 10 Things You Shouldn’t Forget To Do To Start Securing Your Website”. This was probably my favourite of the sessions I attended at DDD Southwest. Niall’s a funny bloke with useful things to teach so if you get a chance to see him talk, do.

Further information and resources can be found on Niall’s site here at http://www.certsandprogs.com/2012/05/dddsw-roundup-and-resources.html. You can contact him on Twitter at @nmerrigan

Writing secure code is hard and takes time. Sales people do not care and we trust each other  that our code is secure. Not that many people try to screw up a site they are visiting. We write for general users.

The Top 10 "Screwables"

10. Restrict your HTTP Headers. It can tell those who care too much, such as the webserver being used, .net version etc. Don’t forget also to restrict easy access to sensitive files. Kill elmah.axd, trace.axd. Search for the phrase googlehacks and you’ll find the number of ways google can help the hacker attack your site simply because you’ve allowed them to index your *.axd files, *.pst files etc.

9. Passwords. Don't use the same password for every single site. Cross-pollination hurts. Don’t save passwords in plain text connection strings. Encrypt them, change them regularly and don’t ell them to others. NB You can't encrypt your password in a connection string when using the entity framework.

8. Patching. Try and follow the server patch bulletins sent out by Microsoft and make sure you test your web applications with new patches attached as they can break.

7. Validation. Don't rely only on client-side scripting for validation. Turn off javascript in your browser and make sure server-side validation is working. Prefer whitelists to blacklists. Validate to RFC rules. Use a central validation source – i.e. a single place to update validation rules.

Search for e.g. RFC email - shoud point to ISO standard validation routine

6. Email & Custom Errors. Email presents too much information to users, and not enough to developers. Error messages should only show users what they expect to see. No stacktraces etc. Very ditto for emails. Turn CustomErrors ON IN PRODUCTION with pages handling specific error codes – 404, 500 etc. Use web config transforms to kill it or set it to localonly and set up custom errors. Handle your errors correctly.

5. Database and AppPool Permissions. Don't use sa in your connection string. Don’t create a user and set it to dbo. Use two connection strings, one for reading, one for writing. Never run AppPools as *Admin user accounts. Always use the minimum permissions. Don't give access to SQL tables if sprocs and views are all that’s required. Perhaps give user only execute permissions if you only use sprocs. (Yes this should include insert perms. Oh, and don’t use dynamic sql in sprocs)

4. Directory traversal. How do I send a file to client that opens a save as dialog? Ans: Whatever you do, don’t do something like this: download.aspx?file.txt. Because download.aspx?..\web.config will work. IIS isn't handling and therefore automatically blocking the request at this point, your handler is. You could probably download the whole source code in dll files and decompile it. If you used the asp.net website template, you can get all the cs files as well. In short, don't use a file name for downloads. Use a GUID or include a hash for the file to check you're downloading the file you think it is.

Find link on blog to WAM_USER WAM_PASSWORD metabase vulnerability on Niall's site,

3. Injection attacks. Addition of scripts to your site against your will. Don't set enablePageValidation to false. Very silly. Don't use cookieless sessions. Only make cookie on server-side readonly.

2. SQL Injection. nuff said. Don't allow naked SQL in your code.

1. Users will never do what you think they are going to do.

Three Changes of Behaviour in AJAX Control Toolkit v40412

by

The interesting thing about writing a book such as Programming ASP.NET 3.5 is that as new readers come to it over time, they find that libraries used within the book code break the examples. Peter Ormshaw got in touch today to point out that the Ajax Control Toolkit has changed slightly since build 20229 which the book was built against.

In particular, he’s come across three differences between the book and working with v3.5.40412 which is the latest version at the moment.

Installing The Control Toolkit

Appendix A, which covers installing the control toolkit is now obsolete. Best practice now would be to download the binaries for the toolkit and follow the installation instructions at http://www.asp.net/ajaxlibrary/act.ashx.

You Must Use The Toolkit Script Manager

Any AJAX web form you’ve created in Visual Studio automatically contains the standard ASP.NET ScriptManager control. If you want to use any toolkit controls on that page, you must replace this with the toolkit’s own ScriptManager control. So then, you change this

<asp:ScriptManager ID="ScriptManager1" runat="server" />

to this

<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>

Toolkit now uses asp as its TagPrefix: BulletedList Users Beware!

The final thing to note is that v40412 now has the Toolkit controls use “asp” as the default TagPrefix for its controls rather than cc1. This in itself is not a problem and makes sense as Microsoft have now more formally adopted the Toolkit with all its jQuery finery and finessing on the client side.

However, the toolkit also includes a control called BulletedList which, with the tagprefix change now means that Visual Studio will no longer compile pages referencing the toolkit and containing this control until you alter the TagPrefix used by the toolkit on that page. Typically, that means changing the “asp” in TagPrefix=”asp” in this line

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

to something other than asp. Don Kiely has a full description and reasoning behind this issue at devproconnections.com.

CSS3, Round Corners, Webforms and IE

by

This article looks at the best methods I've found and lessons I've learned trying to style various HTML elements consistently with rounded corners. As with all articles of this type, your mileage may vary.

I don't know about you, but as an ASP.NET Webforms developer one of the first things I look for when a designer sends me a new look for a site I'm working on is the presence of rounded corners. Switching between square and round corners in photoshop or illustrator is done with the click of a button. In HTML, there's a little more effort involved. How much depends on

  • What range of browsers are being targeted
  • Whether or not I need to inject additional HTML into the markup generated by my webform controls. Will I end creating a user control to keep generating the correct HTML for the technique?
  • How many additional images I'll need to create to get it working
  • Will I need to use some javascript (jQuery etc) in the technique and slow the total page load time further?

For example, let's assume we have three nesting block-level elements (a form, and 2 divs) and three buttons (an input element, a link as a button and a button elements) inside the inner div

  • The form and outer div will both have rounded corners of radius 25px and 20px respectively.
  • The inner div will have rounded corners top left and bottom right of 15px radius.
  • The three buttons should have rounded corners of 10px radius.
<%@ Page Language="C#" AutoEventWireup="true"  
CodeFile="css3.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">  
<title>Rounded Corners</title>
</head>
<body>
<form id="a" runat="server">
<div id="b">
<div id="c">
<p>This is an &lt;input&gt; button -  &lt;asp:button&gt;: 
<asp:Button runat="server" ID="testInputButton" 
CssClass="button" Text="Input Button" /></p>
<p>This is an &lt;a&gt; tag - &lt;asp:linkbutton&gt;: 
<asp:LinkButton runat="server" ID="testLinkButton" 
CssClass="button">Link Button</asp:LinkButton></p>
<p>This is a &lt;button&gt; tag: 
<button runat="server" id="testHtmlButton" 
class="button">Html Button</button></p>
</div>
</div>
</form>
</body>
</html>

Ideally of course, we should be starting to use CSS3. The border-radius property is custom-made for rounding the corners of any element. Adding a few rules like the ones below - not forgetting the -moz-border-radius and -webkit-border-radius equivalent properties as Firefox and Safari don't directly support border-radius itself yet - and we get pretty good results.

html
{
background-color: #004;
font-family: Calibri;
}
#a
{
width: 500px;
margin: 25px auto;
padding: 25px;
background-color: #888;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
}
#b
{
padding: 25px;
background-color: #00c;
border-radius: 20px;
-moz-border-radius: 20px;
-webkit-border-radius: 20px;
}
#c
{
background-color: #fff;
border-radius: 15px 0 15px 0;
-moz-border-radius: 15px 0 15px 0;
-webkit-border-radius: 15px 0 15px 0;
}
p
{
padding: 10px;
}
.button
{
background-color: #ccc;
padding: 10px;
border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
}
That bit of CSS renders the page correctly in Chrome 4 and 5, Safari 3 and Firefox 3.6.

CSS3 in Action

In Opera 10.51, <input> and <button> don't get rounded corners, and to give it credit, the current IE9 preview rounds everything save the Link Button as well, but it's IE8 and older which cause the problems, steadfastly refusing to do anything at all. There are many - and I do mean, many - CSS solutions to do away with IE's sharp corner fixation. Some involve lots of images, some use javascript and some both.

After trying pretty much all of them over the past few days, here are some thoughts.

  • No one of these techniques works satisfactorily on both block-level and button elements - out of the box anyway. And unless you feel confident working with some of the javascript-based techniques, that means you'll need to incorporate one technique for divs and the other for the buttons.
  • The <input> element is incredibly intransigent as far as styling goes in IE. The path of least resistance is to prefer using <button runat="server" onserverclick="handler"> to <asp:Button> wherever possible. The only exception to this is when you want to use a CommandName property on the button. In this case, you can use an <asp:LinkButton> instead.
  • The most backward-compatible techniques seem to be those that were originally created around IE7 time and have been built-upon since. Many of the button-rounding techniques are based on the sliding doors technique first documented here and here on A List Apart back in October 2003.
  • A lot of these techniques use several images. Some already combine all these images into one 'sprite' to improve performance, implying that it's more than possible to do the same with the others too. Automatically bundling CSS images into sprites looks to be one of the items being investigated for ASP.NET vNext. Perhaps we may be able to leverage these automation with these techniques in years to come.

And here are the two techniques that are now secured in my toolbox for the time being.

For Rounded DIVs - CurvyCorners

Curvy Corners (www.curvycorners.net) is a simple Javascript library, actively maintained and updated for new browser versions as they appear. It comes in a plain Javascript and jQuery variants, the latter as a reaction to the work done on the former.

Once you've downloaded it, you can round the corners of DIVs by either calling the javascript library explicitly, like this

<script type="text/JavaScript"> 
addEvent(window, 'load', initCorners);
function initCorners() {
var settings = {
tl: { radius: 25 },
tr: { radius: 25 },
bl: { radius: 25 },
br: { radius: 25 },
antiAlias: true
}
curvyCorners(settings, "#a");
}
</script> 

or, more excitingly, it also works as a frictionless library. Just make a reference to the curvycorners.js in your page and when the page loads, it will look for the CSS3 -webkit-border-radius properties on divs and use them as cues to do its thing. Crucially, it detects first whether or not your browser supports the CSS3 border-radius property (or its -moz or -webkit reflections) and works its magic only if the browser does not - i.e. if your browser is IE8-, Firefox 2-, Chrome 2-, or Opera 9-.

There are naturally, some limitations... And I quote

Because of the need for the mechanism to operate across all browsers, the CSS selector syntax supported is necessarily limited. This sets out what is supported:

  • a selector-list, where a selector-list is either a single selector or a single selector followed by a comma and an optional space, followed by a selector-list.
  • A single selector may be either a simple-selector or a simple-selector followed by a space followed by another simple-selector.
  • A simple-selector may be either an ID of the form #myID, or a tag-class-selector.
  • A tag-class-selector may be any one of:
    1. a tag name (e.g. div);
    2. a class name preceded by a dot (e.g. .myClass); or
    3. a tag name followed by a dot followed by a class name (e.g. div.myClass).

The following are examples of supported selectors:

  • .myclass
  • #mydiv frameset.myclass
  • form.rounded frameset,div.rounded

Warning: because CurvyCorners appends extra DIVs to the boxes you wish to round, the following selector will reliably not work:

#myBox div

This is because the style will be applied not just to the top-level DIVs within the element whose ID is myBox, but also to the DIVs inserted by CurvyCorners.

The following selectors may not work as expected:

  • div #mybox
  • div.rounded #mybox

Because an ID identifies a page element uniquely, qualifying it with an enclosing scope may cause the selector to fail (e.g. if #mybox is a top-level DIV, or if it is not located within a DIV of class rounded). However, CurvyCorners assumes that the element is to be referenced anyway and will apply the appropriate rounding styles.

But it is otherwise a pretty solid thing and, obviously, easy to disable - just remove the js file reference from the page.

For Rounded Buttons - Simply-Buttons

Simply-Buttons (http://www.p51labs.com/simply-buttons-v2/) is one of the aforementioned sliding doors technique, so fully CSS-based using two image for left and right sides of the button with enough hacks to produce the same result for LinkButtons and <button>s in all browsers back to IE6. In addition, should you need your buttons to react to a click or a hover event, it also proffers a small javascript routine which allows you to set additional images to reflect those events.

The demonstration code on the site also shows how to embed icons into your buttons for a better UI feel.

SimplyButtons

What's nice about Simply-Buttons is the flexibility it offers. As far as additional HTML goes, all you need add are two nested <span> elements to your button. This means the technique would be invalid with <input> buttons but as noted earlier, a combination of <asp:LinkButton> and <button runat="server"> tags as replacement work just as well.

<asp:LinkButton runat="server" ID="testLinkButton" 
CssClass="button">
<span><span>Link Button</span></span>
</asp:LinkButton>
<button runat="server" id="testHtmlButton" class="button">
<span><span>Html Button</span></span>
</button>

The download contains the stylesheet that makes the buttons so well. Once you've created the left and right images for your buttons, you need to adjust four well-identified CSS properties in the stylesheet to match the height of the button with the height of the image et voila.

Should you need the hover and click actions for the button, you create the rest of the images to reflect those states (find a good tutorial for creating round buttons here and rectangular ones here) and add the javascript file to your page.

<link rel="stylesheet" type="text/css" href="stylesheets/SimplyButtons.css" media="screen" />
<script type="text/javascript" src="SimplyButtons.js"></script>
<script type="text/javascript">
window.onload = function()
{
SimplyButtons.init();
};
</script>

The included stylesheet includes styles for both link buttons and html buttons, the iconized buttons shown above and for the hover and clicked pseudo-selectors, so you can cut it down a fair amount as well. All in all, it's a great tool to add to your basket.

Summary

In this article, I've outlined my two preferred methods for incorporating rounded corners into my ASP.NET web sites. Both are are almost frictionless as far as the original asp.net page goes with the only significant restriction being the inability to use <asp:Button> with simply-buttons. However, html\asp.net provides a complete alternative for this so it is a viable option. As ever, your mileage may vary, but it works for me :-)

Happy coding!

ASP.NET 4.0 Part 15, Data Enhancements

by

Welcome to part 15 of my tour through ASP.NET 4.0. In this episode, we're going to look at how webforms developers can make more use of both Dynamic Data 4.0 and Entity Framework 4.0 thanks to several new features baked into ASP.NET 4.0.

For those of you unfamiliar with these two products, Entity Framework is the 'enterprise-level' data modeller (O/RM) technology, aimed at larger applications where LINQ2SQL was aimed at small ones. Dynamic Data meanwhile is a rapid development tool used to create a basic scaffolding for a website based on the schema of the database that supports. Almost a CSS-like construct based on the type of data in a field rather than the type,class or id of an HTML element.

It's odd how both Dynamic Data (DynData) and the Entity Framework (EF)  were both released in .NET 3.5 SP1 almost as a tester to garner public reaction to Microsoft's efforts thus far with both projects. And it's fair to say that mistakes / omissions were made in those v1 releases which are now being corrected. EF was vilified in comparison to other, more mature OR/M frameworks for many reasons including

  • Short list of shortcomings that have been fixed in EF 4
  • Unit testing shortfalls. EF objects couldn't be generated as plain old CLR objects (POCOs) - they had to be classes derived from EntityObject which meant they would hit the db when tests were run against them.
  • EF didn't support many to many relationships

DynData, which sat on top of EF, suffered from both EF's shortcomings and some of its own including.

  • DynData 3.5 required you to start a new project and coudn't easily be integrated into a webforms or MVC application
  • If you used EF as the data model, DynData couldn't tell which field in a database table was the primary key and would model it as an editable field. You had to go into the model and annotate it separately.
  • Scaffolding templates for only basic field types and none for entities (types defined across several table joins)

Needless to say, both DynData 4.0 and EF 4.0 address these issues and many more. It's now fair to say that both technologies are well beyond where their first versions perceptibly fell short.

EnableDynamicData

One of the goals of ASP.NET 4.0 was to make DynData's scaffolding available to both Webforms and MVC. As noted earlier, DynData v1 was a project of its own that couldn't be easily retrofitted into an existing website, be it using Webforms or MVC. To remedy this, ASP.NET 4.0 now includes a new method called EnableDynamicData that you can use on any page in a website or web application.

Consider the scenario where you've a FormView or GridView allowing you to update, add to or delete records from a database. Typically, the controls auto-generate columns containing textboxes and maybe a checkbox. Users can add in invalid text, dates, values outside desired ranges etc. So you disable auto-generation and template the columns yourself with a calendar control for dates, say, and validation controls. And then you do the same thing for various other data-bound controls based on the same tables of data. Rather than setting all columns and rows yourself on each control, the EnableDynamicData method tells ASP.NET to generate those customized input and validation controls itself using the DynData scaffolding generated against the database and annotations you may give it as a (central) template.

Let's take an example.

  • Open VS2010 and create a new, empty web site.
  • If you’re using SQL Express, add an App_Data folder and add in the AdventureWorksLT database. You’ll find it for download on codeplex.
  • Add add an Entity Data Model to your site. Generate it from the tables in the newly added database.
  • Add a new page to your site and place on it an EntityDataSource and a GridView. The EntityDataSource should retrieve the EntitySet for the Products table. The GridView should use the EntityDataSource and both should have Update and Deletes enabled.

Your page code should look like this.

<%@ Page Language="C#" AutoEventWireup="true" 
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView runat="server" DataSourceID="entityDs" ID="gvwProducts">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
</Columns>
</asp:GridView>
<asp:EntityDataSource runat="server" ID="entityDs" 
ConnectionString="name=AdventureWorksLT2008_DataEntities" 
DefaultContainerName="AdventureWorksLT2008_DataEntities" 
EnableDelete="True" EnableFlattening="False" 
EnableUpdate="True" EntitySetName="Products"
EntityTypeFilter="Product"> </asp:EntityDataSource>   
</div>
</form>
</body>
</html>

If you run this page and try to update any of the currency-based fields for an item now listed in the grid (eg. StandardCost or ListPrice) with a non-currency value such as the string ‘abc’, you’ll get the following Yellow Screen Of Death message.

Error while setting property 'StandardCost': 'Cannot convert the value of parameter 'StandardCost' to the type 'System.Decimal'.'.

Of course, if we were to manually generate the columns in the GridView, we could add in validation to ensure that only valid currency values are sent to the database. But let’s not and enable the dynamic data framework on the GridView and see what happens. It’s a single line of code added to your page’s codebehind.

public partial class _Default : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
gvwProducts.EnableDynamicData(typeof(AdventureWorksLT_DataModel.Product));
}
}

If you run the page again and try to make the same page, you’ll see that some validation is performed pre-save and so clicking Update on the grid doesn’t produce the previously seen yellow screen of death.

Simple Validation

Admittedly, it’s not earth-shatteringly useful as the invalid value is simply highlighted by an asterisk to its side with the actual error message that StandardCost is a required value hidden in a tooltip, but by adding a ValidationSummary control to the page, things become much clearer. And we’re leveraging the Dynamic Data framework to generate validation for us, which we can always amp up by adding instructions centrally to the entity model such as an appropriate error message. For example,

namespace AdventureWorksLT_DataModel
{
[MetadataType(typeof(ProductMetadata))]
public partial class Product
{  }
public class ProductMetadata
{
[RegularExpression(@"^[0-9]{1,}\.[0-9]{2}$", 
ErrorMessage="Value should be greater than 0.00")]
public decimal StandardCost { get; set; }
}
}

Run the page again and you’ll see that a RegularExpressionValidator is now added to the RequiredFieldValidator already there.

There are loads of new features in Dynamic Data 4.0 that we can now leverage in WebForms and MVC including. 

  • Primary keys are now identified as primary keys and are not shown as an editable field
  • New field templates for URLs and email addresses.
  • Many-to-many relationships are now handled as a field template

Entity templates are another new feature in Dynamic Data 4.0. Whereas field templates deal with single field types, entity templates deal with objects as a whole, be they contained in a single table or spanned across many. Let's say we've a website in which the information for an auction item is restricted based on whether you're an admin, the seller or a buyer. An entity template means you can control what each role sees at the object level rather than reiterating it across several pages where that object is bound to controls.

Entity and field templates are available to both MVC and Webforms.

QueryExtender

If there's one problem with LINQ-based DataSource controls (for example, LinqDataSource and EntityDataSource) in .NET 3.5 it's that filtering on the data isn't supported declaratively by the data source. You have to take control of the query being sent to the database, add the filtering yourself and then passing the query back to the data source, usually by handling the OnQueryCreated event.

protected void dsProducts_QueryCreated(object sender, QueryCreatedEventArgs e)
{
if (!String.IsNullOrWhiteSpace(txtFilterName.Text))
{
e.Query = from p in e.Query.Cast<AdventureWorksLT_DataModel.Product>()
where p.Name.StartsWith(txtFilterName.Text.Trim())
select p;
}
}

In .NET 4.0 however, there is now a solution - the new QueryExtender control. Let's take an example and reuse the page we've got going. It already pulls down the contents of the Products table from the AdventureWorks table. Let's add a simple textbox which let's you set the start of the product's name to search for.

<body>
<form id="form1" runat="server">
<div>
Name starts with:
<asp:TextBox ID="txtFilterName" runat="server">Sport</asp:TextBox>
<asp:Button ID="btnGo" runat="server" Text="Go" />
<br />
<asp:GridView runat="server" DataSourceID="entityDs" ID="gvwProducts">
...

To include the filtering in the page, we add the QueryExtender to the page as follows.

<asp:QueryExtender runat="server" ID="qeFilter" TargetControlID="entityDs">
<asp:SearchExpression DataFields="Name" SearchType="StartsWith">
<asp:ControlParameter ControlID="txtFilterName" PropertyName="Text" />
</asp:SearchExpression>
</asp:QueryExtender>

Et voila. As the page loads, the QueryExtender informs the EntityDataSource and filters the data it presents us based on the contents of the text box.

Summary

There's a heck of a lot of new and interesting stuff going on in and around the world of data in .NET. Besides the advancements to the Dynamic Data and Entity Frameworks, there's also a new version of ADO Data Services (now known as WCF data services), the introduction of data storage in the cloud with SQL Azure Services and client-side data binding with AJAX Data Templates.

In our look at one small corner of it all, we saw how the EnableDynamicData method allows us to leverage the Dynamic Data Framework to act as a CSS-like form presentation and validation rules template for all our templated, data bound controls - a level of integration between Dynamic Data and Webforms/MVC previously unavailable.

We also saw how we can leverage the new QueryExtender control against LinqDataSource and EntityDataSource controls to act as dynamic filters for the data they retrieve.

Notes From Guathon Birmingham

by

On March 26, Scott Guthrie came and talked to about 200 developers in the centre of Birmingham. For six hours. Here's the abridged and annotated version of what he said about ASP.NET

Talk 1 : ASP.NET Development

The focus for ASP.NET 4.0 is to improve the end-to-end development scenarios, and to provide a productivity boost for all development within VS2010.

Improvements in VS2010

  • Intellisense in VS2010 now takes three hints for filtering items: the start of the class or member name, a substring of the name, and its 'initials' based on how it's spelled using pascal/camel casing. For example, type HttpCac, Cache or HCP and you'll get HttpCachePolicy in the intellisense list.
  • When you select a variable all instance of that variable are highlighted in the code editor window.
  • You can make box \ vertical selections in the code editor window by holding down the alt key
  • Snippet support has been added for most asp.net and http elements. Perhaps the most used of these will be "runat tab tab" to add ="server". However, there is no snippet support yet in the XAML editors.
  • When editing javascript, variable type inference informs what intellisense lists for that object. This feature works across multiple javascript files by adding comment at the top of the file referencing the other page
/// <reference path="ScriptFile1.js" />
  • Ctrl+, gives you a live search across your projects. It's essentially a Find In All Files dialog on amphetamines. Make a search and then double click on a search result to go straight to it. However there is no filter to show only class names, methods, properties etc.
  • Right click on method name : Call hierarchy window shows the call tree for a given method.
  • Right click on method name : View sequence diagram to produce visio style diagram showing call stack diagrams.
  • Generate dependency graph.
  • Pinning support for watched variables.
  • Intellitrace allows you to step backwards from a breakpoint.. Tools - Options - Intellitrace - Enable  (very cool). It will also do parallel execution analysis.
    • Intellitrace dumps can be saved to disk, sent over to another machine, load the dump and investigated further on that machine from exactly the same point.
    • Intellitrace is not in Pro - it's in premium or ultimate.
    • Intellitrace requires .NET 4.0 (need to check with ScottGu)
  • MSDN subscribers, websitespark, bizspark and dreamspark subscribers get VS2010 on the day. MSDN subscribers get a free year's upgrade to the next level SKU.
  • VS2010 has multiple monitor support.
  • VS2010 includes new test impact analysis tools to help developers figure out which tests they should be using to test the changes they are making. (MSDN docs here and Chanel 9 vid here)

When using Intellitrace, does edit and continue work after you step backwards?
The answer depends on the IntelliTrace collection level. If the user has set the collection level to “IntelliTrace events and call information”, then edit and continue is disabled altogether. If the collection level is set to “IntelliTrace events only”, edit & continue is supported.

Does intellitrace require us to use .NET 4.0 or will it work with earlier versions of .net?
IntelliTrace works on CLR 2.0 and above.

Can you create a sequence diagram in VS, save it and then use that diagram as a basis for code generation in another project?
We do not have code generation out of the box from sequence diagrams.  It certainly would be possible to write an extension that would do that though.

Multi-Targetting

  • .net4 includes a new CLR and version string.
  • VS2010 supports multi-targeting for .NET 2.0, 3.0, 3.5, and 4.0.
  • A new AppPool type is added to IIS for .net 4.0 websites when .net 4.0 is installed.
  • VS2010 will install side by side with VS2008. However VS2008 does not read VS2010 project files. Meanwhile VS2010 will auto-convert VS2008 project files to VS2010 so you'll need to maintain separate solution and project files for teams working with both versions of visual studio
  • When you set the target framework in a project properties screen in VS2010, you can select all four .net frameworks plus "Load Other Frameworks". Intellisense in VS2010 is informed by the shipped reference assemblies for the targeted framework rather than the version of .net that visual studio is built against. So when a new set of reference assemblies is released, you can 'Load Other Assemblies' to include those reference assemblies in your list of frameworks to target. (For example, reference assemblies already exist for Windows Phone & Silverlight. Theoretically you could also create reference assemblies for Mono.)

VS2010 installs safely side-by-side with vs2008 on the machine, but does vs2008 install safely side-by-side with vs2010 already on the machine?
Yes – this works fine.

Will the reference assemblies for Silverlight 4 be included with its installer or will they be a separate download? Ditto for RTM Win Phone 7.
Yes – they are included as part of the SL4 tools and Windows Phone 7 tools.  No separate download required.

Webforms 4.0

Does the ScriptManager have some sort of internal list of scripts already on the CDN so that when EnableCDN is set to true, it only seeks out jQuery or MS AJAX from the CDNs rather than a developer’s own JS files? Or is there some way to upload your own scripts to a corner of the CDN?
Yes – I believe it does.  It also, though, allows you to add other scripts to the list and/or use alternative CDNs if you want.

Deployment

  • Config transform files - config transform files only work with web app projects and not website projects.
  • One click Publish mechanism - to file system, via ftp, or using WebDeploy (which also sucks out the sql for the database schema and includes them in the deployment package).
  • There will be a web deployment package for vs2010 for upgrading projects from vs08 or vs05, but new projects should use the new WebDeploy set built into vs2010. WDP2010 may not be released on April 12 with vs2010 but probably by the end of April.
  • New Package Publish Web step in project properties dialogs. (This is where you can pull the SQL schema and stuff).
    • Build Deployment Package option which pulls in all files, ACLs and SQL into one zip.
    • Zip can be published to remote server and populated remotely.
    • Zip can be imported into IIS. (RHS Actions - Deploy - Import Application)
    • WebDeploy can be scripted with Powershell.
    • WebDeploy can be used with asp.net 3.5
    • By default it will copy only the files that have changed.
    • WebDeploy is designed to work with shared hosting.

Final bits

End of Session One - 12 noon

Outside, the weather has turned and mild, grey, overcast Birmingham has turned into mild, grey, wet Birmingham with additional chances of heavier downpours as we go into the afternoon. Campaigners from world vision are apparent by the people avoiding them and those running the taste test for Magnums equally apparent for the opposite reason.

The stay at home mums outside the Odeon are wondering why 200 geeky people keep running in and out of the building.

Pre-session two questions

How do you see the relationship between WPF and Silverlight evolve? 
WPF has definitely enhanced in 4.0 as part of enhancing VS2010 with WPF. Our goal now is to keep the same programming models in sync between the two. Silverlight and WPF are both governed by the same team so there is a fair amount of cross-pollination between the two.

Is the QueryExtender control built using the dynamic LINQ library shipped earlier?
Yes. 

Will there be a ReMIX 10?
Possibly not, but if so then in September. Certainly in the future.

Session Two - ASP.MET MVC 2

There was heavy focus on emphasizing the new features of MVC 2 in this session, which was mostly demonstration. However, it began with a brief introduction to MVC for those who had not come across it before.

  • Webforms and MVC are complementary templating engines for ASP.NET. Web sites / apps can be 100% one or the other or hybrid.
  • MVC allows complete and full control over what is rendered to the browser. It is also geared towards better unit testing.
  • MVC 2 is a separate download for VS2008 and ASP.NET 3.5. It is built-in to VS2010 for ASP.NET 4.0
  • Like webforms, file - new project gives empty and working web app projects.
  • MVC uses a convention-based structure works for MVC.
  • MVC has three main components - Actions, Controllers,Views and Models.

Can you overload an action method with multiple signatures? 
Yes, although it’s probably easier to use default parameter values for this and more common to overload action methods by HTTP verb

// get /events/details?eventid = 3 
// if not specified, eventid given default value of 0. 
public string Details(int eventid = 0)  
  • MVC promotes separation of concerns. Which makes things\code easier to replace and easier to test.
  • Controllers pass data from a Model to a View template which then puts that data into HTML as required.
  • Model = objects that represent the data and corresponding validation and domain logic.

Scott builds a new database. Uses the Entity Framework to create the Model for the database. (File –> New -> EF Data Model).

  • New <%: variable %> syntax. HTML encodes the string value in the variable. Good for protecting against injection attacks.
  • MVC 2 pages now inherit from ViewPage<dynamic> which allows for late binding against the data type. Replacing dynamic with an actual type name will early bind it and allow intellisense against the model object in VS2010.
  • AddView wizard generates a default template to work with against a table or entity in the database. Uses the new <%: syntax.

What if your view contains more than one model?
You create a ViewModel class which encapsulates all the data items to add in and then inherit your view from ViewPage<viewmodelclass>

  • The view does not have to be strongly typed. Just inherit it from ViewPage<dynamic>

Strongly-typed html helpers

In MVC 1 = Html.TextBox("FirstName") would go find the type from the database. In MVC2  = Html.TextBoxFor(m=>m.FirstName) and it will pick up the type from the class. And pick up any renames of class properties which it wouldn't in MVC 1.

  • There are built-in snippet for these html helper methods.
  • Basically suffix MVC1 helper method name with For to get strongly typed version.
  • Scott demos the CRUD view templates based on the model.
  • Scott demos overloading the create action method by verbs. GET to show form, POST to add item to db. Note that [AcceptVerbs] decorator attribute in MVC1 still there but now also [HttpPost] [HttpDelete] etc as shortcut for [AcceptVerbs] also in MVC 2.
  • No support for HTTP OPTIONS verb.
  • New HtmlHelpers - EditorFor, DisplayFor. Both pick up the type of the variable and displays the appropriate editor or display type. Both work really well for whole classes - they'll inspect all properties and put in appropriate things for all of its properties.
Html.EditorFor(model=>model); 
  • If you have complex relationships between tables (foreign keys), editorFor doesn't automatically generate dropdowns for those foreign keys. But all is customizable. You can add data annotations to your model class or custom template annotations.

Data annotations

Add a Metadata class to Models directory

[MetadataType(typeof(EventMetadata))] 
public partial class Event 
{ 
class EventMetadata 
{ 
[ScaffoldColumn(false)] 
public int EventId {get; set; } 
[DataType(DataType.MultilineText)] 
public string Description { get; set; } 
} 
} 
  • Custom template file in Views/abc/EditorTemplates
  • Scaffold the template then adjust exactly as you want. Name it after the model you want to be templated. Good practice? Use EditorFor without a custom template to begin with and then use custom templates to lock it down before release.
  • Note that data annotations are picked up by editor template (not ignored)
Html.EditorFor(model=>model, "nameOfEditorTempalteToUse"); 

Validation In MVC

“Skinny controllers with fat models”: validation logic into model or service layer - not inside action methods.

  • Add custom validation stuff in metadata class
class EventMetadata 
{ 
[Required(ErrorMessage="You msut specify a name")] 
public string EventName {get; set; } 
} 
  • You can plug any other validation libraries into MVC 2 should you wish to do so. (separation of concerns). Or build your own. All descriptors derive from ValidationAttribute.
  • To include client-side validation as well as server-side, include MicrsoftAjax.js and MicrosoftMVCValidation.js and add <% Html.EnableClientValidation(); %> to your view.

ActionRendering

  • Html.Action and Html.RenderAction.
  • Allows you to encapsulate bits of common UI  with backend processing (a la user controls in webforms).
  • Create a view - set it as a partial view. Set [ChildActionOnly] on the action method. Then on another view add a call to Html.Action(method, controller);

What’s the difference between this and Html.Partial?
Partial doesn't do the data modelling stuff.

Areas

  • Allows to encapsulate Controllers, Models and Views.
  • Essentially another layer - {area}\{controller}\{action}. 
  • You can split out areas across multiple projects but the tooling isn't entirely there yet. 
  • Avoid having an area with the same name as a controller not in an area.

Can you scope a Shared folder within an Area folder?
Yes

Asynchronous Support In MVC 2

To perform asynchronous operations without blocking the working thread waiting for the response from a long operation.

Unit Testing

  • TDD support is enhanced in VS10.
  • You can generate entity template so they don't derive from EntityObject (and thus no dependence on a database)
  • Ctrl+Alt+Space toggles Intellisense into “Consume First” mode which stops it aggressively replacing classes and methods you haven't created yet. Indeed it will even add in references to phantom classes.
  • Right click on phantom class to generate class and methods. Then let test fail, then make test pass.
  • Code coverage features included

End of session

A massive thanks to Scott for talking and braving the rain, and to Dave and Phil who managed to put on this Guathon and the one in Glasgow at such relatively short notice. It worked a treat.