|
|
These blog entries are written by industry experts and leaders. We consider this content to be a good read for any software developer or web technologist.
July 2007 - Posts
-
Last week I blogged about the new HTML web designer and CSS support in VS 2008. In it I talked about the new "split-view" feature that allows you to see both the HTML source and the Design View of a page at the same-time, and easily have any changes you make in one view be updated in the other. One of the questions several people have asked me since is whether you can customize the split-view arrangement so that you can have the views arranged vertically instead of horizontally - allowing you to make maximum usage of screen real-estate on wide-screen monitors and laptops. The good news is that this feature is now enabled in Beta 2 (click on the image below to see my laptop screen in all its glory): Notice above how when I select text in source-view, the designer automatically selects the equivalent markup element in design-view. The "CSS Properties" window on the right-hand side works in both design-view and source-view, and enables me to easily see/edit all CSS properties (defined in an external style sheet) for the <img> element within my <ul> list. To enable vertical split-view orientation in VS 2008, select the tools->options menu item and go to the HTML Designer->General section. Then check the "Split views vertically" checkbox: Hope this helps, Scott 
|
-
With all the out-of-band technology releases we've had (ASP.NET AJAX, .NET 3.0), it's nice to reach a point where we can bring them all together.
As an example...
Create a new web site in Visual Studio 2008. This will have to be a website under IIS, unfortunately, for reasons I'll point out later. Once the web site is up, add a new item – a WCF service. The service contract can look like the following:
[ServiceContract(Namespace="http://OdeToCode.com/ws",
Name="ServerProcessInfo")]
public interface IServerProcessInfo
{
[OperationContract]
IEnumerable<ProcessInfo> GetRunningProcesses();
}
The data contract can look like so:
[DataContract]
public class ProcessInfo
{
[DataMember]
public string Name { get; set; }
[DataMember]
public long WorkingSet { get; set; }
}
Finally, the LINQish implementation:
public class ServerProcessInfo : IServerProcessInfo
{
public IEnumerable<ProcessInfo> GetRunningProcesses()
{
return
(
from p in Process.GetProcesses()
orderby p.WorkingSet64 descending
select new ProcessInfo
{
Name = p.ProcessName,
WorkingSet = p.WorkingSet64
}
).Take(10);
}
}
We can entirely remove any WCF <system.serviceModel> configuration from web.config. Instead of all the XML configuration goo, we just need a Factory attribute in our .svc file:
<%@ ServiceHost Language="C#" Debug="true" Service="ServerProcessInfo"
...
Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" %>
What magic does this factory give us? Well, we can add a ServiceReference via a ScriptManager (it's nice that AJAX extensions are in the toolbox by default), and write some script:
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/ServerProcessInfo.svc" />
</Services>
</asp:ScriptManager>
<script type="text/javascript">
var ws = new odetocode.com.ws.ServerProcessInfo();
ws.GetRunningProcesses(getRunningProcessesComplete);
function getRunningProcessesComplete(result)
{
for(var i = 0; i < result.length; i++)
{
document.write(result .Name, " ", result .WorkingSet);
document.write("<br />");
}
}
Voila! Zero configuration and we have JSON on the wire!
HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 Server: Microsoft-IIS/7.0 X-Powered-By: ASP.NET Date: Tue, 31 Jul 2007 03:08:10 GMT Content-Length: 662
{"d":[{"__type":"ProcessInfo:#","Name":"devenv","WorkingSet":51011584}, {"__type":"ProcessInfo:#","Name":"w3wp","WorkingSet":44748800}, {"__type":"ProcessInfo:#","Name":"Fiddler","WorkingSet":34213888}, ... }
Note: there is a problem in Beta 2 that prevents this magic from working with WebDev.exe. The error you'll see with WebDev (aka Cassini) is:
"IIS specified authentication schemes 'Ntlm, Anonymous', but the binding only supports specification of exactly one authentication scheme. Valid authentication schemes are Digest, Negotiate, NTLM, Basic, or Anonymous. Change the IIS settings so that only a single authentication scheme is used."
Unfortunately, twiddling with the NTLM checkbox for WebDev doesn't help. Thus, the current need for IIS.

|
-
In the past I've blogged about the JavaScript and AJAX improvements with VS 2008 JavaScript Intellisense and VS 2008 JavaScript debugging. Below are a few notes about some of the ASP.NET AJAX runtime features coming as part of the VS 2008 and .NET 3.5 release, as well as important notes to read if you are opening existing ASP.NET AJAX 1.0 projects in VS 2008. ASP.NET AJAX included in .NET 3.5 ASP.NET AJAX 1.0 shipped as a separate download that you could install on top of ASP.NET 2.0. Starting with the .NET Framework 3.5 release, all of these features are built-in with ASP.NET, which means you no longer have to download and install a separate ASP.NET AJAX setup when building or deploying applications. When you create a new ASP.NET application or web-site in VS 2008 that targets the .NET 3.5 framework, VS will automatically add the appropriate AJAX registrations in your web.config file and the core ASP.NET AJAX server controls will show up in your toolbox. The version of ASP.NET AJAX that ships with .NET 3.5 has a number of nice improvements to it - including support for using UpdatePanels with WebParts, support for WCF based JSON end-points, support for using the ASP.NET Profile, Role and Login Application Services using JavaScript, and a number of bug fixes and performance improvements. Understanding ASP.NET AJAX Versioning ASP.NET AJAX 1.0 and .NET 3.5 can both be installed side-by-side on the same machine. ASP.NET AJAX 1.0 is implemented in V1.0 of the System.Web.Extensions.dll assembly. The implementation of ASP.NET AJAX included with .NET 3.5 lives in V3.5 of the System.Web.Extensions.dll assembly. The V3.5 of System.Web.Extensions.dll is a fully compatible super-set of the 1.0 implementation (which means you don't need to change any code in order to use it). Each ASP.NET application on a machine can choose which version of ASP.NET AJAX they want to build and run against. This is configured via the <system.web.extensions> section in its web.config file, as well as by what System.Web.Extensions.dll assembly it is compiled against (with web-site projects these references are registered in the <assemblies> section of the web.config file, with web application projects they are referenced via the project file). You will be able to use VS 2008 to target ASP.NET AJAX 3.5 applications, as well as to use the new VS 2008 multi-targeting support to build ASP.NET 2.0 applications that use ASP.NET AJAX 1.0. I cover how to-do both in the sections below. Important Beta 2 Information A few days before we shipped Beta2 on the web, we discovered a side-by-side issue with ASP.NET AJAX. If you read my original VS 2008 and .NET 3.5 Beta Released blog post, you'll remember that I called out this post-install patch step to fix this issue: You should download and run this batch file. This takes only a few seconds to run, and fixes an issue we found earlier this week with the version policy of System.Web.Extensions.dll - which is the assembly that contains ASP.NET AJAX. If you don't run this batch file, then existing ASP.NET 2.0 projects built with ASP.NET AJAX 1.0 and VS 2005 will end up automatically picking up the new version of ASP.NET AJAX that ships in .NET 3.5 Beta2. This will work and run fine - but cause you to inadvertently introduce a .NET 3.5 dependency in the applications you build with VS 2005. Running the batch file will change the version binding policy of the new System.Web.Extensions.dll assembly and ensure that you only use the new .NET 3.5 ASP.NET AJAX version with projects that you are explicitly building for .NET 3.5. The good news is that this fixes the side-by-side issue we found, and makes it safe to develop ASP.NET AJAX with both VS 2005 and VS 2008 on the same machine. The one gotcha is that it causes VS 2008 to incorrectly detect the version of ASP.NET AJAX being used when first opening older ASP.NET 2.0 projects (specifically it can cause VS 2008 to think the project is already using .NET 3.5). This requires that you to take a few additional steps in Beta2 the first time you open existing ASP.NET AJAX 1.0 web-site projects with VS 2008 to correct this. You will not need to take these steps with the final VS 2008 release. Upgrading ASP.NET AJAX 1.0 Applications to use ASP.NET AJAX 3.5 When you use VS 2008 to open an existing ASP.NET 2.0 application that uses ASP.NET AJAX 1.0, you can optionally choose to upgrade the application to use .NET 3.5 (and the version of ASP.NET AJAX included within it). The VS Web Tools team recently published a Upgrading ASP.NET AJAX 1.0 Websites and Web Applications to .NET Framework 3.5 blog post that describes the step-by-step instructions to accomplish this using VS 2008 Beta2. The good news is that upgrading an ASP.NET AJAX 1.0 application to .NET 3.5 does not require that you change any of your code, and should take only a few minutes to complete. As part of upgrading ASP.NET AJAX 1.0 application to .NET 3.5, you'll want to update compiled ASP.NET AJAX control libraries you might be using. The ASP.NET AJAX Control Toolkit team is now publishing both ASP.NET AJAX 1.0 and .NET 3.5 versions of the AJAX Control Toolkit that you can download here:
The Upgrading ASP.NET AJAX 1.0 Websites and Web Applications to .NET Framework 3.5 blog post covers how to add this ASP.NET AJAX 3.5 version of the AJAX Control Toolkit to the VS 2008 toolbox. Using VS 2008 to Build ASP.NET AJAX 1.0 Applications (using Multi-Targeting) When you use VS 2008 to open an existing ASP.NET 2.0 application that uses ASP.NET AJAX 1.0, you can alternatively choose not to upgrade it to .NET 3.5, and instead use the new multi-targeting features of VS 2008 to build it using ASP.NET 2.0 and ASP.NET AJAX 1.0. The VS Web Tools team recently published a Using VS 2008 to Target ASP.NET AJAX 1.0 blog post that describes the step-by-step instructions to accomplish this using VS 2008 Beta2. Included in the blog post are a number of manual steps you need to take in Beta2 to populate the VS 2008 toolbox with ASP.NET AJAX 1.0 and ASP.NET AJAX Control Toolkit server controls. For the final release of VS 2008 we'll release a setup package that will automate this for you, as well as add ASP.NET AJAX 1.0 project and item templates to VS 2008 for you to use. You might be wondering - why is it interesting to target ASP.NET AJAX 1.0 applications using VS 2008 instead of just using VS 2005? The benefit is that it enables you to build ASP.NET AJAX 1.0 applications that work on your existing servers (no need to upgrade them to .NET 3.5 immediately), while still allowing you to take advantage of some of the new VS 2008 IDE features like JavaScript Intellisense, JavaScript Debugging, better WYSIWYG HTML Designer, CSS management, the improved code editor, unit testing in VS Professional, continuous integration support with TFS, and more. Summary .NET 3.5 now includes built-in support for all ASP.NET AJAX 1.0 features. I'll be doing more blog posts in the future that also describe how to take advantage of the new features it provides. You can use VS 2008 to target both existing ASP.NET applications built with ASP.NET AJAX 1.0, as well as target the new version of ASP.NET AJAX built-into .NET 3.5. The VS Web Tools team blog posts above should help walk you though the step-by-step instructions on how to-do both. Hope this helps, Scott 
|
-
I ran across this book in Borders and was instantly intrigued. I have heard of some of the recent praise for Ellis's work so the idea of reading his first book, written when he was 19, was a compelling one.
This book gives the reader a feel for a group of people in a certain place at a certain time. It doesn't have a wealth of character development, or a traditional plot, but rather immerses the reader in this environment. The environment in this case is filled with drugs, bisexual encounters, pimps, dead bodies, snuff films, and worse. You get the impression that the people in this environment don't even realize the absurdity of what they are doing, or really have any feelings at all. The protagonist is the one person who starts to realize the insanity of what is going on, as each encounter gets darker and worse. Throughout the story the protagonist is also trying to work out his relationship with his ex-girlfriend, but this part of the plot is more symbolic about the protagonist's reluctance to go back to this city and lifestyle, and less about an actual human relationship.
Overall I enjoyed the book as much as you can enjoy a book about such dark things. This book doesn't try to answer the question of whether humans do evil things because of internal evil (original sin) or because of the influences of soceity (naturalism) but rather just shows how messed up things can be and sometimes are.
-James

|
-
I've blogged in the past about some of the text editor improvements in VS 2008 that have been made for JavaScript intellisense and CSS style intellisense. Recently I was looking over the shoulder of someone writing some code, and saw them using some other new text editing features that I hadn't seen before ("wait - how did you just do that?"). Below is a non-exhaustive list of a few new code editing improvements I've learned about this week. I'm know there are many more I don't know about yet - but I thought these few were worth sharing now: Transparent Intellisense Mode One of the things I sometimes find annoying with intellisense in VS 2005 is that the intellisense drop-down obscures the code that is behind it when it pops-up: With VS 2005 I often find myself needing to escape out of intellisense in order to better see the code around where I'm working, and then go back and complete what I was doing. This sometimes ends up disturbing my train of thought and typing workflow. VS 2008 provides a nice new feature that allows you to quickly make the intellisense drop-down list semi-transparent. Just hold down the "Ctrl" key while the intellisense drop-down is visible and you'll be able to switch it into a semi-transparent mode that enables you to quickly look at the code underneath without having to escape out of intellisense: When you release the "Ctrl" key, the editor will switch back to the normal intellisense view and you can continue typing where you were in the Intellisense window. This feature works with all language (VB, C#, and JavaScript). It also works with HTML, XAML and XML based markup. VB Intellisense Filtering The VB team has made some nice improvements to intellisense that make it much easier to navigate through APIs. Intellisense completion now automatically filters the member list available as you type to help you better pinpoint the API you are looking for. For example, if in an ASP.NET code-behind page you type "R" it will show the full list of types and members available (with the selection starting in the "R" list): When you type the second character of what you are looking for (in this case "e"), VB will automatically filter to only show those types that start with "Re" and highlight the most likely option: When you type the "s" it filters the list even further: When you type "p" it filters down to just the one option available: I find this cleaner and more intuitive than the previous model that always showed everything in the drop-down. VB LINQ Intellisense I've done several posts in the past about LINQ and LINQ to SQL. Both VB and C# obviously have full support for LINQ and LINQ to SQL. I think the VB team in particular has done some nice work to provide nice intellisense hints to help guide users when writing LINQ statements in the editor. For example, assuming we have a LINQ to SQL data model like the one I built in Part 2 of my LINQ to SQL series, I could use the VB code editor to easily work with it. Notice below how VB automatically provides a tooltip that helps guide me through writing the LINQ query syntax: I can then start writing my query expression and the VB intellisense will guide me through creating it: The above expression retrieves three column values from the database and creates a new anonymous type that I can then loop over to retrieve and work on the data: Organize C# Using Statements The C# editor has added some great intellisense improvements as well. Some of the biggest obviously include language intellisense and refactoring support for the new language features (Lambdas, Extension Methods, Query Syntax, Anonymous Types, etc). Just like in our VB example above, C# supports type inference and intellisense completion of anonymous types: One of the small, but nice, new features I recently noticed in VS 2008 is support for better organizing using statements in C#. You can now select a list of using statements, right-click, and then pull up the "Organize Usings" sub-menu: You can use this to alphabetically sort your namespaces (one of my pet peeves), and optionally use the 'Remove Unused Usings" command to remove un-necessary namespace declarations from the file: When you use this command the editor will analyze what types you are using in your code file, and automatically remove those namespaces that are declared but not needed to support them. A small but handy little feature. Summary The above list of editor improvements is by no means exhaustive, but rather just a few small improvements I've played with in the last week. Post others you notice in the comments section of this post, and I'll try and do an update with more in the future. Thanks, Scott 
|
-
-
If you read through my moster of a previous post you will notice that I am a big fan of technologies that are lumped into the phrase "ALT.NET". Stuff like MonoRail, nHibernate, MbUnit, Rhino.Mocks, etc.
While reading some of the posts about ALT.NET the thought that kept crossing my mind is how long will people stick with .NET when they start to understand some of the possible solutions out there. Many of the .NET solutions above are accomplishing goals in .NET that are very hard. ORM is hard. Mocking in a statically typed language is hard. But when you really start to look outside of the area of .NET you might find Ruby on Rails. Where all of this stuff is just plain easy.
In the link above the first bullet point of being ALT.NET is:
"You’re the type of developer who uses what works while keeping an eye out for a better way."
What if Ruby on Rails is the better way? How long before the people driving the ALT.NET movement figure out that the best way to do stuff is NOT.NET and perhaps RoR? I know that I feel myself getting closer and closer to that realization. What would make an ALT.NET developer stay in the .NET realm?
1) Your job. Ok, this is a pretty good one. You work for a company that uses .NET and they aren't going to switch. This will keep a number of people who love their jobs, but most people thinking about ALT.NET won't usually let a paycheck get in their way if they see greener pastures elsewhere. This might delay the move, the next contract I took is .NET because I can bill much more doing .NET work, but in the long run it won't stop me from pursuing RoR in my off-time and at some point making the switch.
2) Your comfort. Using Ruby and RoR is weird. I will be the first to admit it hasn't been easy adapting to how different it is. I don't think I have ever been more comfortable in a language then I am in C# and .NET. Similiar to #1 though, the people looking at ALT.NET aren't all about comfort. They are willing to try something different and get uncomfortable.
3) Microsoft. Microsoft puts an incredible amount of money and effort into .NET. One of the things I noticed at the Ruby Brigade here that was missing was the endless Microsoft swag that usually shows up at most .NET user groups. Microsoft has the MVP program, they send people to conferences for free, etc. But again, if someone is looking at ALT.NET technologies they are already somewhat detaching themselves from Microsoft. I can't see this holding too many people back.
I haven't made the switch yet. My next contract, which should last at least a year, is .NET. ChiroEase, my side-project, is .NET. But I am working on a little project using RoR. Testing the waters, we shall see where it goes.
Do you consider yourself in the ALT.NET camp? Are you looking at RoR? Why or Why not?
-James

|
-
I think I have mentioned it a little bit about it in the past, but I haven't ever really blogged about it. So here goes. ChiroEase is the side-project that I have spent a decent amount of my nights and weekends on for the last year or so.
The basic idea is that ChiroEase is a smart-client application for managing a chiropractors office. Currently there are a large number of older applications available for chiropractors, many are classic windows applications, many are actually geared toward all medical professions (so they include lots of unused features), etc. There are some new good competitors out there, but I think the one angle we have is that we are really trying to make it as simple and easy to use as possible. Because it's a smart-client they don't have to worry about back-ups, they can access the data from multiple devices, access their data from home, etc.
I never thought I would be building a smart-client. I think 99% of the time a website does a better job than a smart-client, but there were a couple compelling reasons to build it this way. The main reason for this is if the office's internet connection goes down they need to be able to continue using their office. Internet connections don't go down that much anymore, but the other partners saw it as a big issue from a sales standpoint. The second reason is that the people using these tools aren't usually savvy computer users. They are used to working with a windows app and this makes the transition much easier. We have plans for putting out a web-only version after we are done with the smart-client, but it will be in addition to and not instead of the smart-cleint.
Enough about that though, the more interesting part to me (and probably you) is the architecture. Here is what I came up with.
The Server-side is fairly simple. There is a web services front-end to a business logic layer. I use strongly-typed business entities (POCOs) tied up to NHibernate. There is a little data layer for the things that can't be done through NHibernate that talks to SQL Server 2000. This works fairly well, I have MbUnit tests at the business and data layer levels. One change I would like to make is to switch to MonoRail's ActiveRecord but for the time being I am using plain old nHibernate. Another change I would like to make is to use Rhino.Mocks for testing, but right now all of my tests hit the actual database.
The client-side is a little trickier. Since the application is a smart-client it needs to be available on-line and off-line. I looked at using SQL Express, but the install and uber-fat package scared me away. I decided on SQLite as off-line storage. This was before SQL Compact was available so I didn't compare SQLite with that. I have been incredibly impressed with SQLite. I used System.Data.Sqlite in conjunction with NHibernate. One of the more interesting parts of this is that I actually use the exact same nHibernate files and data access code on the server-side and client-side, which I think it just pretty cool.
The other client-side decision I had to make was what smart-client model I wanted to go with. I could go with either a sync model where the client and server-side database would synchronize when coming on-line, or I could go with the queue model where I store messages in a queue and send them when the connection comes back on. While making this decision the Smart Client literature over at P&P was very helpful, unfortunately when I went to look at the Smart Client App Block I found it to be over engineered and overly complex. Instead I just grabbed the only code out of the block I felt I really needed (the PInvoke line to check for a connection) and wrote my own simple message based queue. Basically when I try to send a message and the connection is down I store that message in Sqlite. When the connection comes back up I send those messages. The only tricky part is dealing with any concurrency issues that might have occurred, but from a day-to-day standpoint the user shouldn't have to deal with that very often.
For the actual client-side piece I used Windows Forms (just regular not XAML) with the Developer Express library. I didn't want to deal with the crappy default controls, and Developer Express gave me a free license for being an MVP, so I went with them. Their library is comprehensive and very well done. The couple of issues I have come across have been quickly answered by their support or I have found an answer in the docs. The only thing lacking was a wizard control, and I went with ActiPro for that. It works OK, but it has some hard to troubleshoot issue where it grabs an assembly and won't let go. (very frustrating as it means you have to reboot Visual Studio). For the actual architecture of the client-side I went with the obscure Presentation Model pattern. Most people use MVC or MVP, but I have become pretty fond of the presentation model. I am writing the synchronize logic by hand, but I think in the future I might try to whip up a framework to do that for me. If you aren't familiar with it, take a moment to read up on in from Fowler. The main reason to use the presentation model is that I think it works great for testing your presentation logic and it eliminates the pointless interfaces required for MVP.
That's about it really. We are dangerously close to a beta of the product, but we hit a snag when we lost one of our main subject matter experts. My two partners on the project (a business/project manager and a chiropractor/sales guy) are busy trying to find us some new users and then we should be ready to go. My goal is to have it live and running by the end of the year, which is a little ambitious but not out of the question.
-James

|
-
I'm very pleased to announce that the Beta 2 release of VS 2008 and .NET 3.5 Beta2 is now available for download. You can download the Visual Studio 2008 product here. You can alternatively download the smaller VS 2008 Express Editions here. VS 2008 and Visual Web Developer 2008 Express can be installed side-by-side with VS 2005. .NET 3.5 Beta2 also includes a go-live license which allows you to build and deploy applications into production. Very Important: Please read my "Installation Notes" at the bottom of this blog post for a few post-installation steps you must make to ensure everything runs well. One of these steps fixes a side-by-side issue we found with ASP.NET AJAX. Quick Tour of Some of the New Features for Web Development Over the last few months I've written several blog posts that discuss some of the new improvements in this release. Below is a quick summary list of several of them that I have already published. This list is by no means exhaustive - there are a lot more things I haven't had a chance to blog about yet (stay tuned for more posts!): VS 2008 Multi-Targeting Support VS 2008 enables you to build applications that target multiple versions of the .NET Framework. You can learn more about how this works from my blog post here: VS 2008 Web Designer and CSS Support VS 2008 includes a significantly improved HTML web designer. This delivers support for split-view editing, nested master pages, and great CSS integration. Below are two articles I've written that discuss this more: ASP.NET also has a new <asp:ListView> control that I'll be blogging about in the near future. It delivers very flexible support for data UI scenarios, and allows full customization of the markup emitted. It works nicely with the new CSS support in VS 2008. ASP.NET AJAX and JavaScript Support .NET 3.5 has ASP.NET AJAX built-in (and adds new features like UpdatePanel support with WebParts, WCF support for JSON, and a number of bug fixes and performance improvements). VS 2008 also has great support for integrating JavaScript and AJAX into your applications: I will be doing a blog post in the next few days that talks more about some of the ASP.NET AJAX specific improvements, as well as how to upgrade existing ASP.NET AJAX 1.0 applications to use them. Language Improvements and LINQ The new VB and C# compilers in VS 2008 deliver significant improvements to the languages. Both add functional programming concepts that enable you to write cleaner, terser, and more expressive code. These features also enable a new programming model we call LINQ (language integrated query) that makes querying and working with data a first-class programming concept with .NET. Below are some of the articles I've written that explore these new language features using C#: Data Access Improvements with LINQ to SQL LINQ to SQL is a built-in OR/M (object relational mapper) in .NET 3.5. It enables you to model relational databases using a .NET object model. You can then query the database using LINQ, as well as update/insert/delete data from it. LINQ to SQL fully supports transactions, views, and stored procedures. It also provides an easy way to integrate business logic and validation rules into your data model. Below are some of the articles I've written that explore how to use it: I'll be adding several more articles to my series above in the weeks ahead. I think you'll find that LINQ to SQL makes it dramatically easier to build much cleaner data models, and write much cleaner data code. Lots of other improvements The list above is only a small set of the improvements coming. For client development VS 2008 includes WPF designer and project support. ClickOnce and WPF XBAPs now work with FireFox. WinForms and WPF projects can also now use the ASP.NET Application Services (Membership, Roles, Profile) for roaming user data. Office development is much richer - including support for integrating with the Office 2007 ribbon. WCF and Workflow projects and designers are included in VS 2008. Unit testing support is now much faster and included in VS Professional (and no longer just VSTS). Continuous Integration support is now built-in with TFS. AJAX web testing (unit and load) is now supported in the VS Test SKU. And there is much, much more... Important Installation Notes - PLEASE READ! There are two important things you should do immediately after installing VS 2008 and .NET 3.5 Beta2: 1) You should download and run this batch file. This takes only a few seconds to run, and fixes an issue we found earlier this week with the version policy of System.Web.Extensions.dll - which is the assembly that contains ASP.NET AJAX. If you don't run this batch file, then existing ASP.NET 2.0 projects built with ASP.NET AJAX 1.0 and VS 2005 will end up automatically picking up the new version of ASP.NET AJAX that ships in .NET 3.5 Beta2. This will work and run fine - but cause you to inadvertently introduce a .NET 3.5 dependency in the applications you build with VS 2005. Running the batch file will change the version binding policy of the new System.Web.Extensions.dll assembly and ensure that you only use the new .NET 3.5 ASP.NET AJAX version with projects that you are explicitly building for .NET 3.5. 2) If you have ever installed a previous version of "Orcas" or VS 2008 on your machine (either Beta1 or one of the CTP versions), you need to reset your VS 2008 settings after installing Beta2. If you don't do this, you'll have an odd set of settings configured (some windows will be in the wrong place), and you'll potentially see some IDE performance slowness. You can reset your settings by typing "DevEnv /resetsettings" on the command-line against the VS 2008 version of the IDE: Summary There are a lot of new improvements and enhancements that I hope you'll find really useful with VS 2008 and .NET 3.5. Stay tuned to my blog over the next few weeks as I'll be posting more about some of the new features and how to get the most out of them. Thanks, Scott 
|
-
One of the big features that web developers will quickly discover with VS 2008 is its dramatically improved HTML designer, and the rich CSS support it brings. VS 2008 now uses the same web designer that ships with Microsoft's new Expression Web product. In addition to providing lots of new functionality, you'll also find that this web designer is much faster than the VS 2005 version (which was based on a much older code base). Below is a quick tour of some of the new web designer features that you'll be able to take advantage of with both VS 2008 as well as the free Visual Web Developer 2008 Express: Split View Editing In addition to supporting both source-view and design-view, VS 2008 adds support for a new "split-view" mode when working on pages. This allows you to see both the HTML source and the Design View at the same-time, and easily have any changes you make in one view be updated in the other:
CSS Style Manager VS 2008 supports a new tool window inside the IDE called "Manage Styles". This shows all of the CSS stylesheets, and their corresponding rules, for the page you are currently editing. It can be used both when you are in design-view, as well as when you are in source view on a page:
A circle around a CSS rule in the manage styles window indicates that particular rule is in use within the current document. Using the mouse to hover over the rule allows you to quickly see the CSS rule values:
You can then either right-click on a CSS rule and select "Modify Style" to bring up a graphical CSS rules editor, or you can double click on the rule in the manage styles window to automatically open the stylesheet file and jump immediately to the CSS source definition to edit (with full intellisense):
For even more tips/tricks about how to best use the "Manage Styles" tool window please read this blog post. CSS Properties Window One of the other cool new CSS features that is also supported in both design and source view is the new CSS Properties Window:
When you select an HTML element or ASP.NET server control, the CSS property window will show you all of the CSS settings currently applied to it. You can also change any of the values using the CSS property grid. The "target rule" drop-down in the style toolbar allows you to determine under what rule the settings are applied (read this blog post to learn more about the style toolbar and target rule dropdown). If, like me, you sometimes struggle with large CSS stylesheets and find yourself shouting "why the $!#@ is it looking like that?", you'll find the "summary" view of the CSS Properties window really useful (just click the summary button at the top of the CSS properties pane). When you press this button it enables a filtering mode that shows you the full inheritance set of CSS rules for the current HTML element or ASP.NET control you are working with:
In the properties grid above you'll notice that some values are duplicated multiple times - with red arrows striking out previous values. This indicates that a parent CSS rule setting is being overridden by another CSS rule's value. You can see both the original value as well as the overridden one in the summary view at the bottom. You can click on the individual values to see where in the CSS precedence hierarchy this value was inherited from or overridden. In the example below you can see that the final color for the current element that my cursor is on is a dark brown color. If I select this final color value, the CSS properties window will draw a blue box in the applied-rules list above indicating that this setting is set in the "singlecontent h3" rule:
If I click on the lighter brown color setting that this rule overrode (and which has the red strike-thru), you can see that it originated with the page's HTML body CSS rule (notice how the body rule below is selected in the applied rules list when I select the overridden value below):
Please read this dedicated CSS Properties Window blog post to learn even more how to use the CSS property window. CSS Source View Intellisense The HTML designer supports the ability to select an element or control in design-view, and graphically select a rule from the CSS list to apply to it. You'll also find when in source mode that you now have intellisense support for specifying CSS class rules:
This is true for both HTML element (like above), as well as with ASP.NET server controls:
This CSS intellisense is supported in both regular HTML / ASP.NET pages, as well as when working with pages based on master pages and nested master pages. Nested Master Page Support Earlier this month I wrote a dedicated blog post that covered the new VS 2008 Nested Master Page Support. All of the above designer and CSS features obviously work with that as well:
Summary The above post provides a quick look at some of the new HTML designer and CSS tool support in VS 2008 (all of the above features also ship with the free Visual Web Developer 2008 Express edition). Because VS 2008 now has multi-targeting support you'll be able to use these feature immediately without having to install .NET 3.5 on your servers. You can open existing ASP.NET 2.0 projects in VS 2008, have VS 2008 continue to target .NET 2.0 as the runtime target, and begin using these features immediately. Over the next week I'll also be starting a new multi-part blog series that covers the new <asp:listview> control that ships as part of ASP.NET in .NET 3.5. One of the big benefits of the <asp:listview> is that it enables developers to have total control over the HTML output emitted in data scenarios. This works well with all of the new CSS tool features above, and enables you to more easily create great looking web sites and applications. Hope this helps, Scott 
|
-
Sahil's post on "Things
I can't live without" got me thinking about some software I use that might
not be so well known.
XaMp Studio plays XM Radio from
a desktop application. Looks like Winamp and
offers more features than the XM web interface. There is a toast notification to tell you when your favorite artist or tune is streaming. Note: don't download the "desktop" edition,
as it seems incompatible with Vista and Windows Media Player 11.
DynDNS Updater coupled with the
DynDNS service can give any computer a name – even if your ISP hands out dynamic
IP addresses. The Updater can run as a Windows service to keep addresses in synch.
FoxIt Reader is a small,
fast PDF reader.
Scott Hanselman first mentioned Foxit a couple years ago, and the feature
list has grown since that time. The only downside is that Foxit does not seem to
decrypt password protected PDF files, so no e-book reading with Foxit.
Robocopy now comes standard
in Windows Vista. It's the tool I use for large file operations,
particularly when moving bits over the network. Robocopy easily beats copying files
using Windows Explorer, after all, the "robo" is short for robust.
There is only one weakness with robocopy. Try copying an Outlook PST file when Outlook
is running:
PS> robocopy C:\Users\bitmask\appdata\Local\Microsoft\Outlook d:\temp outlook.pst
-------------------------------------------------------------------------------
ROBOCOPY :: Robust
File Copy for Windows
-------------------------------------------------------------------------------
Started : Tue Jul 24 12:33:20 2007
Source : C:\Users\bitmask\appdata\Local\Microsoft\Outlook\
Dest : d:\temp\
Files : outlook.pst
Options : /COPY:DAT /R:1000000 /W:30
------------------------------------------------------------------------------
1 C:\Users\bitmask\appdata\Local\Microsoft\Outlook\
0.0% New File
856.3 m Outlook.pst
2007/07/24 12:33:20 ERROR 33 (0x00000021) Copying File C:\Users\bitmask\appdata\Local\Microsoft\Outlook\Outlook.pst
The process cannot access the file because another
process has locked a portion of the file.
Waiting 30 seconds...
Which brings me to my "last but not least" entry:
Hobocopy.
PS> .\hobocopy C:\users\bitmask\appdata\local\microsoft\outlook\ d:\temp outlook.pst
HoboCopy (c) 2006 Wangdera Corporation. hobocopy @ wangdera.com
Starting a full copy from C:\users\bitmask\appdata\local\microsoft\outlook\ to d:\temp
Copied directory
Backup successfully completed.
Backup started at 2007-07-22 12:46:25, completed at 2007-07-22 12:47:48.
1 files (856.39 MB, 1 directories) copied, 7 files skipped
Hobocopy is Craig Andera's
tool that uses the Volume Shadow Service to copy locked files. Pure goodness. 
|
-
Ayende had a recent post with the following quote from Nicholas Piasecki:
To me, this discussion all boils down to one thing: the foreach loop. Let's say you want to display a table of sales reports, but after every tenth row, you want to print out an extra row that displays a running total of sales to that point. And you want negative numbers to appear in red, positive numbers to appear in green, and zeros to appear in black. In MonoRail, this is easy; with WebForm's declarative syntax, just shoot yourself in the face right now. Most solutions I've seen end up doing lots of manipulation in the code-behind and then slamming it into a Literal or something, which to me defeats the purpose of the code separation.
Ayende says this is the essence of why he dislikes WebForms. In the comments, someone proposed a rails solution ...
#set ($i = 0)
#set ($running_total = 0)
#foreach ($report in $reports)
#each
<tr>
<td>$report.name</td>
#if ($report.ammount > 0)
<div class="green">
#elseif ($report.ammount < 0)
<div class="red">
#else
<div class="black">
#end
$report.ammount</td>
</tr>
#set ($running_total = $running_total + $report.ammount)
#set ($i = $i + 1)
#between
#if (($i % 10 ) == 1)
<tr class="Running Total">
<td>$running_total</td>
</tr>
#end
#end
... which received praise for elegance. I'm thinking if you really want to intermingle code and markup, than open up an .aspx page and have at it:
<%@ Page Language="C#" %>
<% SalesReport report = new SomeApplicationService().GetSalesReport(); int rowCount = 0;
int runningTotal = 0;
%>
<table>
<% foreach (Salesperson p in report.SalesPeople) {
rowCount++;
runningTotal += p.TotalSales;
%>
<tr>
<td><%= p.Name %></td>
<td>
<div class="<%= p.TotalSales < 0 ? "red" : p.TotalSales > 0 ? "green" : "black" %>">
<%= p.TotalSales.ToString("c") %>
</div>
</td>
</tr>
<% if(rowCount % 10 == 0) { %>
<tr>
<td>SubTotal:</td>
<td><%= runningTotal.ToString("c") %></td>
</tr>
<% } // end if %>
<% } // end foreach %>
</table>
Why throw out the baby with the bathwater? 
|
-
RockNUG is the newest .NET user group in the vast suburbia of Washington D.C. Their next meeting is on August 8 at Montgomery College, and I'll be there to talk about ASP.NET AJAX. I have one WF book and one Pluralsight T-shirt to give away, too.
Come for the free pizza, and stay for the asynchronous fun! 
|
-
Over the last few years we've been working to make .NET and the CLR a great environment for dynamic languages. About 14 months ago we formed a dedicated group within my team that has been focused on adding richer CLR runtime support for dynamic languages, as well as delivering first class .NET implementations of popular dynamic languages. DLR Background This spring we shipped the first preview release of a new .NET library that we call the "Dynamic Language Runtime" (or DLR for short). It provides a set of features on top of the CLR designed explicitly for dynamic language scenarios. These include a shared dynamic type system, language hosting model, and support to make it possible to generate fast dynamic code. These features make it much easier to build high-quality dynamic language implementations on .NET. These implementations can access and use any of the APIs in the .NET Framework, as well as easily interoperate with code written in any other .NET language (for example: you could write a Ruby class that invokes and uses a C# class, which in turn invokes a Python class). This spring at the MIX 07 conference we announced that Microsoft will be shipping 4 dynamic language implementations of our own for .NET: - IronPython
- IronRuby (new)
- Javascript
- Dynamic VB (new)
The source code of our IronPython implementation, as well as the source code for the underlying DLR library, was published on CodePlex in April. You can download both of them today from the IronPython codeplex site. All of the source is made available under the MSPL permissive license - which provides full commercial and non-commercial modification rights. IronRuby Pre-Alpha Release Today we are making available the first public drop of our IronRuby implementation. You can learn more about how to download the source, build it, and try it out from John Lam's blog post here. Today's IronRuby drop is still a very early version, and several language features and most libraries aren't implemented yet (that is why we are calling it a "pre-alpha" release). It does, though, have much of the core language support implemented, and can also now use standard .NET types and APIs. IronRuby has been architected to take advantage of a new DLR feature we call "Dynamic Sites" - which delivers a fast adaptive call-site method caching implementation. It also uses the lightweight-code generation features of the CLR. Lightweight code generation enables dynamic language implementations to create in-memory IL that is then JIT'd into native code at runtime (without ever having to save anything to disk). This can yield much better runtime performance than interpreted code, and the lightweight codegen feature ensures that once we are finished with the JIT'd code we can optionally garbage collect it to avoid leaking. We are releasing today's drop mainly for developers interested in language implementations to start looking at the IronRuby source code, and learn how it was implemented. Developers interested in playing with an early version of Ruby for .NET can also download it and give it a spin. IronRuby Project Plans Next month we will be moving the IronRuby source code repository to be hosted on RubyForge. As part of this move we are also opening up the project to enable non-Microsoft developers to enlist in the project and contribute source code. We'll then work to implement the remaining features and fix compatibility issues found as more libraries and source are ported to run on top of it. The end result will be a compatible, fast, and flexible Ruby implementation on top of .NET that anyone can use for free. IronRuby "Hello World" Console Sample If you download and build the IronRuby source code, you are probably wondering "how do I start using it?" The easiest way to get started is to run the "rbx.exe" interactive console application that by default is built under the \bin\release directory:
This console shell provides you with the ability to write Ruby code interactively. After each line, the shell will interactively execute it. For example, we could output hello world by typing puts "Hello World":
To output this 10 times in a row, we could type the following:
To use Windows Forms functionality in IronRuby, we could type a require statement that references the System.Windows.Forms assembly, and then use the MessageBox.Show method to display a message in a modal dialog:
IronRuby "Hello World" WPF Sample One of the benefits of implementing a language on top of .NET is that it enables developers using that language to get full access to the rich framework libraries provided with the .NET Framework. For a simple example of this in action, I could create a "HelloWPF.rb" text file and type in the following Ruby code below:
The above code uses the WPF UI framework to create a Window that hosts a StackPanel layout manager that initially contains just a button. When the button is pressed, a new label control is created and added into the StackPanel (causing it to automatically be flowed in the Window). I can then run the above application using IronRuby by passing the "HelloWPF.rb" text file as an argument to rbx.exe:
When I run it I'll get a window with a WPF button (note above I added a nice DropShadowBitmapEffect to it in the code above):
And each time I press the button a new label will be added to the Window:
Not only does having the ability to use all of the .NET APIs provide a lot of power, but you'll notice in the code we wrote how it is possible to naturally integrate .NET APIs into other language syntaxes:
In the code snippet above I'm using the Ruby block language feature (similar to a Lambda expression with C# 3.0 and VB9) to implement a "Click" event handler on the WPF button. Notice how within the block the standard Ruby naming patterns can be used when accessing any .NET API. For example, instead of using the "FontSize" property on the WPF Label we are accessing it using "font_size" as the property accessor name. IronRuby automatically handles the naming conversion - enabling developers to program with a consistent naming pattern regardless of their language of choice. Summary If you are interested in trying out this first early drop of IronRuby, you can download the source and build it here. You can then download my WPF sample above and run it yourself here (note: you must have .NET 3.0 or 3.5 installed - since those deliver the WPF APIs). To learn more about WPF, I also highly recommend Adam Nathan's excellent WPF Unleashed book (read the review comments on Amazon to see why). Hope this helps, Scott 
|
-
Unit testing features will now be available in the Professional version of Visual Studio 2008.
Unit testing has been to Visual Studio what Barry Bonds has been baseball – a center of controversy. First there was the Peter Provost petition to include unit testing features in all version of VS. Then there was the highly criticized TDD guidance accompanying the feature. Next came some performance issues and pain while using the shipping version, and most recently, the TestDriven.NET hullaballoo added an emotional charge to the air.
Putting all this behind us - what's new in 2008? I've been working with the latest bits, and I can say:
- Performance has improved dramatically.
- The context-menu command "Run Tests" is new (and context sensitive).
- Keyboard shortcuts take away the pain of the VS2005 test runner (Ctrl+R, A to run all tests in a solution, Ctrl+R, T to run tests in the current context).
Moving the unit-testing features into the Pro edition is a great move by Microsoft. I hope the feature gains traction and brings awareness of unit testing into the mainstream (although I think we are already close, aren't we?).
Related Links
Guidelines for Test-Driven Development by Jeff Palermo
Rules to Better Unit Tests by Adam Cogan.

|
-
A few weeks ago I blogged about the new JavaScript Intellisense support in VS 2008. One of the other JavaScript features that I'm sure will be popular in VS 2008 is the much-improved support for JavaScript debugging. This is enabled in both the free Visual Web Developer 2008 Express edition as well as in Visual Studio, and makes using JavaScript and building AJAX applications significantly easier. Setting JavaScript breakpoints in ASP.NET pages One of the annoying things with VS 2005 is that you have to first run your ASP.NET pages before you can set JavaScript breakpoints in them in the debugger. VS 2008 makes this much better by adding new support that allows you to set client-side JavaScript breakpoints directly within your server-side .aspx and .master source files:  When you set a breakpoint in your .aspx page like above, VS 2008 will automatically map the breakpoint location to the dynamically generated client HTML that runs in the browser when the page is later executed: If you add/remove/update the breakpoint locations in the running HTML document, VS 2008 is also now smart enough to perform the reverse mapping and update the breakpoint in the original .aspx or .master source file on the server. This makes it much easier to get into a nice edit/debug/edit/debug flow as you are iterating on your applications. Best of all, you can now set both client-side JavaScript breakpoints and VB/C# server-side breakpoints at the same time (even in the same page) and use a single debugger to step through both the server-side and client-side code in a single debug session (which is extremely useful for any AJAX heavy application). Any JavaScript breakpoints you set will also now by default be saved by VS 2008 when you close the project/solution. When you open up the project again, the previous locations you set the breakpoints on will still have them enabled. Script Document Navigation within the Solution Explorer Often the JavaScript that is sent down to a browser client is dynamically generated on the server (for example: with scripts that are stored as resources within compiled server controls - like ASP.NET AJAX UpdatePanels and control extenders). In scenarios such as these, you want to be able to easily see all JavaScript URLs being loaded from a page, as well as step into the within the debugger. VS 2008 makes it much easier to-do this by integrating the running Script Document feature (that in VS 2005 was a separate tool-pane window) into the VS 2008 solution explorer view when you are debugging a web application. Specifically, when you are using VS to run and debug a page, VS 2008 will now list all of the script URLs that the page you are debugging has loaded in the browser at the top of your VS solution explorer pane: You can then double click on any of the URLs under the "Script Documents" node at the top to see the JavaScript file that was loaded in the page: You can obviously then set breakpoints in the loaded JavaScript and debug everything. Much Richer Debug Watch/Locals and Visualizer Support Easily opening and navigating JavaScript files in the debugger is nice - but the real meat of the improvements made with VS 2008 JavaScript debugging is in the much improved object execution and inspection support. When you inspect a variable within the debugger using VS 2008, you'll find much more detailed object information is now available: You can now browse runtime object methods: You can now browse runtime object events: And you now get much, much more detailed property and property type information of running objects. Note below how I am traversing the div element's "parentElement" property to dynamically look up details about the element's parent HTML element and overall position within the HTML DOM: You can obviously use the debugger property grid above to both lookup as well as set values. You can also run code in the immediate window to retrieve and change JavaScript at runtime: VS 2008 also provides support for pluggable debug visualizers that you can use with JavaScript debugging. This enables developers to add extensions to the debugger that can work against running objects and provide richer visualization views of them. For example, we could use the built-in "Text", "XML", or "HTML" visualizer to load a dialog to better inspect a value: I suspect we might see a cool CodePlex project providing nice JSON and REST JavaScript visualizers soon. Summary The above walkthrough hopefully provided a good overview of some of the new JavaScript debugging features coming soon. There are many more JavaScript and AJAX features coming in VS 2008 and .NET 3.5 that I'll be covering in future blog posts. Note that because of the new VS 2008 multi-targeting support, you can use the JavaScript debugging features above with both ASP.NET applications built using .NET 3.5 (which also now has ASP.NET AJAX built-in), as well as with existing ASP.NET 2.0 applications (including ones that use the separate ASP.NET AJAX 1.0 download). This, combined with the new VS 2008 JavaScript intellisense support, provides a very compelling reason to start using VS 2008 - even if you are using it to only target .NET 2.0 applications. Hope this helps, Scott P.S. To learn more about VS 2005 JavaScript Debugging, please read this blog post. Dan Wahlin also recently posted a nice set of AJAX testing and debugging tools that I recommend checking out here. 
|
-
I wrote my first class with automatic properties in Orcas today...
[DataContract(Name="FoodFact")]
public class FoodFactMessage
{
[DataMember]
public int ID { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public int Calories { get; set; }
}
... then I found myself staring at the screen.
It's an interface!
No,it's a class! Wait, it is a class!
I'd say the syntax is still growing on me.
I'm sure some people will say – why use properties at all? If you don't need special code in the get and set methods – why not just use a public field?
The quick answer is: reflection. There are many forms of magic that will only occur if you expose state using public properties.
Related Links

|
-
Over the last few weeks I've been writing a series of blog posts that cover LINQ to SQL. LINQ to SQL is a built-in O/RM (object relational mapper) that ships in the .NET Framework 3.5 release, and which enables you to easily model relational databases using .NET classes. You can use LINQ expressions to query the database with them, as well as update/insert/delete data. Below are the first four parts of my LINQ to SQL series: In these previous LINQ to SQL blog posts I focused on how you can programmatically use LINQ to SQL to easily query and update data within a database. In today's blog post I'll cover the new <asp:LinqDataSource> control that is shipping as part of ASP.NET in the upcoming .NET 3.5 release. This control is a new datasource control for ASP.NET (like the ObjectDataSource and SQLDataSource controls that shipped with ASP.NET 2.0) which makes declaratively binding ASP.NET UI controls to LINQ to SQL data models super easy. Sample Application We'll be Building The simple data editing web application I'll walkthrough building in this tutorial is a basic data entry/manipulation front-end for products within a database: The application will support the following end-user features: - Allow users to filter the products by category
- Allow users to sort the product listing by clicking on a column header (Name, Price, Units In Stock, etc)
- Allow users to skip/page over multiple product listings (10 products per page)
- Allow users to edit and update any of the product details in-line on the page
- Allow users to delete products from the list
The web application will be implemented with a clean object-oriented data model built using the LINQ to SQL ORM. All of the business rules and business validation logic will be implemented in our data model tier - and not within the UI tier or in any of the UI pages. This will ensure that: 1) a consistent set of business rules are used everywhere within the application, 2) we write less code and don't repeat ourselves, and 3) we can easily modify/adapt our business rules at a later date and not have to update them in dozens of different places across our application. We will also take advantage of the built-in paging/sorting support within LINQ to SQL to ensure that features like the product listing paging/sorting are performed not in the middle-tier, but rather in the database (meaning only 10 products are retrieved from the database at any given time - we are not retrieving thousands of rows and doing the sorting/paging within the web-server). What is the <asp:LinqDataSource> control and how does it help? The <asp:LinqDataSource> control is an ASP.NET control that implements the DataSourceControl pattern introduced with ASP.NET 2.0. It is similar to the ObjectDataSource and SqlDataSource controls in that it can be used to declaratively bind other ASP.NET controls on a page to a datasource. Where it differs is that instead of binding directly to a database (like the SqlDataSource) or to a generic class (like the ObjectDataSource), the <asp:linqdatasource> is designed to bind against a LINQ enabled data model. One of the benefits of using the <asp:linqdatasource> control is that it leverages the flexibility that LINQ based ORMs provide. You don't need to define custom query/insert/update/delete methods for the datasource to call - instead you can point the <asp:linqdatasource> control at your data model, identify what entity table you want it to work against, and then bind any ASP.NET UI control against the <asp:linqdatasource> and have them work with it. For example, to get a basic product listing UI on my page that works against Product entities within a LINQ to SQL data model, I could simply declare a <asp:linqdatasource> on my page that points to my LINQ to SQL datacontext class, and identify the entities (for example: Products) in the LINQ to SQL data model I want to bind against. I could then point a GridView at it (by settings its DataSourceID property) to get a grid-like view of the Product content: Without having to-do anything else, I can run the page and have a listing of my Product data with built-in support for paging and sorting over the data. I can add a edit/delete button on the Grid and automatically have update support as well. I don't need to add any methods, map any parameters, or write any code for the <asp:LinqDataSource> to handle both these querying and updating scenarios - it can work against the LINQ to SQL data model we point it against and do these operations automatically. When updates are made, the LINQ to SQL ORM will automatically ensure that all business rules and validation logic we've added (as partial methods) to the LINQ to SQL data model pass before persisting anything to the database. Important: The beauty of LINQ and LINQ to SQL is that it obviously isn't tied to being used only in UI scenarios - or with particular UI binding controls like the LinqDataSource. As you've seen in my previous posts in this series, writing code using the LINQ to SQL ORM is extremely clean. You can always write custom UI code to directly work against your LINQ to SQL data model if you prefer, or when you find a UI scenario that isn't particularly suited to using the <asp:linqdatasource>. The below sections walkthrough using LINQ to SQL and the <asp:LinqDataSource> control to build the web application scenario I defined above. Step 1: Define our Data Model We'll begin working on the application by first defining the data model we'll use to represent our database. I discussed how to create a LINQ to SQL data model using VS 2008's LINQ to SQL designer in Part 2 of this series. Below is a screenshot of the data model classes I can quickly create using the LINQ to SQL designer to model the "Northwind" sample database: We'll revisit our data model in Step 5 of this tutorial below when we add some business validation rules to it. But to begin with we'll just use the above data model as-is to build our UI. Step 2: Creating a Basic Product Listing We'll start our UI by creating an ASP.NET page with a <asp:gridview> control on it and use some CSS to style it: We could write code to programmatically bind our data model to the GridView (like I did in Part 3 of this series), or alternatively I could use the new <asp:linqdatasource> control to bind the GridView to our data model. VS 2008 includes build-in designer support to make it easy to connect up our GridView (or any other ASP.NET server control) to LINQ data. To bind our grid above to the data model we created earlier, we can switch into design-view, select the GridView, and then select the "New Data Source..." option within the "Choose Data Source:" drop-down: This will bring up a dialog box that lists the available datasource options to create. Select the new "LINQ" option in the dialog box and name the resulting <asp:linqdatasource> control you want to create: The <asp:linqdatasource> designer will then display the available LINQ to SQL DataContext classes that your application can use (including those in class libraries that you are referencing): We'll want to select the data model we created with the LINQ to SQL designer earlier. We'll then want to select the table within our data model that we want to be the primary entity for the <asp:linqdatasource> to bind against. For this scenario we'll want to select the "Products" entity class we built. We'll also want to select the "Advanced" button and enable updates and deletes for the datasource: When we click the "Finish" button above, VS 2008 will declare a <asp:linqdatasource> within our .aspx page, and update the <asp:gridview> to point to it (via its DataSourceID property). It will also automatically provide column declarations in the Grid based on the schema of the Product entity we choose to bind against: We can then pull up the "smart task" context UI of the GridView and indicate that we want to enable paging, sorting, editing and deleting on it: We can then press F5 to run our application, and have a product listing page with full paging and sorting support (note the paging indexes at the bottom of the grid below): We can also select the "edit" or "delete" button on each row to update the data: If we flip into source view on the page, we'll see that the markup of the page contains the content below. The <asp:linqdatasource> control points at the LINQ to SQL DataContext we created earlier, as well as the entity table we want to bind against. The GridView then points at the <asp:linqdatasource> control (via its DataSourceID) and indicates which columns should be included in the grid, what their header text should be, as well as what sort expression to use when the column header is selected. Now that we have the basics of our web UI working against our LINQ to SQL data-model, we can go ahead and further customize the UI and behavior. Step 3: Cleaning up our Columns Our GridView above has a lot of columns defined within it, and two of the column values (the SupplierID and the CategoryID) are currently foreign-key numbers -- which certainly isn't the ideal way to represent them to an end-user. Removing Unnecessary Columns We can start cleaning up our UI by deleting a few of the columns we don't need. I can do this in source mode (simply nuke the <asp:boundfield> declarations) or in designer mode (just click on the column in the designer and choose the "Remove" task). For example, we could remove the "QuantityPerUnit" column below and re-run our application to get this slightly cleaner UI: If you have used the <asp:ObjectDataSource> control before and explicitly passed update parameters to update methods (the default when using DataSet based TableAdapters) one of the things you know can be painful is that you have to change the method signatures of your TableAdapter's update methods when the parameters based by your UI are modified. For example: if we deleted a column in our grid (like above), we'd end up having to modify our TableAdapter to support update methods without that parameter. One of the really nice things about the <asp:LinqDataSource> control is that you do not need to-do these types of changes. Simply delete (or add) a column from your UI and re-run the application - no other changes are required. This makes changing web UI built using the <asp:LinqDataSource> much easier, and enables much faster scenarios iterations within an application. Cleaning up the SupplierID and CategoryID Columns Currently we are displaying the foreign-key integer values in our GridView for the Supplier and Category of each Product: While accurate from a data model perspective, it isn't very end-user friendly. What I really want to-do is to display the CategoryName and SupplierName instead, and provide a drop-downlist while in Edit mode to enable end-users to easily associate the SupplierID and CategoryID values. I can change the GridView to display the Supplier Name and Category Name instead of the ID's by replacing the default <asp:BoundField> in our GridView with an <asp:TemplateField>. Within this TemplateField I can add any content I want to customize the look of the column. In the source code below I'm going to take advantage of the fact that each Product class in the LINQ to SQL data model we created has a Supplier and Category property on it. What this means is that I can easily databind their Supplier.CompanyName and Category.CategoryName sub-properties within our Grid: And now when I run the application I get the human readable Category and Supplier name values instead: To get drop-down list UI for the Supplier and Category columns while in Edit-Mode in the Grid, I will first add two additional <asp:LinqDataSource> controls to my page. I will configure these to bind against the Categories and Suppliers within the LINQ to SQL data model we created earlier: I can then go back to the <asp:TemplateField> columns we added to our GridView earlier and customize their edit appearance (by specifying an EditItemTemplate). We'll customize each column to have a dropdownlist control when in edit mode, where the available values in the dropdownlists are pulled from the categories and suppliers datasource controls above, and where we two-way databind the selected value to the Product's SupplierID and CategoryID foreign keys: And now when end-users click edit in the GridView, they are presented a drop-down list of all valid Supplier's to associate the product with: And when they hit save the Product is updated appropriately (the GridView will use the DropDownList's currently selected value to bind the SupplierID). Step 4: Filtering our Product Listing Rather than show all products within the database, we can update our UI to include a dropdownlist that allows the user to filter the products by a particular category. Because we already added a <asp:LinqDataSource> control to the page earlier that references our Categories within our LINQ to SQL data model, all I need to-do to create a drop-downlist control at the top of the page that binds against this. For example: When I run the page I'll now get a filter dropdownlist of all categories at the top of the page: My last step is to configure the GridView to only show those Products in the category the end-user selects from the dropdownlist. The easiest way to-do this is by selecting the "Configure DataSource" option in the GridView smart task: This will bring me back to the <asp:LinqDataSource> control's design-time UI that we used at the very beginning of this tutorial. I can select the "Where" button within this to add a binding filter to the datasource control. I can add any number of filter expressions, and declaratively pull the values to filter by from a variety of places (for example: from the querystring, from form-values, from other controls on the page, etc): Above I'm going to choose to filter by the Products by their CategoryID value, and then retrieve this CategoryID from the DropDownList control we just created on our page: When we hit finish, the <asp:linqdatasource> control in our page will have been updated to reflect this filter clause like so: And when we now run the page the end-user will now be able to select from the available Categories in the filter drop-downlist and page, sort, edit and delete just the products in that category: The <asp:LinqDataSource> control will automatically apply the appropriate LINQ filter expression when working against our LINQ to SQL data model classes to ensure that only the required data is retrieved from the database (for example: in the Grid above only the 3 rows of Product data from the second page of Confection products will be retrieved from the database). You can optionally handle the Selecting event on the <asp:LinqDataSource> if you want to write a custom LINQ expression in code to completely customize the query instead. Step 5: Adding Business Validation Rules As I discussed in Part 4 of this LINQ to SQL series, when we define LINQ to SQL data models we will automatically have a default set of schema based validation constraints added to our data model classes. This means that if I try and enter a null value for a required column, try and assign a string to an integer, or assign a foreign-key value to a row that doesn't exist, our LINQ to SQL data model will raise an error and ensure that our database integrity is maintained. Basic schema validation is only a first step, though, and is rarely enough for most real-world applications. Typically we'll want/need to add additional business rules and application-level validation to our data model classes. Thankfully LINQ to SQL makes adding these types of business validation rules easy (for details on the various validation approaches available, please read Part 4 of my LINQ to SQL series). Example Business Validation Rule Scenario For example, let's consider a basic business logic rule we might want to enforce. Specifically, we want to ensure that a user of our application can't discontinue a product while we still have units on backorder for it: If a user tries to save the above row, we'll want to prevent this change from being persisted and throw an appropriate error telling the user how to fix it. Adding a Data Model Validation Rule The wrong place to add this type of business validation rule is in the UI layer of our application. Adding it in the UI layer of our application will mean that the rule will be specific to only that one place, and will not be automatically enforced when we add another page to our application that also updates Products. Distributing business rules/logic in our UI layer will also make life extremely painful as our application grows in size - since changes/updates to our business will necessitate making code changes all over the place. The right place to specify this type of business logic validation is instead in our LINQ to SQL data model classes that we defined earlier. As I discussed in Part 4 of this series, all classes generated by the LINQ to SQL designer are defined as "partial" classes - which means that we can easily add additional methods/events/properties to them. The LINQ to SQL data model classes automatically call validation methods that we can implement to enforce custom validation logic within them. For example, I could add a partial Product class to my project that implements the OnValidate() partial method that LINQ to SQL calls prior to persisting a Product entity. Within this OnValidate() method I could add the following business rule to enforce that products can't have a Reorder Level if the product is discontinued: Once I add the above class into my LINQ to SQL project, the above business rule will be enforced anytime anyone uses my data model to try and modify the database. This is true for both updating existing Products, as well as adding new Products into the database. Because the <asp:LinqDataSource> that we defined in our pages above works against our LINQ to SQL data model classes, all of its update/insert/delete logic will now have to pass the above validation check prior to the change being persisted. We do not need to-do anything to our UI tier in order for this validation to occur - it will automatically be applied anywhere and everywhere our LINQ to SQL data model is used. Adding Nice Error Handling in our UI Tier By default if a user now uses our GridView UI to enter a non-valid UnitsOnOrder/Discontinued combination, our LINQ to SQL data model classes will raise an exception. The <asp:LinqDataSource> will in turn catch this error and provides an event that users can use to handle it. If no one handles the event then the GridView (or other) control bound to the <asp:LinqDataSource> will catch the error and provide an event for users to handle it. If no one handles the error there then it will be passed up to the Page to handle, and if not there to the global Application_Error() event handler in the Global.asax file. Developers can choose any place along this path to insert appropriate error handling logic to provide the right end-user experience. For the application we defined above, probably the best place to handle any update errors is by handling the RowUpdated event on our GridView. This event will get fired every time an update is attempted on our datasource, and we can access the exception error details if the update event fails. We can add the below code to check if an error occurs, and if so display an appropriate error message to the end-user: Notice above how we have not added any validation specific logic into our UI. Instead, I am retrieving the validation error message string we raised in our business logic and am using it to display an appropriate message to the end-user (I am then displaying a more generic error message in the event of other failures). Notice how I'm also indicating above that I want the GridView to stay in Edit mode when an error occurs - that way the user can avoid losing their changes, and can modify the values they entered and click "update" again to try and save them. We can then add a <asp:literal> control with the "ErrorMessage" ID anywhere we want on our page to control where where we want the error message to be displayed: And now when we try and update the Product with an invalid value combination we'll see an error message indicating how to fix it: The nice thing about using this approach is that I can now add or change my data model's business rules and not have to modify any of my UI tier's code to have them pick up and honor the changes. The validation rules, and corresponding error messages, can be written and centralized in one place in my data model and automatically applied everywhere. Summary The <asp:LinqDataSource> control provides an easy way to bind any ASP.NET UI control to a LINQ to SQL data model. It enables UI controls to both retrieve data from a LINQ to SQL data model, as well as cleanly apply updates/inserts/deletes to it. In our application above we used the LINQ to SQL ORM designer to create a clean, object oriented data model. We then added three ASP.NET UI controls to our page (a GridView, a DropDownList, and a ErrorMessage Literal), and added three <asp:LinqDataSource> controls to bind Product, Category, and Supplier data from it: We then wrote 5 lines of business validation logic in our data model, and 11 lines of UI error handling logic. The end result is a simple web application with custom UI that allows users to dynamically filter product data by category, efficiently sort and page over the product results, inline-edit the product data to save updates (providing our business rules pass), and delete products from the system (also providing our business rules allow it). In future posts in this series I'll cover more LINQ to SQL scenarios including optimistic concurrency, lazy and eager loading, table mapping inheritance, and custom SQL/SPROC usage. Next week I also plan to start a new series of blog posts that cover the new <asp:ListView> control - which is a new control that will ship with the ASP.NET release in .NET 3.5. It provides total control over the markup generated for data scenarios (no tables, no spans, no inline styles...), while also delivering built-in support for paging, sorting, editing, and insertion scenarios. For example, we could optionally use it to replace the default Grid layout look of our application above with a completely custom look and feel. Best of all, I could replace it within the above page in my application and not have to change my Data Model, the <asp:linqdatasource> declaration, or my code-behind UI error handling logic at all. Hope this helps, Scott 
|
-
Come join Fritz Onion and myself at a Pluralsight double feature in southern California. Starting October on 22nd, we'll cover everything from JSON spitting web services to the Sharepointy magic of ASP.NET 2.0 web parts.
It's more than a class … it's an experience (and fun, too)!

|
-
Raymond tags me in every blogging meme, which is great. If it wasn't for Raymond, I wouldn't get to play along.
The current meme is "what I will do to be a better developer in the next 6 months". Bettering is a tough topic to write about, because there are so many ways to get better.
Interviewing Skills
Not interviewing for jobs, but interviewing candidates. Although interviewing isn't strictly a development job – it is a job I am occasionally tasked to do. Good interviewing skills can help you build a great team and contribute to the success of a project and a company. The truth is – I have terrible interviewing skills. My record shows I'm too optimistic about candidates. If left to build a team on my own, I'd end up with something that resembles the 1976 Buccaneers. I need to prepare better, and have a plan in place to dig deeper in interviews.
Forge Ahead
I feel like I've spent the last 6 months playing catch up on some old technologies (these days – old technology is anything released over 6 months ago – legacy technology is anything released over 18 months ago). While I was catching up to get work done on current projects, exciting changes began to loom on the horizon. LINQ comes to mind as a technology that I think will be huge, and I want to be ready before the next application comes along.
Build Something New
I learn the most when I build working software. To forge ahead I really need to set aside some time, put together some ideas, and build something new. Actually, I do have an idea for a new web site- and one wholly unrelated to technology. The technology I'll use to build the web site? ASP.NET. It's fashionable these days to criticize ASP.NET as a leaky, heavyweight, complicated beast, but I believe it's easy to poke holes in any non-trivial platform. ASP.NET is what you make of it. If you want to swim against the current and make ASP.NET be difficult - it will be difficult. I can't leave the huge feature set, the range of extensibility, and the strong foundation of the CLR and the framework class libraries.
But enough fanboy racket – I gotta build some software, and hopefully have time to blog about it, too.
Tag
Four people, picked at random people from my techie OPML list:
Wayward LINQ Lacky Matt Warren New and Notable Sam Gentile Master Microsoft Interviewer Chris Sells Carnage4Life aka Dare Obasanjo
Will they play the game, too?

|
-
A knock came on the door today and it was my MacBook Pro fresh from Shanghai. I have been playing with it all day and getting everything backed up and ready to move over from my PC. I am supremely impressed.
From a hardware standpoint there is nothing out there in the windows world that can compete. Its thin, light, and incredible fast. (I am sure the 4gigs of memory helps).
From a software standpoint I am very impressed with OS X, this is what Vista should have been. Elegant, Simple, and fun to use. Lots of interesting new applications to play with (using Ecto to post right now).
I am working on copying over my VMWare images from my Alienware (which will soon be on ebay) and already have VMWare Fusion setup and waiting.
-James

|
-
Over the last few weeks I've been writing a series of blog posts that cover LINQ to SQL. LINQ to SQL is a built-in O/RM (object relational mapper) that ships in the .NET Framework 3.5 release, and which enables you to easily model relational databases using .NET classes. You can use LINQ expressions to query the database with them, as well as update/insert/delete data. Below are the first three parts of my LINQ to SQL series: In today's blog post I'll cover how we we can use the data model we created earlier, and use it to update, insert, and delete data. I'll also show how we can cleanly integrate business rules and custom validation logic with our data model. Northwind Database Modeled using LINQ to SQL In Part 2 of this series I walked through how to create a LINQ to SQL class model using the LINQ to SQL designer that is built-into VS 2008. Below is a class model created for the Northwind sample database and which I'll be using in this blog post:
When we designed our data model using the LINQ to SQL data designer above we defined five data model classes: Product, Category, Customer, Order and OrderDetail. The properties of each class map to the columns of a corresponding table in the database. Each instance of a class entity represents a row within the database table. When we defined our data model, the LINQ to SQL designer also created a custom DataContext class that provides the main conduit by which we'll query our database and apply updates/changes. In the example data model we defined above this class was named "NorthwindDataContext". The NorthwindDataContext class has properties that represent each Table we modeled within the database (specifically: Products, Categories, Customers, Orders, OrderDetails). As I covered in Part 3 of this blog series, we can easily use LINQ syntax expressions to query and retrieve data from our database using this NorthwindDataContext class. LINQ to SQL will then automatically translate these LINQ query expressions to the appropriate SQL code to execute at runtime. For example, I could write the below LINQ expression to retrieve a single Product object by searching on the Product name:
I could then write the LINQ query expression below to retrieve all products from the database that haven't yet had an order placed for them, and which also cost more than $100:
Note above how I am using the "OrderDetails" association for each product as part of the query to only retrieve those products that have not had any orders placed for them. Change Tracking and DataContext.SubmitChanges() When we perform queries and retrieve objects like the product instances above, LINQ to SQL will by default keep track of any changes or updates we later make to these objects. We can make any number of queries and changes we want using a LINQ to SQL DataContext, and these changes will all be tracked together. Note: LINQ to SQL change tracking happens on the consuming caller side - and not in the database. This means that you are not consuming any database resources when using it, nor do you need to change/install anything in the database to enable it. After making the changes we want to the objects we've retrieved from LINQ to SQL, we can then optionally call the "SubmitChanges()" method on our DataContext to apply the changes back to the database. This will cause LINQ to SQL to dynamically calculate and execute the appropriate SQL code to update the database. For example, I could write the below code to update the price and # of units in stock of the "Chai" product in the database:
When I call northwind.SubmitChanges() above, LINQ to SQL will dynamically construct and execute a SQL "UPDATE" statement that will update the two product property values we modified above. I could then write the below code to loop over unpopular, expensive products and set the "ReorderLevel" property of them to zero:
When I call northwind.SubmitChanges() above, LINQ to SQL will calculate and execute an appropriate set of UPDATE statements to modify the products who had their ReorderLevel property changed. Note that if a Product's property values weren't changed by the property assignments above, then the object would not be considered changed and LINQ to SQL would therefore not execute an update for that product back to the database. For example - if the "Chai" product's unitprice was already $2 and the number of units in stock was 4, then calling SubmitChanges() would not cause any database update statements to execute. Likewise, only those products in the second example whose ReorderLevel was not already 0 would be updated when the SubmitChanges() method was called. Insert and Delete Examples In addition to updating existing rows in the database, LINQ to SQL obviously also enables you to insert and delete data. You can accomplish this by adding/removing data objects from the DataContext's table collections, and by then calling the SubmitChanges() method. LINQ to SQL will keep track of these additions/removals, and automatically execute the appropriate SQL INSERT or DELETE statements when SubmitChanges() is invoked. Inserting a New Product I can add a new product to my database by creating a new "Product" class instance, setting its properties, and then by adding it to my DataContext's "Products" collection:
When we call "SubmitChanges()" above a new row will be created in our products table. Deleting Products Just as I can express that I want to add a new Product to the database by adding a Product object into the DataContext's Products collection, I can likewise express that I want to delete a product from a database by removing it from the DataContext's Products collection:
Note above how I'm retrieving a sequence of discontinued products that no one has ever ordered using a LINQ query, and then passing it to the RemoveAll() method on my DataContext's "Products" collection. When we call "SubmitChanges()" above all of these Product rows will be deleted from our products table. Updates across Relationships What makes O/R mappers like LINQ to SQL extremely flexible is that they enable us to easily model cross-table relationships across our data model. For example, I can model each Product to be in a Category, each Order to contain OrderDetails for line-items, associate each OrderDetail line-item with a Product, and have each Customer contain an associated set of Orders. I covered how to construct and model these relationships in Part 2 of this blog series. LINQ to SQL enables me to take advantage of these relationships for both querying and updating my data. For example, I could write the below code to create a new Product and associate it with an existing "Beverages" category in my database like so:
Note above how I'm adding the Product object into the Category's Products collection. This will indicate that there is a relationship between the two objects, and cause LINQ to SQL to automatically maintain the foreign-key/primary key relationship between the two when I call "SubmitChanges()". For another example of how LINQ to SQL can help manage cross-table relationships for us and help clean up our code, let's look at an example below where I'm creating a new Order for an existing customer. After setting the required ship date and freight costs for the order, I then create two order line-item objects that point to the products the customer is ordering. I then associate the order with the customer, and update the database with all of the changes.
As you can see, the programming model for performing all of this work is extremely clean and object oriented. Transactions A transaction is a service provided by a database (or other resource manager) to guarantee that a series of individual actions occur atomically - meaning either they all succeed or they all don't, and if they don't then they are all automatically undone before anything else is allowed to happen. When you call SubmitChanges() on your DataContext, the updates will always be wrapped in a Transaction. This means that your database will never be in an inconsistent state if you perform multiple changes - either all of the changes you've made on your DataContext are saved, or none of them are. If no transaction is already in scope, the LINQ to SQL DataContext object will automatically start a database transaction to guard updates when you call SubmitChanges(). Alternatively, LINQ to SQL also enables you to explicitly define and use your own TransactionScope object (a feature introduced in .NET 2.0). This makes it easier to integrate LINQ to SQL code with existing data access code you already have. It also means that you can enlist non-database resources into the transaction - for example: you could send off a MSMQ message, update the file-system (using the new transactional file-system support), etc - and scope all of these work items in the same transaction that you use to update your database with LINQ to SQL. Validation and Business Logic One of the important things developers need to think about when working with data is how to incorporate validation and business rule logic. Thankfully LINQ to SQL supports a variety of ways for developers to cleanly integrate this with their data models. LINQ to SQL enables you to add this validation logic once - and then have it be honored regardless of where/how the data model you've created is used. This avoids you having to repeat logic in multiple places, and leads to a much more maintainable and clean data model. Schema Validation Support When you define your data model classes using the LINQ to SQL designer in VS 2008, they will by default be annotated with some validation rules inferred from the schema of the tables in the database. The datatypes of the properties in the data model classes will match the datatypes of the database schema. This means you will get compile errors if you attempt to assign a boolean to a decimal value, or if you attempt to implicitly convert numeric types incorrectly. If a column in the database is marked as being nullable, then the corresponding property in the data model class created by the LINQ to SQL designer will be a nullable type. Columns not marked as nullable will automatically raise exceptions if you attempt to persist an instance with a null value. LINQ to SQL will likewise ensure that identity/unique column values in the database are correctly honored. You can obviously use the LINQ to SQL designer to override these default schema driven validation settings if you want - but by default you get them automatically and don't have to take any additional steps to enable them. LINQ to SQL also automatically handles escaping SQL values for you - so you don't need to worry about SQL injection attacks when using it. Custom Property Validation Support Schema driven datatype validation is useful as a first step, but usually isn't enough for real-world scenarios. Consider for example a scenario with our Northwind database where we have a "Phone" property on the "Customer" class which is defined in the database as an nvarchar. Developers using LINQ to SQL could write code like below to update it using a valid telephone number: The challenge that we will run into with our application, however, is that the below code is also legal from a pure SQL schema perspective (because it is still a string even though it is not a valid phone number): To prevent bogus phone numbers from being added into our database, we can add a custom property validation rule to our Customer data model class. Adding a rule to validate phone numbers using this feature is really easy. All we need to-do is to add a new partial class to our project that defines the method below: The code above takes advantage of two characteristics of LINQ to SQL: 1) All classes created by the LINQ to SQL designer are declared as "partial" classes - which means that developers can easily add additional methods, properties, and events to them (and have them live in separate files). This makes it very easy to augment the data model classes and DataContext classes created by the LINQ to SQL designer with validation rules and additional custom helper methods that you define. No configuration or code wire-up is required. 2) LINQ to SQL exposes a number of custom extensibility points in its data model and DataContext classes that you can use to add validation logic before and after things take place. Many of these extensibility points utilize a new language feature called "partial methods" that is being introduced with VB and C# in VS 2008 Beta2. Wes Dyer from the C# team has a good explanation of how partial methods works in this blog post here. In my validation example above, I'm using the OnPhoneChanging partial method that is executed anytime someone programmatically sets the "Phone" property on a Customer object. I can use this method to validate the input however I want (in this case I'm using a regular expression). If everything passes successfully, I just return from the method and LINQ to SQL will assume that the value is valid. If there are any issues with the value, I can raise an exception within the validation method - which will prevent the assignment from taking place. Custom Entity Object Validation Support Property level validation as used in the scenario above is very useful for validating individual properties on a data model class. Sometimes, though, you want/need to validate multiple property values on an object against each other. Consider for example a scenario with an Order object where you set both the "OrderDate" and the "RequiredDate" properties: The above code is legal from a pure SQL database perspective - even though it makes absolutely no sense for the required delivery date of the new order to be entered as yesterday. The good news is that LINQ to SQL in Beta2 makes it easy for us to add custom entity level validation rules to guard against mistakes like this from happening. We can add a partial class for our "Order" entity and implement the OnValidate() partial method that will be invoked prior to the entity's values being persisted into the database. Within this validation method we can then access and validate all of the data model class properties: Within this validation method I can check any of the entity's property values (and even obtain read-only access to its associated objects), and raise an exception as needed if the values are incorrect. Any exceptions raised from the OnValidate() method will abort any changes from being persisted in the database, and rollback all other changes in the transaction. Custom Entity Insert/Update/Delete Method Validation There are times when you want to add validation logic that is specific to insert, update or delete scenarios. LINQ to SQL in Beta2 enables this by allowing you to add a partial class to extend your DataContext class and then implement partial methods to customize the Insert, Update and Delete logic for your data model entities. These methods will be called automatically when you invoke SubmitChanges() on your DataContext. You can add appropriate validation logic within these methods - and if it passes then tell LINQ to SQL to continue with persisting the relevant changes to the database (by calling the DataContext's "ExecuteDynamicXYZ" method): What is nice about adding the above methods is that the appropriate ones are automatically invoked regardless of the scenario logic that caused the data objects to be created/updated/deleted. For example, consider a simple scenario where we create a new Order and associate it with an existing Customer: When we call northwind.SubmitChanges() above, LINQ to SQL will determine that it needs to persist a new Order object, and our "InsertOrder" partial method will automatically be invoked. Advanced: Looking at the Entire Change List for the Transaction There are times when adding validation logic can't be done purely by looking at individual insert/update/delete operations - and instead you want to be able to look at the entire change list of operations that are occurring for a transaction. Starting with Beta2 of .NET 3.5, LINQ to SQL now enables you to get access to this change list by calling the public DataContext.GetChangeList() method. This will return back a ChangeList object that exposes collections of each addition, removal and modification that has been made. One approach you can optionally employ for advanced scenarios is to sub-class the DataContext class and override its SubmitChange() method. You can then retrieve the ChangeList() for the update operation and perform any custom validation you want prior to executing it: The above scenario is a somewhat advanced one - but it is nice to know that you always have the ability to drop-down and take advantage of it if needed. Handling Simultaneous Changes with Optimistic Concurrency One of the things that developers need to think about in multi-user database systems is how to handle simultaneous updates of the same data in the database. For example, assume two users retrieve a product object within an application, and one of the users changes the ReorderLevel to 0 while the other changes it to 1. If both users then attempt to save the product back to the database, the developer needs to decide how to handle the change conflicts. One approach is to just "let the last writer win" - which means that the first user's submitted value will be lost without the end-users realizing it. This is usually considered a poor (and incorrect) application experience. Another approach which LINQ to SQL supports is to use an optimistic concurrency model - where LINQ to SQL will automatically detect if the original values in the database have been updated by someone else prior to the new values being persisted. LINQ to SQL can then provide a conflict list of changed values to the developer and enable them to either reconcile the differences or provide the end-user of the application with UI to indicate what they want to-do. I'll cover how to use optimistic concurrency with LINQ to SQL in a future blog post. Using SPROCs or Custom SQL Logic for Insert/Update/Delete Scenarios One of the questions that developers (and especially DBAs) who are used to writing SPROCs with custom SQL usually ask when seeing LINQ to SQL for the first time is - "but how can I have complete control of the underlying SQL that is executed?" The good news is that LINQ to SQL has a pretty flexible model that enables developers to override the dynamic SQL that is automatically executed by LINQ to SQL, and instead call custom insert, update, delete SPROCs that they (or a DBA) define themselves. What is really nice is that you can start off by defining your data model and have LINQ to SQL automatically handle the insert, update, delete SQL logic for you. You can then at a later point customize the data model to use your own custom SPROCs or SQL for updates - without having to change any of the application logic that is using your data model, nor would you have to change any of the validation or business rules logic supporting it (all of this stays the same). This provides a lot of flexibility in how you build your application. I'll cover how to customize your data models to use SPROCs or custom SQL in a future blog post. Summary Hopefully the above post provides a good summary of how you can easily use LINQ to SQL to update your database, and cleanly integrate validation and business logic with your data models. I think you'll find that LINQ to SQL can dramatically improve your productivity when working with data, and enable you to write extremely clean object-oriented data access code. In upcoming blog posts in this series I'll cover the new <asp:linqdatasource> control coming in .NET 3.5, and talk about how you can easily build data UI in ASP.NET that takes advantage of LINQ to SQL data models. I'll also cover some more specific LINQ to SQL programming concepts including optimistic concurrency, lazy and eager loading, table mapping inheritance, custom SQL/SPROC usage, and more. Hope this helps, Scott 
|
-
If you are a heavy user of remote desktop connections, and you haven't tried Terminals, then give this free, open source utility from CodePlex a try.
"Terminals is a multi tab terminal services/remote desktop client. It uses Terminal Services ActiveX Client (mstscax.dll). The project started from the need of controlling multiple connection simultaneously."
One of the great features in Terminals is the ability to set up a "group". One click on a group can open multiple RDP sessions at once. Terminals can also auto-scale a remote desktop to the window size, and setup a default desktop share for drag and drop operations into the remote desktop window.
Tip: If you are using a nonstandard port for RDP, don't enter the port number with the computer name (machine.foo.com:3399). This syntax doesn't work in Terminals. Instead, enter the port in the Remote Server Port textbox on the Advanced settings tab.

|
-
Since I am down here in Raleigh relaxing I decided to hook up the Wii and see what games were available for download, I of course downloaded Super Mario Bros and showed my wife how you could warp from 1-2 to 4-1, but then screwed up the second warp and went to 5 instead of 8. Oh well, she still said I was cool. With the other half of my 1000 credits I downloaded Zelda II: The Adventure of Link. I forgot what a great game this was. I downloaded this one because I never did beat it, back in the day I got stuck on one of the bosses and never finished it. My new number 1 goal in July is to beat this game, it's not looking good though because I already had to check a FAQ to remember what I need to do to find the damn candle or hammer. This game has reminded me of a couple things about old video games that new video games just don't match: 1) It's hard. New games like to give you a couple hours of gameplay that any semi-competant four year old could handle. This game really doesnt. You can't just hack your way through, the first palace you fight through will tear you up if you get lazy. 2) No big movies or other crap. Sure they look nice, but I forgot how cool it was to start a game and start to play right away. You go to a new town or fight an enemy all you get is a flash of the screen and some simple music. 3) No load times. I never sit there and wait, unless its because I forgot you have to use the select and start keys. I can see myself dropping some money on the Wii, they sure don't make em like they used to. ;) -James 
|
-
At the end of the last post, we looked at a function named createDelegate. The createDelegate function constructed a nested function named shim, and shim created all the magic we needed to invoke an object's method during a button click event. In this post we'll finally put the topic to rest.
First, we have to cover an important topic: scope.
Scope
A variable's scope defines where the variable can be used. In JavaScript there is really only local scope and global scope. Notice that local variables will hide global variables of the same name.
var x = 10;
function f()
{
{
// no block scope in ECMAScript -
// this x is available everywhere inside f()
var x = 20;
}
alert(x);
}
f(); // this displays 20
alert(x); // this displays 10
Nesting a function inside a function is essentially nesting a local scope inside a local scope. Note that functions have access to all the variables and arguments in all their ancestor's scopes (as long as the variables aren't hidden by a local variable).
var x = 10;
function f()
{
var y = 15;
function g()
{
var z = 25;
alert(x+y+z);
}
g();
}
f(); // this displays 50
The above behavior is what we expect after reading section 10 of the ECMAScript standard. JavaScript creates a new activation object for each scope. The activation object references all function arguments and variables in the scope. The activation objects become part of a scope chain that JavaScript will traverse when trying to find a variable. The following diagram is a conceptual model of all these players, with red brackets indicating scope, red circles indicating activation objects, and blue lines indicating the scope chain.
When we ask for the value of x inside function g(), JavaScript looks at activation object for the innermost scope, but doesn't find x, so it moves to the parent scope, but still doesn't find x. Finally, the runtime looks at the global scope and finds x. If the engine had found x in a nested scope, it wouldn't have gotten to the x in the global scope.
Knowing what we know now, what does the following code display?
var x = 10;
function printIt(y)
{
function doAlert()
{
alert(x+y)
}
doAlert();
}
printIt(5);
The answer is 15. The innermost function has access to both the incoming y parameter of printIt and the global variable x thanks to the scope chain. Now, let's add a twist.
Closures
Instead of having the printIt function invoke doAlert, let's return doAlert as an object and execute the function from global scope.
var x = 10;
var y = 20;
function makePrintIt(y)
{
return function doAlert()
{
alert(x+y)
}
}
var f = makePrintIt(5);
f();
Returning a function object creates a closure, which Wikipedia defines as "a function paired with an environment". Generally speaking, when a function like makePrintIt() exits, all the local variables and arguments are lost. A closure, however, closes over its environment and keeps these local variables and arguments alive. The function captures its execution environment.
Looking at our conceptual diagram above, it's easy to see how a JavaScript engine might implement a closure*. All a nested function has to do is carry a reference to its activation object, which will keep all the variables and arguments in the scope chain alive.
If you've gotten a good grip on closures, then you'll realize the last code snippet will display 15. Since doAlert captured its execution environment, it will use the y value of 5 that was passed into makePrintIt, not the y value of 20 that exists at global scope. Thanks to closures, JavaScript functions always execute with their lexical scope (where they appear in the source code).
Finally, every call into makePrintIt() creates a new closure by pairing a function object with its unique execution environment. That means the following code prints 10, then 15.
var x = 5;
function makePrintIt(y)
{
return function doAlert()
{
alert(x+y)
}
}
var f1 = makePrintIt(5);
var f2 = makePrintIt(10);
f1();
f2();
With this understanding of closures, I hope you can look at the implementation of Function.createDelegate and understand what is happening!
* The ECMAScript standard only describes how the interpreter has to behave. How scope chains and closures are actually realized is an implementation detail. 
|
-
It's done! I am down in Raleigh in our empty little apartment (we are waiting to move all our furniture down until the house sells). I have about a month off before my next gig starts, and here is some of the stuff I plan on working on: 1) Relaxing. I was on a pretty big project for almost two years, I need some solid rest and relaxation. The apartment has a nice pool, and the beach is only a couple hours away. This shouldn't be tough. 2) CE. That is all I will call it for now but it's my main side project. I have a couple partners and I want to make sure they are fine with me talking about it here. I think with a week or two of solid work I can get it into Beta which would be a major step. (we have been working on it for over a year) 3) Playing with my MacBook Pro. Yeah, I broke down and ordered one. I plan on running OS X and then XP in VMWare, it's not that different from my current setup since I do all my development in VMWare. 4) FeedZerk. This is a little ruby on rails app I have been playing around with off and on for awhile, I think I could get it up and running in a week or so if I had time to dedicate to it. I am going to wait till the MBP comes in so I can get used to TextMate. 5) Blogging. I have so much to blog, 7 drafts so far. -James 
|
-
"Master Page" support was one of the most popular features introduced with ASP.NET 2.0, and is one of those features that almost every new ASP.NET project now uses to deliver consistent layout template support across a web site. One of the cooler scenarios that ASP.NET 2.0 supports is the ability to have "nested master pages" - where you can create a root master page for a site that defines a site's overall layout, and then create nested master pages that are based on the root master and further customize the layout (for example: you could create a SingleColumn.Master and TwoColumn.Master that defined 1 or 2 column layout structures based on the root master template). This nested master page feature is extremely flexible, and enables developers and designers to quickly and very cleanly make changes to the layout and organization of a site with minimal code changes and no content duplication. The one (big) catch, though, is that Visual Studio 2005 doesn't really support using nested master pages, and pages based on nested masters can't be edited within the VS 2005 WYSIWYG designer. The good news is that VS 2008 fully supports nested master pages, and makes using them super easy. Going forward I recommend that almost all ASP.NET projects should advantage of this feature - since it can add tremendous flexibility to the UI of your projects. Using Nested Master Pages With VS 2008 One of the sites I recommend checking out is http://www.opensourcetemplates.org/. This is an online repository of free HTML site templates that you can browse, download and use. The templates on the site are pure HTML (meaning you can use them with any server-side programming technology), and are built using clean CSS and XHTML markup: To help with this blog post, I picked one of the templates that I thought looked nice. You can browse it online here, and download it here. Like most web-sites out there, this template has pages that utilize a few different layout approaches for displaying content. For example, it includes a page that uses multiple-columns to layout content: It also has pages that use a single column approach that fills the entire width of the page with content: Using the Above HTML/CSS Template with Nested Master Pages Converting the above template to use ASP.NET and its nested Master Page support is really easy with VS 2008. Step 1: Create a Site.Master template To begin with we can create a new root master page file that we'll use to define the overall layout and structure for all pages on the site. We'll name this file "Site.Master" and copy/paste the "outer chrome" HTML from the template we downloaded into it. We'll then add a <asp:contentplaceholder> into the content section in the middle where we'll fill in page specific content. We'll name this <asp:contentplaceholder> control "MainContent": Step 2: Create SingleColumn.Master Template We used our Site.Master template above to define the "outer chrome template" of the site we are working on. We'll now want to create a few nested master pages that provide further templates that customize the layout of the "MainContent" section. To do this we can right-click in the solution explorer and choose the "Add New Item" menu option. We'll create a new Master Page called "SingleColumn.Master" and will want to make sure that the checkbox indicating that we want to base this master page off a parent master page is selected: VS 2008 will then allow us to pick the Site.Master template as the master page we want to base this new SingleColumn.master template on: VS 2008 will then create a new SingleColumn.master file that looks like below: Notice above how VS 2008 has picked up the fact that we defined a <asp:contentplaceholder> control in the root Site.Master file called "MainContent" - and automatically added a blank <asp:content> control within this nested master page so that we can override and customize that content region. Also notice above how we can use the new "Split View" support within VS 2008 to enable us to see both the HTML source and WYSIWYG designer surface at the same time. We can make changes within either of the split views, and immediately see the changes applied in the other (hint: make sure to show your boss this new feature when asking for a bigger monitor). Our SingleColumn.Master template is going to end up being really simple to begin with, and will just add a CSS rule to define the width of the single column of content - and then add its own <asp:contentplaceholder> control so that pages based off of this master can fill in their page specific content: Step 3: Create TwoColumn.Master Template In addition to having our SingleColumn.Master template, we'll want to create a second nested master page template to handle two columns of content. We'll repeat the steps we followed above - but this time call the file "TwoColumn.Master". We'll define the layout of this file like below: Notice above how we have added two <asp:contentplaceholder> controls within this nested master page - one called "MainColumn" (just like the SingleColumn.Master), and the other called "LeftColumn" (to handle a smaller column of content that will be displayed on the left of the page). We'll use standard HTML and CSS to position these two columns. Step 4: Creating Content Pages using our Nested Master Pages Now that we've defined master pages to control our site's layout structure, we can start adding pages to the site. Let's create a new page that we'll call "HomePage.aspx" - and indicate that we want it to be based on a master page: We can then choose which master page or nested master page we want to base it on. For the home-page let's use the two column layout: VS 2008 will then base HomePage.aspx on this nested master file, and add two empty <asp:content> controls to the page that allows us to fill in the left and main column content for the page: Notice above how we not only get WYSIWYG support for pages built using nested master pages, but we can also use split-view with them. I can then fill in the specific content I want into the appropriate <asp:content> regions, and add any code I want to the code-behind: I can later add additional pages to the project, and base them on either the SingleColumn.Master or TwoColumn.Master template. Because both of these templates are based on a root Site.Master template, if I make any changes to this root template (for example: I want to change the top logo or navigation structure), it will automatically apply to all pages within the site without me having to modify them at all. I also now have the flexibility to change the layout of the SingleColumn or TwoColumn templates (for example: adjusting their width) and all of the pages on the site that are built with the modified master templates will immediately have the changes applied. Summary VS 2008 has full support for using ASP.NET nested master pages (this feature is also fully supported with the free Visual Web Developer Express 2008 edition). I think you'll find that this makes building consistent UI and site layout much easier. Best of all, because VS 2008 now has multi-targeting support you'll be able to use the above feature immediately without having to install .NET 3.5 on your servers. You can open existing ASP.NET 2.0 projects in VS 2008, have VS 2008 continue to target .NET 2.0 as the runtime target, and start using this feature. Hope this helps, Scott 
|
-
My Toolbox column in the July 2007 issue of MSDN Magazine is avaiable online. The July issue examines three products:
- ANTS Profiler - quickly and easily find performance and memory bottlenecks in your .NET applications with this helpful tool.
- Simian - duplicate source code can happen when developers cut and paste code. Such repetitious code is dangerous because if there is a bug in the duplicated code or if the business logic is changed, problems will arise unless all duplications of the code are appropriately modified. Simian can efficiently search through millions of lines of source code and alert you if it finds any duplicate blocks of code.
- Pixie - a free, light-weight color picker.
This month's issue reviewed Foundations of Security, by Neil Daswani et al. Here is an excerpt from the review:
Security requires planning and domain knowledge and its results are not easily measurable. Furthermore, since security spans physical, technological, and policy levels, it is easy for a developer to bury her head in the sand and assume someone else will implement or has implemented the necessary security precautions. Such attitudes, however, are an invitation to disaster. Security is an important aspect of any application and all developers should have at least a cursory understanding of key security concepts, potential attack vectors, and techniques for protecting against common threats. Foundations of Security: What Every Programmer Needs to Know (Apress, 2007), ... provides a solid overview of security fundamentals at a level appropriate for developers who may have little to no background in security.
As always, if you have any suggestions for products or books to review for the Toolbox column, please send them into toolsmm@microsoft.com.
|
-
In the last post I demonstrated how you can fiddle with the this reference during a method invocation using Function.call and Function.apply. After reading that post, you should understand why Function.apply was the most interesting method to us. It's because we can use apply() to specify the this reference for an arbitrary target method, and also pass-through an argument list to that target method via the arguments identifier.
With the above understanding in place, let's look at the following code.
<input type="button" id="submitButton" value="Press Me!" />
<script type="text/javascript">
function MagicButtonManager(buttonId, message)
{
this._message = message;
var btn = document.getElementById(buttonId);
btn.onclick = // what do we here do here?
}
MagicButtonManager.prototype.showMessage = function()
{
alert(this._message);
}
var m = new MagicButtonManager('submitButton', 'Hello World!');
</script>
How do we get the onclick event to invoke our showMessage() method using the correct this reference? We've already seen this approach doesn't work:
btn.onclick = this.showMessage;
Inside of showMessage(), the this reference will point to the submit button instead of a MagicButtonManager instance, and this._message will be undefined. We've assigned a function object to the onclick event. The button does not invoke that function through an instance of the MagicButtonManger (which would correctly setup the this reference) - it just directly invokes that function.
What we need to do is trick the button into calling showMessage via our instance of the MagicButtonManager, right? As in: manager.showMessage();. Unfortunately, the only thing the event handler knows how to do is invoke a function. It doesn't know how, given an object, to "dot operate" (did I just invent a verb?)
and invoke a specific method on that object. Here then, is what we know so far:
- We need to give the button a function object to invoke.
- To setup the correct this reference for showMessage(), we don't necessarily need to invoke showMessage via a MagicButtonManager instance - we can also use Function.apply().
What our createDelegate function was doing in a previous post (and what the ASP.NET AJAX Function.createDelegate method essentially does), is this:
function createDelegate(object, method)
{
var shim = function()
{
method.apply(object, arguments);
}
return shim;
}
// ...
btn.onclick = createDelegate(this, this.showMessage);
Here we are creating a new function object, a shim if you will. When this shim is invoked, it will use apply() on the incoming method parameter, which invokes that specified method. The shim will pass object as the this reference for apply to setup, and the shim does a "pass-through" of all its incoming arguments using the arguments identifier.
The createDelegate function returns a shim as a result. We can assign the return value of createDelegate to an event, so the event can invoke the shim function. When the event fires and shim executes, our this reference is correct thanks to the magic of apply.
Everything works now. Thank you, and goodnight.
What's that? Something doesn't make sense?
We've covered apply and arguments in great detail, so I assume if you are sticking around you might be puzzled by the shim function. How does shim remember the method and object parameters? Since method and object are arguments to createDelegate - don't they go out of scope when createDelegate exits on the closing curly brace? Aren't those function arguments blown away with the crackling pop of a stack frame? Wouldn't those arguments be long gone by the time the button event executes the shim function?
Hang on for one more post...

|
-
In order to explain how the createDelegate function works in the
last post, we have to understand JavaScript closures and Function.apply().
The apply() method is the easiest subject to tackle, so we'll start there and work up.
Every function in JavaScript has a number of attached methods, including toString(),
call(), and apply(). If it sounds odd to you that a function might
have its own methods - then remember that every function in JavaScript is an object.
Read this article for a refresher.
You might also wonder what the difference is between a function and a method. I
believe the descriptors 'function' and 'method' are just a JavaScript convention.
Functions stand on their own (there is an alert() function,
for example),
while methods are functions inside an object's dictionary, and we invoke them through
the object reference. Every JavaScript object has a toString()
method,
for example, and we can use the toString() method on a function object
to see its source code:
function foo()
{
alert('x');
}
alert(foo.toString());
Because functions are objects they can have their own properties and methods, and
we can treat them like data. "Functions as data" is important to remember for the
next post, too, but for now we'll focus on two of a function's methods: apply(),
and its counterpart: call().
Let's start with the following code:
var x = 10;
function f()
{
alert(this.x);
}
f();
Here we have a global function by the name of f(). f() uses the this
keyword to reference x, but notice we don't invoke the function through an instance of an object.
So what object does this reference? this will reference the global
object. The global object is where we defined the variable x. The above code does
work and will show the value 10 in a dialog.
Both call() and alert() are methods we can use to assign the this
pointer for the duration of a method invocation. As an example, here is how we could use the call()
method:
var x = 10;
var o = { x: 15 };
function f()
{
alert(this.x);
}
f();
f.call(o);
The first invocation of f() will display the value of 10, because this references the global object. The second invocation (via the call
method) however, will display the value 15. 15 is the value of the x property inside object
o. The call() method invokes the function and uses its first parameter
as the this pointer inside the body of the function. In other words - we've told the runtime what object
to reference as this while executing inside of function f().
Fiddling with the
this pointer might sound funny, even perverse, to C++, Java, and C# programmers.
What's next? Dogs sleeping with cats? Working nVidia drivers for Windows Vista?
It's all part of the fun that is ECMAScript.
We can also pass arguments to the target function via call():
var x = 10;
var o = { x: 15 };
function f(message)
{
alert(message);
alert(this.x);
}
f("invoking f");
f.call(o, "invoking f via call");
The apply() method is identical to call(), except apply()
requires an array as the second parameter. The array represents the arguments for
the target method.
var x = 10;
var o = { x: 15 };
function f(message)
{
alert(message);
alert(this.x);
}
f("invoking f");
f.apply(o, ["invoking f through apply"]);
The apply() method is useful because we can build a function like createDelegate
(from the last post) that doesn't care about the signature of the target method.
The function can use apply() to pass all additional arguments to the target
method via an array. Are we getting close to a
curry function?
var o = { x: 15 };
function f1(message1)
{
alert(message1 + this.x);
}
function f2(message1, message2)
{
alert(message1 + (this.x * this.x) + message2);
}
function g(object, func, args)
{
func.apply(object, args);
}
g(o, f1, ["the value of x = "]);
g(o, f2, ["the value of x squared = ", ". Wow!"]);
The problem here is the awkward syntax. We are forcing the caller to stuff arguments
into an array just so we call apply(). Fortunately, there is a way to make
the syntax easier, but we have to introduce one more topic: the arguments
identifier.
In JavaScript, every function essentially has a variable length argument list. The
means we can pass 5 parameters to a function even if the function only uses one
argument. The following runs without error and displays "H":
function f(message)
{
alert(message);
}
f("H", "e", "l", "l", "o");
If we did want to access the other arguments from inside f(), we can use
the arguments keyword. arguments references an Arguments object, which
has a length property and feels like an array.
function f(message)
{
// message param is the same as arguments[0]
for(var i = 1; i < arguments.length; i++)
{
message += arguments ;
}
alert(message);
}
// this will say "Hello"
f("H", "e", "l", "l", "o");
Just so you know, arguments is technically not an array, even if it walks
and talks like one. arguments has a length property but no split,
push, or pop methods. What we can do with arguments inside
our previous g() function is copy the incoming arguments after arguments[1]
into an array object that we pass to apply.
var o = { x: 15 };
function f(message1, message2)
{
alert(message1 + (this.x * this.x) + message2);
}
function g(object, func)
{
// arguments[0] == object
// arguments[1] == func
var args = []; // empty array
// copy all other arguments we want to "pass through"
for(var i = 2; i < arguments.length; i++)
{
args.push(arguments );
}
func.apply(object, args);
}
g(o, f, "The value of x squared = ", ". Wow!");
When we invoke g(), we can pass additional arguments as parameters instead of stuffing
the arguments into an array.
At this point, we have the theoretical knowledge needed to understand call
and apply, but perhaps you are already asking a question: what if I don't
want to immediately invoke the target function f()? What if I just want to
arrange all the players in this little drama so that I can invoke f() at
some later point (as an event handler, for example), but still have this
referencing the desired object (whithout tracking the desired object myself). In an upcoming post, we'll see how to combine our
Function.apply and arguments knowledge with the concept of nested
functions and closures to answer this very question.

|
-
I've fallen behind on my weekly link-listing series - apologies for the delay. ASP.NET -
.NET DateTime and Number Format String Cheat Sheet: If you are like me, you might have trouble remembering all of the standard format strings you can pass to the String.Format() method and/or the Eval() databinding method in ASP.NET to generate the appropriate string output from a DateTime or Numeric datatype. This PDF cheatsheet is a useful one to download and save to quickly look these format strings up. John has some other really useful .NET PDF cheatsheets he has also created that you might like to download here. -
ASP.NET Photo Handler: Bertrand has posted a cool photo album HttpHandler for ASP.NET that allows you to easily drop images into a web directory and automatically generate a nice photo album of them (complete with EXIF information, stack sorting icons, etc). Might be very useful for people enjoying holidays this summer. Download the code here. - BlogEngine.NET: This is a new open source blog engine for ASP.NET that Mads Kristensen has helped start up, and which I've heard a lot of good things about. You can read about its features here, and download it here.
ASP.NET AJAX Visual Studio -
GhostDoc 2.1.1 Released: GhostDoc is a free add-in for Visual Studio 2005 (and now 2008) that automatically generates default XML documentation comments for code you write in C# or VB. It can automatically re-use existing documentation inherited from base classes or implemented interfaces, or generate initial documentation by deducing comments from the name and type of the member signature. You can learn more about it and download it for free here. Silverlight - Silverlight Tutorials: Michael Schwarz has a great blog where he writes regularly about Silverlight. This tutorials link points to a bunch of great Silverlight content.
IIS 7 -
IIS 7.0 is now running all of Microsoft.com: One of the things we push at Microsoft is to "dogfood" our products on our high volume sites when they enter the beta cycle. As of a few weeks ago, all of the web servers running www.microsoft.com are now running on IIS7 and Windows 2008 Server Beta3. These servers host 500+ virtual roots and 350 ASP.NET applications, and handle 300,000 concurrent connections. IIS7 is going to be an awesome release. -
IIS 7.0 on Server Core: Bill Staples blogs about some of the new IIS7 enhancements that appear with the June CTP of Windows 2008 Server. One of the big features that is now supported is the ability to install IIS7 on "server core" - which is a low footprint installation of Windows 2008 Server that lays down just the minimal footprint needed to boot (meaning no GUI shell). This lowers the resources required on servers, and even more importantly means that servers don't need to be updated if a patch is released for a component not installed on the server (which lowers the downtime of servers). ASP.NET and the .NET Framework aren't supported yet in server core configurations - but will be in the future. Hope this helps, Scott P.S. I'm out on vacation this week, so please excuse delays on email and comment feedback. 
|
-
One problem in WWWTC # 16 is the assumptions Estelle makes about this. In C# you
don’t need to explicitly use the this keyword to reference an instance field from
inside an instance method. It’s tempting to write a method like Estelle’s …
InputManager.prototype.resetToInitialValue = function()
{
_input.value = _initialValue;
}
… only to find out the method tries to access a global variable named _input and
a global variable named _initialValue. In ECMAScript we need to explicitly bring
this into play to reference entries in the object’s own dictionary:
InputManager.prototype.resetToInitialValue = function()
{
with(this)
{
_input.value = _initialValue;
}
// OR
this._input.value = this._initialValue;
}
Thanks to delegate inference in C#, it’s also tempting to think we can assign an
instance method to a DOM event …
function InputManager(input)
{
this._input
= input;
this._initialValue
= input.value;
// won't work
this._input.ondblclick = this.resetToInitialValue;
}
… only to find out we’ve simply given the DOM event a reference to a function object.
The DOM element will happily invoke the function directly and without using an instance
of an InputManager object. Our this reference inside of the resetToInitalValue function
is then useless. Similar code in C# will work, because the C# compiler
will magically create a delegate behind the scenes, and that delegate will manage
an object reference, and invoke an instance method through that object reference.
There are mechanisms in ASP.NET AJAX to fix the above scenario, but in the end it
boils down to giving the DOM element a function object that can remember the proper
this reference. A simple approach would look like:
function createDelegate(object,
method)
{
return
function() { method.apply(object,
arguments); }
}
function InputManager(input)
{
this._input
= input;
this._initialValue
= input.value;
this._input.ondblclick
= createDelegate(this,
this.resetToInitialValue);
}
Here we are using the magic of a JavaScript closure to create and return a new function
object from inside createDelegate. The DOM event will reference this new function
object. When this new function object is invoked by the DOM element, the new function
sets up a proper invocation of resetToInitialValue by using Function.apply and passing
through the InputManager reference to use as the this reference.
We’ll explain this topic of closures and Function.apply more thoroughly in the future.
Those fixes should get the code working for now, but what else in that code was
a monster in the closet?
For one, the event handler registration could use some work. There are tons of JavaScript
code and articles written on the topic of how to do safe, non-desctuctive, cross-browser
event registrations, so for now I’ll just say if you are using something like ASP.NET
AJAX’s $addHandler technique your code will improve over the above approach.
Secondly, it’s good practice to clean up event registrations. The code sets up a
scenario where each InputManager holds a reference to DOM element (in the _input
field), and that same DOM input holds a reference back to it’s InputManager (via
the function object / event handler that formed a closure over the InputManager
instance). In the past, these circular references created memory leaks and were
a common “memory leak pattern” in Internet Explorer. I say “in the past” because
these problems are fixed in IE7 (and in IE6 (with an update)). Still, the generally
accepted practice in today’s AJAX patterns is to clean up afterwards, which feels
like the right thing to do as not all browsers are perfect in figuring out these
circular references.

|
-
It’s been some time since the last WWTC, but Estelle Hertz is still cranking out software. This time Estelle was asked to write some JavaScript code for a web page with hundreds of textbox input controls (the page collects details for a life insurance policy). When a user double clicks on any textbox on the page, the textbox should reset itself to its initial value (the value in the control when the page first loaded).
Estelle has yet to experience all the slippery pitfalls in JavaScript development, and writes the following code:
<% @ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<form id="form1" runat="server">
<div>
<input id="Text1" value="default" type="text" />
<%-- and so on for a 100 textbox controls --%>
</div>
</form>
</body>
</html>
<script type="text/javascript">
function InputManager(input)
{
this._input = input;
this._initialValue = input.value;
this._input.ondblclick = this.resetToInitialValue;
}
InputManager.prototype.resetToInitialValue = function()
{
_input.value = _initialValue;
}
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++)
{
if(inputs .type != "text")
continue;
var manager = new InputManager(inputs );
}
</script>
Anyone spot a problem? Two problems? Three problems? Could there be possibly be more than three problems in the 20 line hunk of script?

|
-
Look! Actual ASP.NET content is back!
The documentation for WebConfigurationManager.OpenWebConfiguration says:
"Opens the Web-application configuration file as a Configuration object using the specified virtual path to allow read or write operations."
This might lead you to think you'll only find stuff from a single web.config file in the returned Configuration object - but this isn't true. The following code will return the extensions and paths mapped to the web forms PageHandlerFactory for "MyWebSite".
IEnumerable GetPageHandlerFactoryExtensions()
{
string sectionName = "system.web/httpHandlers";
string pageHandlerFactoryName = typeof(PageHandlerFactory).ToString();
Configuration config =
WebConfigurationManager.OpenWebConfiguration("/MyWebSite");
HttpHandlersSection handlersSection = config.GetSection(sectionName)
as HttpHandlersSection;
foreach (HttpHandlerAction httpHandlerAction in handlersSection.Handlers)
{
if(httpHandlerAction.Type == pageHandlerFactoryName)
{
yield return httpHandlerAction.Path;
}
}
}
... and you should at least get a result of ".aspx". This ".aspx" entry probably isn't in the web.config for "MyWebSite", but it is in the machine level web.config file (found in %Windows%\Microsoft.NET\Framework\v2.0.50727\CONFIG) by default.
Remember .NET configuration files are hierarchical, and if you look at the documentation for System.Configuration you'll find (emphasis mine):
The Configuration class instance represents the merged view of the configuration settings that apply to a specific physical entity, such as a computer, or to a logical entity, such as an application, or a Web site.

|
-
My Working with Data in ASP.NET 2.0 tutorial series has been updated with five new tutorials: one on building database-driven site maps and four on working with batched data.
The site map feature introduced in ASP.NET 2.0 allows developers to logically arrange a web application's pages into a hierarchy. This hierarchy can then be accessed programmatically through the SiteMap class in the .NET Framework or rendered visually through the Menu, TreeView, and SiteMapPath controls. .NET ships with a site map implementation that serializes the site map to an XML file. Since the site map framework was designed using the provider model, developers can easily plug in their own serialization implementations. (For more on ASP.NET 2.0's site map feature, see Examining ASP.NET 2.0's Site Navigation.) Building a Custom Data-Driven SiteMap Provider [VB | C#] looks at how to create a site map provider that constructs the site map based on data pulled from the application architecture.
The remaining four tutorials look at working with batched data. By default, the GridView is designed to modify data one record at a time. The built-in Delete and Edit buttons, for example, allow for one record to be deleted or updated. This can result in a lot of pointing and clicking when you need to delete or edit multiple records. The four tutorials on working with batched data examine important considerations and illustrate how to customize the data Web controls to create a user interface conducive to batch deletes, updates, and inserts:
- Wrapping Database Modifications within a Transaction [VB | C#] - looks at how to wrap a series of database modifications within the scope of a transaction. Transactions guarantee atomicity, ensuring that either all of the batched modifications will succeed or none of them will.
- Batch Updating [VB | C#] - examines turning a GridView into a fully-editable GridView, where all rows can be edited at once.
- Batch Deleting [VB | C#] - shows how to add a series of checkboxes to a GridView to enable multiple records to be deleted at the click of a button.
- Batch Inserting [VB | C#] - explores a user interface for quickly inserting multiple records.
Like the previous tutorials in the series, all tutorials are available in C# and VB, include the complete code download as a self-extracting ZIP, and are available in PDF format.
Happy Programming!
|
|
|
|