|
Friday, October 10, 2008
#
There has been a rumor for quite some time that Apple will announce some new notebooks, laptops, or netbooks on October 14th. Apparently there is some truth to this rumor as Apple has invited some members of the press to a town hall event on October 14th with an invitation that reads - “The spotlight turns to notebooks.”
Based on other rumors and certain images that have been leaked about a new design of the MacBook Pro, perhaps we will be getting a new MacBook Pro, more lower entry MacBooks, or possibly a NetBook from Apple. I believe Apple needs to be more competitive around the sub $1000 price range, and personally I need a good NetBook from Apple that is competitive with the Dell Mini :)
Really looking forward to the announcements.
Related Posts
Thursday, October 09, 2008
#
Awhile back I mentioned that I was looking for a good iPhone 3G Case to protect my iPhone:
Since then I have bought a few of them just to see what suited me best.
A couple weeks back I was in the Apple Store looking at cases again and a salesperson recommended the Speck PixelSkin. Even though he didn't have an iPhone 3G because he had to wait for his current contract to expire, he said that you cannot go wrong with rubber as a way to protect your iPhone. He mentioned how he thought the green case looked like a grenade and the yellow case looked like corn on the cob, etc. :)
This, of course, is when I play devil's advocate and say but won't the rubber make the phone unable to dissipate heat, etc., and he said that the only “complaint” he had received with them is that they can be difficult to get into and out of a pocket, depending on the pocket. People in tight pants may want to steer away from this one :)
Fair enough. I bought the green Speck PixelSkin iPhone 3G Rubber Case for the heck of it.
Fast forward to the other night when I am getting out of the car with my daughter in the garage and I lost my grip on the phone and it falls to the hard cement garage floor. Yep - my heart skipped a beat and all the blood rushed to my face where I was about to scold myself for being a complete idiot. Unfortunately, my daughter was there, so the expletives were confined to my thoughts. Well, maybe a few drifted out :)
To my amazement, not a scratch. The iPhone fell at least 4 feet to a cement floor. No scratch. No nick. No crack. No damage!
I don't know if it was complete luck, or if the phone happened to fall at just the right angle, or the rubber iPhone case was just that good, but the heck with all the other cases. The $25 Speck PixelSkin just saved me $300!
Now how the heck I lost my grip on a textured rubber case is beyond me!
Related Posts
Wednesday, October 08, 2008
#
I think MacRabbit is finally building the Mac web design and web development tool that most Mac web developers can appreciate.
Per the Espresso description on MacRabbit:
“Espresso is not a bunch of apps forcibly smashed together. Instead, we looked at the needs of modern web developers and streamlined their workflow into one focused app. Extremely powerful editing, sleek projects, live preview (we make CSSEdit — did you really expect anything less?), real publishing and extensive synchronization tools. All this, and an amazing extensible core? It's not too good to be true. It's coming in November.”

Espresso is currently in beta and isn't expected to be available until November.
If MacRabbit's Espresso is even half as well thought out as their CSSEdit product, Espresso will be a great web design and development tool for the Mac.
Learn more here.
Recent Posts
Sunday, October 05, 2008
#
There is a free day of training on the ASP.NET MVC Framework on Monday, November 17, 2008 at the Microsoft Office in Tampa, Florida. Myself, Jim Zimmerman, and Joe Healy will be showing how to develop ASP.NET MVC Framework Applications from the ground up - no experience required.
“Throughout the day we will be demonstrating the ASP.NET MVC Framework in a cookbook-style approach with recipes on how to solve common challenges when developing MVC web applications. No previous knowledge or experience is necessary. We will walk you through the basics on creating views and controllers and by the end of the day show you how to develop end-to-end MVC applications complete with ajax, authentication, authorization, caching, databinding, logging, persistence, validation, and other common challenges we experience in day-to-day development.
Sample code will leverage and integrate popular frameworks and libraries like ADO.NET Data Services, ASP.NET AJAX, ASP.NET Dynamic Data, Enterprise Library, Entity Framework, and LINQ To SQL to show you how to write less code and be more productive during your development. Polish it all off with examples showing the extensibility of the MVC Framework using custom controller factories, alternative view engines, and custom action filter attributes just to name a few.“
Should be an absolute blast. Register here.
Related Posts:
Wednesday, October 01, 2008
#
Love the iPhone. Sure there have been little bumps here and there, but overall the new iPhone 3G, App Store, and iPhone Applications are getting better and better everyday.
Two cool things happened recently that get me all excited:
- Apple now requires you to have either downloaded and/or bought an iPhone Application to review it. Fanstastic! This gets rid of all the knuckle heads who feel it necessary to rate a product even though they have not used it. You know what I am talking about. The idiots who rate it badly because they think it is too expensive and won't buy it. Or, users who really like the Mac or PC Version and give the iPhone version 5 stars even though they have not tried the iPhone Version. Geez...
- As the title of this post suggests, Apple Drops the more strict NDA on the iPhone, which will allow iPhone Developers to write books and tutorials on how to develop applications for the iPhone using the iPhone SDK. I mean seriously, who doesn't want to write an application for the iPhone and get a little help from books and tutorials! Fantastic!
I think the iPhone 3G and App Store is going to get even better with the lifting of the iPhone NDA. Certainly Apple needs to protect their intellectual property from other companies who will steal their information, but I really like the idea of getting the development information out there so I can write some programs on my iPhone 3G!
Learn more about the NDA announcement here.
Sunday, September 28, 2008
#
 ScottGu mentions that jQuery will be bundled with Visual Studio 2008 and the ASP.NET MVC Framework. And more than that, you will actually be able to call Microsoft Product Support on jQuery problems. Now that really means Microsoft is definitely in bed with jQuery :) jQuery is all I have been using in my ASP.NET MVC Framework Projects, so it is really good to see that jQuery will become a first-class citizen not only in the ASP.NET MVC Framework and Visual Studio 2008, but Scott also mentions the AJAX Control Toolkit!
Before I forget, if you want a good book on jQuery, check out my jQuery in Action Book Review. I was learning jQuery on my own very slowly, but then needed that extra help and found jQuery in Action very helpful!
Per Scott-
"The jQuery intellisense annotation support will be available as a free web-download in a few weeks (and will work great with VS 2008 SP1 and the free Visual Web Developer 2008 Express SP1). The new ASP.NET MVC download will also distribute it, and add the jQuery library by default to all new projects."
Great stuff!
Saturday, September 27, 2008
#
WebKit, the browser engine used by Apple's Safari and Google's Chrome, is apparently the first browser engine to fully pass Acid3. WebKit has long scored 100/100, but now it appears to have passed the final requirement of smooth performance on animations.
According to the Surfin' Safari Blog:
“Today we would like to announce that WebKit is the first browser engine to fully pass Acid3. A while back, we posted that we scored 100/100 and matched the reference rendering. Now, thanks to recent speedups in JavaScript, DOM and rendering, we have passed the third condition, smooth animation on reference hardware.”
You can learn more here.
I created a screencast the other day called:
which showed off the new Unity Interception Extension and RemotingPolicyInjection in Unity v1.2 ( still in development ).
This got me thinking about a presentation I did for IASA Tampa on AOP, where I showed off the Policy Injection Application Block, PostSharp, Castle Windsor, and various other tools:
Similar to the IASA Tampa Bay Presentation where I compared and contrasted the various alternative tools using the same scenario, I thought I would provide some code using PostSharp 1.0 that does the same thing as mentioned in the screencast. For background please watch the screencast where I walk through the details of the sample using Unity. All I plan to do here is show some code using PostSharp Laos with very brief commentary. My only point is that there are many, many ways to solve a problem. It is nice to understand the alternatives as well as their pros and cons. You can learn more about PostSharp at PostSharp.org.
In the screencast I created a custom HandlerAttribute and ICallHandler that invokes the Stopwatch Attribute Class and prints out the time it takes for the ILogger.Write Method to execute. Again, see the screencast for details. I can do the same thing with PostSharp Laos, but instead create a StopwatchAttribute that derives from OnMethodBoundaryAspect:
[Serializable]
public class StopwatchAttribute : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionEventArgs eventArgs)
{
var sw = new Stopwatch();
sw.Start();
eventArgs.MethodExecutionTag = sw;
}
public override void OnExit(MethodExecutionEventArgs eventArgs)
{
var sw = (Stopwatch)eventArgs.MethodExecutionTag;
sw.Stop();
Console.WriteLine();
Console.WriteLine(string.Format("Time Elapsed: {0} ms", sw.ElapsedMilliseconds));
}
}
I can then decorate my Logger's Write Method with the Stopwatch Attribute as such:
public interface ILogger
{
void Write(string message);
}
public class Logger : ILogger
{
[Stopwatch]
public void Write(string message)
{
Console.WriteLine();
Console.WriteLine("*** In Logger ***");
Console.WriteLine(string.Format
("message : {0}", message));
}
}
When I register the logger with Unity and run the application:
static void Main(string[] args)
{
IUnityContainer container = new UnityContainer();
container.RegisterType<ILogger, Logger>(new ContainerControlledLifetimeManager());
ILogger logger = container.Resolve<ILogger>();
logger.Write("Hello!");
Console.ReadLine();
}
it displays the results of the Stopwatch's Elaspsed Time in a console window. Notice that I don't need to use the Interception Extension or the RemotingPolicyInjector in this case. PostSharp Laos will be handling the interception via IL Weaving during the post-compile.

The interesting part is what PostSharp Laos does under the covers. It does a bit of IL Weaving and changes the Logger.Write Method into a Try/Catch/Finally Block that calls your Stopwatch Attribute Code inline to the method. No better way to see this than with Reflector:

Cool stuff!
Hope you enjoy the screencast. Check out other Patterns & Practices Screencasts.
David Hayden
Friday, September 26, 2008
#
Adobe Dreamweaver CS4 sounds better than I previously thought. Some of the features in Dreamweaver CS4 that have my immediate interest include:
- Subversion Integration - Update your site and check in modifications directly from within Dreamweaver. Dreamweaver CS4 integrates with Subversion® software, an open source versioning control system, for a more robust check-in/check-out experience.
- Code hinting for Ajax and JavaScript frameworks - Write JavaScript more quickly and accurately with improved support for JavaScript core objects and primitive data types. Put the extended coding functionality of Dreamweaver CS4 to work by incorporating popular JavaScript frameworks, including jQuery, Prototype, and Spry.
- Integrated coding - Tap the power of built-in code hints for faster and cleaner coding in HTML; JavaScript; Ajax frameworks such as Spry, jQuery, and Prototype; and several server languages.
- Live View - Design your web pages under real-world browser conditions with the new Live View in Adobe Dreamweaver CS4 — while still retaining direct access to the code. Changes to the code are instantly reflected in the rendered display.
You also have your choice of running Dreamweaver on the Mac as well as the PC.
You can get the entire list of Dreamweaver CS4 features on the Adobe Website.
Related Posts:
I mentioned the Silverlight 2 Release Candidate earlier:
but wanted to mention that Scott Guthrie has a good post on various Silverlight 2 features, functionality, and getting started links as well.
I mentioned the Entity Framework POCO Adapter a couple of times:
Jaroslaw Kowalski updated the Entity Framework POCO Adapter to v1.03 based on feedback from users in N-Tier Application Scenarios and with Detached Entities. Some of the changes include:
- Added wrapper for ObjectContext.ApplyPropertyChanges() to IEntitySet<T>
- Added wrapper for ObjectContext.Detach() to IEntitySet<T>
- Fixed handling of detached/out-of-scope entities w.r.t lazy loading and attaching to other contexts. Lazy loading outside of scope will do nothing if the context had DeferredLoadingEnabled=false, otherwise will throw.
- Added partial OnZZZCreated() methods on generated contexts, adapters and proxies to enable integration with 3rd-party extensions
- Fixed code generation from EDMX.
- EFPocoContext.EnableLazyLoading has been renamed to EFPocoContext.DeferredLoadingEnabled to better align with Linq to SQL and our plans for EF v2
- Fixed adapter-POCO synchronization for complex types
You can download the Entity Framework POCO Adapter here.
TAGS: O/R Mappers, Code Generators
Wednesday, September 24, 2008
#

Update 9/26/2008 - I spoke too soon. Dreamweaver 4 has some pretty compelling features given I am a few versions back: Dreamweaver 4 New Features - Subversion Integration - Live View - jQuery Code Hinting
As much as I hate the idea of parting with $400 to upgrade to Adobe Creative Suite 4 for the new Dreamweaver and Fireworks, it is probably inevitable since I am a few versions behind on Dreamweaver and Fireworks.
Although I don't use the Dreamweaver and Fireworks for anything hardcore, they have become fairly indispensible since I started using them when they first came out with Macromedia. Personally, I prefer Dreamweaver over Microsoft Expression Web 2 ( see Microsoft Expression Studio 2 ), but that is probably based on more familiarity than technology and features.
Although I will say that the FTP Manager in Microsoft Expression Web 2 sucks! Tell me why I don't have a TreeView to publish files back and forth to the remote FTP Server???? ( Expression Web 2 - FTP Explorer to Publish Websites Should be a TreeView )
And, Microsoft Expression Design 2 does not have bitmap tools, only vector graphic tools. Geez... I need bitmap tools as well folks ( Expression Design 2 Needs Some Bitmap Graphics Tools like Crop Lasso Magic Wand Marquee ). Sorry, I digress :)
Anyway, Adobe mentions the new Live Preview in Dreamweaver 4 which is apparently different from the WYSIWYG feature that Dreamweaver has had for years. And, Adobe always mentions product integration improvements, which I take as annoying filler in their feature list and just hear ( blah blah blah ).
Fireworks has some functionality with exporting to PDF as well as a few more Photoshop Blend Modes, but again I don't see much to get excited about there as well. I think Fireworks will always be taking a back seat to PhotoShop, but I really like the ease and simplicity of Fireworks for simple web graphics.
Currently, the free trials for Dreamweaver and Fireworks in Creative Suite 4 are unavailable. However, when they come out, I will have to give them a serious test drive.
Learn more about Adobe Creative Suite 4 here.
I am looking forward to Unity v1.2, which will include Aspect-Oriented Programming ( AOP ) Features ported from the Enterprise Library Policy Injection Application Block.
For those of you familiar with the Policy Injection Application Block and its use of Remoting Proxies, you will easily get up to speed on the new Unity v1.2 Interception Extension and RemotingPolicyInjector that provide similar functionality in Unity. In fact, the new Microsoft.Practices.Unity.Inteception Assembly is mostly a transfer of the PIAB Core Code to Unity.
To demonstrate the new RemotingPolicyInjector and Interception Extension, I created a screencast:
Although Unity v1.2 is in the early drops and subject to change, hopefully the screencast will help you understand the possibilities.
Check out other Patterns & Practices Screencasts.
Wednesday, September 17, 2008
#
If you are in the area, check out the Sarasota .NET Developer Group's Meeting tonight on the Unity Application Block:
Unity is the new dependency injection and inversion of control container from Microsoft Patterns & Practices that can be used as a standalone IoC Container or as a alternate configuration mechanism for use with Enterprise Library.
Randy is an excellent speaker and has been presenting on Unity across Florida. Should be a great presentation.
You can check out my Unity Screencasts and Unity Tutorials for an introduction to Unity.
Related Posts:
Tuesday, September 16, 2008
#

VMware Fusion 2.0 was just released. VMware Fusion 2 is a free, downloadable upgrade for all VMware Fusion 1.x customers. Simply download the new software for use with your existing serial number.
“Building on the award-winning VMware Fusion 1.x, and leveraging nearly a decade of desktop virtualization technology, VMware Fusion 2 delivers the most advanced Mac virtualization software available today. VMware Fusion breaks down the walls between Windows and Mac OS X, transforming Windows applications to work seamlessly within OS X like native applications, letting users launch any Mac file with any Windows application, seamlessly share data and folders between Windows and Mac, use Windows applications across multiple monitors, and even custom map the Mac keyboard to special keystrokes for Windows applications.”
Download VMware Fusion 2.0 here.
Sunday, September 14, 2008
#
Love the iPhone and the various iPhone Apps.
There is a FREE iPhone Application, called Sportacular, which provides excellent sports coverage. I use it for up-to-the-minute NFL coverage as well as standings, stats, etc. Sportacular is a must have FREE iPhone Application for the sports fan.

Related Posts:
Saturday, September 13, 2008
#
With support for the new Zune 3.0 Firmware, you can download the XNA Game Studio 3.0 Beta next week with the following Framework and Visual Studio Enhancements:
- Media enumeration and playback on Windows and Xbox 360 (parity with the Zune APIs that were available in the CTP)
- Simple sound effects on Windows and Xbox 360
- Rich presence, invites and join session in progress
- Content compression
- FBX importer improvements
- Support for C# 3.0 features in Xbox 360 and Zune games (this was already available for Windows in the CTP)
- Screenshots of games while they are running on a Zune
- ClickOnce deployment for Windows games
- Project upgrade wizard to automatically upgrade XNA Game Studio 2.0 games
- Multiple content projects
- Cross-platform project synchronization
You can learn more about the XNA Game Studio 3.0 Beta on the XNA Game Studio blog.
Based on personal experience I can tell you that the new iPhone 2.1 Update is more than just some bug and security fixes, but really does have much better reception and fewer call drops. In my office I now experience far better call reception and didn't have a single call drop compared to before. The reception was so great I made several test calls to family members in disbelief that a software update could make such a difference.
Some of the new iPhone 2.1 changes:
- Decrease in call set-up failures and dropped calls
- Significantly better battery life for most users
- Dramatically reduced time to backup to iTunes
- Improved email reliability, notably fetching email from POP and Exchange accounts
- Faster installation of 3rd party applications
- Fixed bugs causing hangs and crashes for users with lots of third party applications
- Improved performance in text messaging
- Faster loading and searching of contacts
- Improved accuracy of the 3G signal strength display
- Repeat alert up to two additional times for incoming text messages
- Option to wipe data after ten failed passcode attempts
- Genius playlist creation
Very cool!
Related Post: iPhone 3G and MobileMe Rock!
Friday, September 12, 2008
#
In the previous ASP.NET MVC Tutorial:
I talked about using the Enterprise Library Validation Application Block with ASP.NET MVC to handle validation of your business objects in our web applications. I used the Validation Application Block's Validation Facade Class in the Controller and then queried the results of ValidationResults.IsValid to determine if validation was successful. If validation was not successful, I enumerated through each ValidationResult and updated ASP.NET MVC's ModelState via ModelState.AddError appropriately to display the UI input validation errors to the user.
This ASP.NET MVC Tutorial will introduce the Enterprise Library Policy Injection Application Block to handle validation in another way. Please check out the tutorial above first as I won't be duplicating some of the code. Feel free to check out the other ASP.NET MVC Tutorials as well:
Policy Injection Application Block Tutorials
Here are some Policy Injection Application Block Tutorials if you need some background:
Policy Injection Application Block Assemblies Referenced
We need to reference two additional assemblies in addition to what I mentioned in the previous tutorial:
- Microsoft.Practices.EnterpriseLibrary.PolicyInjection
- Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers
ValidationCallHandler in Policy Injection Application Block
There is a particular call handler in the Policy Injection Application Block for use with the Validation Application Block, called ValidationCallHandler. I am adding the ValidationCallHandler Attribute to my ICustomerRepository Interface's Add Method to invoke validation as a cross-cutting concern. When the Add Method is called, the method will be intercepted and validation on my customer instance will take place prior to the Add Method being executed. If validation fails, the Add Method will not be called. Instead, an ArgumentValidationException will be thrown and we will pass those validation errors back to the UI for correction. Nice and tidy :)
public interface ICustomerRepository
{
[ValidationCallHandler]
void Add(Customer customer);
}
public class CustomerRepository : ICustomerRepository
{
public void Add(Customer customer)
{
}
}
The actual code for persistence is unimportant so I left it blank. Notice the [ValidationCallHandler] Attribute mentioned above on the ICustomerRepository Interface.
PolicyInjection.Wrap Returns Remoting Proxy
The Policy Injection Application Block has a PolicyInjection Class with a Wrap Method ( PolicyInjection.Wrap ) that will return a remoting proxy if it detects that interception needs to take place on the class it is wrapping. The remoting proxy returned in this case intercepts the Add Method on ICustomerRepository and first does validation as mentioned above. In my Customers Controller Class I am wrapping CustomerRepository in the constructor.
public class CustomersController : Controller
{
private ICustomerRepository _repository;
public CustomersController() : this(
PolicyInjection.Wrap<ICustomerRepository>
(new CustomerRepository())) {}
public CustomersController(ICustomerRepository repository)
{
_repository = repository;
}
// ...
}
ASP.NET MVC Validation in Action
Now in our Controller Action we can attempt to add the customer to the repository and catch the Policy Injection Application Block's ArgumentValidationException when it detects bad user input:
public ActionResult Save()
{
Customer customer = new Customer();
try
{
UpdateModel(customer, new[] { "Name", "Email" });
_repository.Add(customer);
}
catch(ArgumentValidationException ex)
{
AddValidationResults(ex.ValidationResults,
ViewData.ModelState);
return View(customer);
}
//...
}
This looks a bit cleaner IMHO. None of that nasty cross-cutting concern garbage getting in the way of our reading of the code.
The results are the same as mentioned in the previous ASP.NET MVC Tutorial when input is erroneous:
Conclusion
The use of the Enterprise Library Policy Injection Application Block with the Validation Application Block offers another way of handling validation in the ASP.NET MVC Framework. You can learn more about proven patterns & practices at PnPGuidance.
I want to note that in the Enterprise Library 4.1 and Unity 1.2 Project Kickoff there was mentioning of other interception mechanisms down the road. Very nice!
Hope this helps.
David Hayden
Wednesday, September 10, 2008
#
Previous ASP.NET MVC Tutorials:
We have been playing with input validation in the previous ASP.NET MVC Tutorials. With the new ModelState.AddModelError functionality we have a really cool way to provide feedback to the user on errors in his/her input. One of the cool offerings from Microsoft Patterns & Practices is the Enterprise Library Validation Application Block to help with validating your custom classes. In this tutorial I will show you a simple way ( one way ) to integrate the Validation Application Block with ASP.NET MVC.
Validation Application Block Tutorials
If you are not up to speed on the Validation Application Block, you can check out my previous Enterprise Library Tutorials:
You can also check out the following Enterprise Library Screencasts:
Enterprise Library Assemblies Referenced
At a minimum you need to reference the following 3 Enterprise Library assemblies in you ASP.NET MVC Application:
- Microsoft.Practices.EnterpriseLibrary.Common
- Microsoft.Practices.EnterpriseLibrary.Validation
- Microsoft.Practices.ObjectBuilder2
Validation Validator Attributes on Custom Class Properties
The Enterprise Library Validation Application Block has numerous validator attributes that you can add to your custom class properties. You can also keep your classes validation ignorant ( Plain Old CLR Objects ) and add the validation in your configuration file. However, let's just stick with attributes for this quick example. Such validation validator attributes you can use are:
- ContainsCharactersAttribute
- DateTimeRangeValidatorAttribute
- DomainValidatorAttribute
- EnumConversionValidatorAttribute
- NotNullValidatorAttribute
- PropertyComparisonValidatorAttribute
- RangeValidatorAttribute
- RegexValidatorAttribute
- StringLengthValidatorAttribute
- etc...
A lot of cool options. I am going to keep this simple and just use the RegexValidatorAttribute to validate an email address on our trivial Customer's Email Property:
public class Customer
{
public string Name { get; set; }
[RegexValidator(@"^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$",
MessageTemplate="Email invalid")]
public string Email { get; set; }
}
ASP.NET MVC Validation Using Validation Application Block
The end result I am looking for is that when a user enters an incorrect email address in the Email TextBox, they are presented with an error such as:

You can use the Validation Application Block in many ways. You can use the decorator pattern with your data access object or repository. You could inject a validation service into your controller. I am going to show it the simplest way - using the Validation Facade Class in the controller to validate the Customer Class and return a ValidationResults Collection that we can query for IsValid and enumerate through any errors.
Here is the simple Controller Action:
public ActionResult Save()
{
Customer customer = new Customer();
UpdateModel(customer, new[] { "Name", "Email" });
ValidationResults results =
Validation.Validate<Customer>(customer);
if (!results.IsValid)
{
AddValidationResults(results, ViewData.ModelState);
return View(customer);
}
return RedirectToAction("...");
}
I use UpdateModel to populate the Customer instance with the form values and then call Validation.Validate and pass it the Customer instance to validate. I query to see if the customer instance is valid, and if not, add the validation results to the ModelState and re-display the view with the errors.
The AddValidationResults Method just copies the ValidationResults to the ModelState via ModelState.AddError:
private static void AddValidationResults(ValidationResults results,
ModelStateDictionary modelState)
{
foreach (ValidationResult result in results)
modelState.AddModelError(
result.Key,
result.Target.GetPropertyValue(result.Key),
result.Message);
}
The gotcha with the Validation Application Block is getting the erroneous value being validated so we can display it back to the user on the form. The ValidationResult Class has a Target Property with the object being validated ( customer instance ), but not the property's value. We can create a quick extension method that uses a bit of reflection to get the value of these simple types. This isn't production code, just example code :) Notice I am using this extension method in the code above: results.Target.GetPropertyValue ...
public static object GetPropertyValue(this object obj,
string propertyName)
{
PropertyInfo property = obj.GetType().
GetProperty(propertyName);
return property.GetValue(obj, null);
}
Another way to accomplish the same thing is to just pass in the FormCollection to AddValidationResults and get the erroneous value from the collection of form values. That avoids the reflection, etc.
Conclusion
The Enterprise Library Validation Application Block is just another way of implementing input validation in your ASP.NET MVC Web Applications. Hopefully this tutorial gives you some ideas. Check out Patterns & Practices Guidance for other Patterns & Practices Tutorials and Screencasts.
David Hayden
Monday, September 08, 2008
#
Recent ASP.NET MVC Tutorials:
ASP.NET MVC has some really nice helpers for databinding and validation that can assist one with a lot of the simple scenarios. I mentioned custom model binders and the ComplexModelBinder, but one can also explicitly call UpdateModel and TryUpdateModel on your controllers to populate custom classes from form values on your Views.
ASP.NET MVC UpdateModel
I have a Customer Class with four simple properties.
public class Customer
{
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public decimal Deposit { get; set; }
}
I also have a form where the user populates these Customer Properties.

We can populate the form values into a Customer instance using either the UpdateModel or TryUpdateModel Methods on our Customer Controller Class. The difference being that TryUpdateModel returns a boolean value if it was successful as opposed to throwing an InvalidOperationException should their be an issue with updating the model.
public ActionResult Save()
{
Customer customer = new Customer();
try
{
UpdateModel(customer, new[] { "Name", "Email",
"Phone", "Deposit" });
return RedirectToAction("...");
}
catch (InvalidOperationException)
{
return View(customer);
}
}
You pass in which properties ( keys ) you want updated by UpdateModel. In this case I am updating “Name“, “Email“, “Phone“, and “Deposit“. Optionally you could pass in an object prefix (e.g. “Customer“) to UpdateModel if you are prefixing your form values with the name of the class, like “Customer.Name“:
UpdateModel(customer, new[] { "Name", "Email",
"Phone", "Deposit" }, "Customer");
One of the more interesting aspects of UpdateModel and TryUpdateModel is that they report any errors to the ViewData's ModelState. For example, if I pass in the letter “a“ as the deposit when the property expects a Decimal, an InvalidOperationException is raised and the following error is displayed on the form:

Again, I did not add the error via ModelState.AddError. UpdateModel and TryUpdateModel add the error to the ViewData's ModelState so the error is displayed accordingly.
As a word of caution, all of this auto-magic databinding is wonderful for smaller applications, but you need to be careful in larger and more complicated applications as there is a lot of convention over configuration happening here that might limit you as the application evolves. Many of these helper methods can be done with simple factory classes, etc., which are more in your control and can be enhanced as needed.
Hope this helps.
David Hayden
Previous Tutorials
In the recent ASP.NET MVC Tutorials I have been investigating a few of the new features in ASP.NET MVC Preview 5. I mentioned the ComplexModelBinder for help in binding your form values with a custom class in your model and now I want to show an example of using a Custom Model Binder in case the Default and ComplexModelBinder don't meet your needs. Although I am going to show a simple custom model binder, you can of course adapt it to your needs.
Registering a Custom Model Binder
You can register a custom model binder in your Global.asax Application Start. In this case we are going to register a custom model binder for our Customer Class:
protected void Application_Start()
{
ModelBinders.Binders[typeof(Customer)] =
new CustomerBinder();
}
The Customer Class is far from interesting and only has 3 simple properties for our trivial example:
public class Customer
{
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
}
Creating a Custom Model Binder
The Custom Model Binder for the Customer Class will implement the IModelBinder Interface and instantiate a Customer instance and populate its properties from Request.Form.
public class CustomerBinder : IModelBinder
{
public object GetValue(ControllerContext controllerContext,
string modelName, Type modelType,
ModelStateDictionary modelState)
{
Customer customer = new Customer();
customer.Name = controllerContext.
HttpContext.Request.Form["Name"];
customer.Email = controllerContext.
HttpContext.Request.Form["Email"];
customer.Phone = controllerContext.
HttpContext.Request.Form["Phone"];
return customer;
}
}
Custom Model Binder In Action
The Custom Model Binder will be executed in the background for you when you add the Customer Class as your argument in your Controller Action. For kicks, I check that the value of the Email property on Customer is a valid email. If it isn't, I add an appropriate error to the ModelState so that the UI displays a validation error appropriately. Yes, there are better ways to handle validation and I will get to those in a separate post :)
public ActionResult Save(Customer customer)
{
var regex = new Regex(@"[\w-]+@([\w-]+\.)+[\w-]+");
if (!regex.IsMatch(customer.Email))
ViewData.ModelState.AddModelError("Email",
customer.Email, "Dude, Email is wrong!");
return View(customer);
}
The UI displays the error accordingly:

Conclusion
Custom Model Binders can get much more interesting than the one above. Hopefully this example and the ComplexModelBinder Example may have helped you better understand some of the features in the ASP.NET MVC Framework.
David Hayden
Sunday, September 07, 2008
#
Previous tutorial: ModelBinders in ASP.NET MVC - ComplexModelBinder Quick Tip
I am still sinking my teeth into ScottGu's post on ASP.NET MVC Preview 5 and absolutely lovin' the new ModelState Property on ViewData that can help the UI developer in re-displaying error messages on the view. The trick is to use the ModelState.AddModelError method during input validation to notify the View that there is an error in the input.
For example, when the following form is posted by the user I am going to automatically tell the user that the phone is indeed incorrect:

A couple of things in play here.
First, the Save Action on the Customers Controller has to notify the ModelState that there is an error in the input via the ViewData.ModelState.AddModelError Method:
public ActionResult Save(FormCollection form)
{
ViewData.ModelState.AddModelError("Phone",
form["Phone"], "Dude, Phone is wrong!");
return View(form);
}
Assume I am doing some validation, but the method of validation is unimportant. The key is calling the AddModelError Method and passing:
- The Key, which is essentially the name of the control on the form - “Phone“
- The Attempted Value for phone that was erroneous - form[“Phone“]
- The Exception or Error Message to display on the View - “Dude, Phone is wrong!“
The other piece of the puzzle is including a
- <%= Html.ValidationMessage("Phone") %>
in the view to display the error message passed into the ModelState. Just add it next to the control on the form.
Notice the red border around the Phone TextBox. Check the Site.css in your ASP.NET MVC Template and you will find a new CSS Class
.input-validation-error
{
border: 1px solid #ff0000;
background-color: #ffeeee;
}
This class is added dynamically by the View to the TextBox Control when you add an error via ModelState.AddModelError.
Very cool stuff!
I found this interesting. If you thought Windows XP was dead given Windows Vista, think again. The new Dell Inspiron Mini 9 comes bundle with either Ubuntu or Windows XP - Vista is not an option. Of course, it only has 1GB of memory, so that would explain why Vista is not in the picture.
Dell is starting to focus more on that inexpensive PC market with this new Inspiron Mini 9 and the previously released Dell Studio Hybrid. Not many options for the Inspiron Mini 9 - choose whether you want Bluetooth and the better built-in camera. You have no choice in the 8.9” display, 1GB Memory, and 16GB Solid State Hard Drive.
Seems less functional than an iPod Touch, but judge for yourself here.
I remember earlier this year that I was feeling uninspired and a bit bored with both technology and development. I felt I needed to shake things up a bit and expose myself to technology and development that was new to me in order to grow as a developer and technologist.
MacBook Pro
I started by purchasing a MacBook Pro. This was somewhat on a whim, but it was an easy purchase to make given that many of my colleagues also use a MacBook Pro and have nothing but great things to say about it. It is sexy and consistently ranks highest among other laptops in terms of performance, usability, and support. The quality of the MacBook Pro was also substantiated given all the MacBook Pro's I saw at TechEd 2008 this year, many of which were used by the presenters themselves.
Most of my colleagues completely removed Mac OS X from the MacBook Pro and ran Vista, but I decided to use Mac OS X as my primary OS when not doing development. Hence MAC OS X is used for mail, calendar, contacts, etc. and Windows XP is only used for development. I use VMware Fusion to run Windows and all my development tools flawlessly on the Mac. Turn on VMware Fusion's “Unity” and it looks like Visual Studio, SQL Server, and everything else is running on the Mac. Very cool.
MobileMe
After purchasing the MacBook Pro, I purchased MobileMe when it immediately became available. Mainly I wanted the contacts and calendar syncing so I can access my calendar and contacts remotely from a browser. The service was a bit flakey for the first week as I think Apple mis-anticipated the initial demand, but after the first week or so the service has been rock solid for me.
The fact that I can now manage my calendar, contacts, and email via a browser, Mac OS X, and my iPhone and everything is transparently in-sync is amazing! Although I haven't tried it, you can also use MobileMe from a PC running Windows! Therefore, if you work on a PC and a Mac, you have the best of both worlds. Utterly amazing.
iPhone 3G
The addition of the iPhone 3G became the icing on the cake. Now I can do all my email, contacts, and calendar from my iPhone, and again, it automatically stays in-sync with MobilMe and my MacBook Pro. Sweet! I can also stay in touch with news feeds using NetNewsWire, and of course, there are iPhone Applications for Twitter, MySpace, various IM clients, FaceBook, etc.
More importantly, however, is that some of the time management, project management, and other 3rd party services that I use for my businesses have either an iPhone App or an iPhone specific web interface that allow me to conduct business operations via the iPhone. This means I can be anywhere and have access to important data as if I was sitting at the MacBook Pro in the office. Unbelievable.
Conclusion
The MacBook Pro, MobileMe, and iPhone 3G have opened my eyes to a lot of new technology and allowed me to grow in many ways. It has also allowed me to become much more connected and untethered from my office. For me this was a great choice and just what I needed to become inspired again in my development. I couldn't be happier. As always, your needs and mileage may vary :)
Related Posts:
|