9/6/2010
LifeCycle Solutions - Home ( the software development blog )
 

<April 2007>
SunMonTueWedThuFriSat
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345

Subscribe to this feed:

RSS 2.0 | Atom 1.0 |CDF






Saturday, April 14, 2007

The Patterns & Practices team at Microsoft recently released the 3.0 version of the ever-useful Enterprise Library.  Among the changes in the current iteration of the library is the addition of a new application block - the Policy Injection Application Block ("PIAB").

The purpose of the PIAB is to provide developers a way to define "policies" that can be applied selectively throughout an application.  Imagine that you're building a human resources application and one of the requirements is that the application provide an audit trail for all changes made to an employee's personnel record.  The PIAB allows you to define this requirement as a "policy" and configure its behavior external to your application.

Here's how it works:

  • Using the Enterprise Library Configuration tool, you define a policy (in this case we'll name it "Audit Policy")
  • Each policy can have any number of associated "matching rules"; these rules define how/when the policy is applied.  The PIAB provides the following rules out-of-the-box:
    • Assembly Matching Rule
    • Custom Attribute Matching Rule
    • Member Name Matching Rule
    • Method Signature Matching Rule
    • Namespace Matching Rule
    • Parameter Type Matching Rule
    • Property Matching Rule
    • Return Type Matching Rule
    • Tag Attribute Matching Rule
    • Type Matching Rule
  • Each policy can also have any number of "handlers"; handlers determine what happens when a policy is executed.  The PIAB provides the following handlers, which utilize other Enterprise Library application blocks, out-of-the-box:
    • Authorization Handler
    • Caching Handler
    • Exception Handling Handler
    • Logging Handler
    • Performance Counters Handler
    • Validation Handler
  • In our HR application example, we'll elect to use a "Tag Attribute Matching Rule" that allows us to mark methods in our business tier classes as requiring audit functionality; in addition, we'll choose to apply the Enterprise Library's Logging Application Block as our policy's handler.

     The resulting XML in our application's configuration file looks like this (the Logging Application Block section has been omitted for brevity):

<policyInjection>
<policies>
<add name="AuditPolicy">
<matchingRules>
<add match="Audit" ignoreCase="false" 
  type=
  "Microsoft.Practices.EnterpriseLibrary.PolicyInjection.MatchingRules.TagAttributeMatchingRule,
  Microsoft.Practices.EnterpriseLibrary.PolicyInjection, Version=3.0.0.0,
  Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
  name="Tag Attribute Matching Rule" />
</matchingRules>
<handlers>
<add logBehavior="After" beforeMessage="" afterMessage="" eventId="0"
  includeParameterValues="true" includeCallStack="false" includeCallTime="true"
  priority="-1" severity="Information"
  type="Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers.LogCallHandler,
  Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers,
  Version=3.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
  name="Logging Handler">
<categories>
<add name="General" />
</categories>
</add>
</handlers>
</add>
</policies>
</policyInjection>


  • In our application, we're going to mark each method that requires an audit trail with a "Tag" attribute...notice that "Audit" corresponds to our matching rule defined above:
    /// <summary> /// Note: class must inherit MarshalByRefObject /// for use with the PIAB /// </summary> class Employee : MarshalByRefObject { [Tag("Audit")] public void Save() { //write employee to data store } [Tag("Audit")] public void Delete() { //remove employee from data store } }
  • The "policy injection magic" performed by the PIAB will occur as a result of the way we create an instance of our Employee class: 

    Employee ourEmployee = PolicyInjection.Create<Employee>(); ourEmployee.Save();

    The Create() factory method actually builds and returns a "proxy class" -- in this example, the proxy class intercepts our call to the Save() method, evaluates the matching criteria and determines that the handler should be executed because of the "Audit" tag match.  The result in this case is that an entry is written to the Windows event log as defined by our Logging Application Block configuration.

The "policy injection" pattern is worth a look if you have common functionality that needs to be applied throughout your application, and you want to do so in a declarative, transparent way.

Posted by Brian Parks

Monday, April 02, 2007


Like most users, I'm finding the switch from Office 2003 to Office 2007 to be relatively painless, EXCEPT, I've been consistently experiencing a delay when switching between instances of Word.  It finally annoyed me enough to research the issue, and I located the solution here...the culprit turns out to be the Acrobat PDFMaker COM Add-In.

Note that this post is not SD-related, directly, except that waiting on Word to switch windows cuts into one's development time.  =)
Posted by Brian Parks

In the slides from Scott Guthrie's 'ASP.NET Tips and Tricks' TechEd Presentation, I ran across this gem.  You can turn off debugging server-wide by adding the following to <system.web> section in the server's machine.config file (typically located in C:\windows\Microsoft.NET\Framework\v<version>\Config):

       <deployment retail="true"/>

This is a great backup in case developers forget to turn it off in the application using <compilation debug="false"/>.  Scott also mentions a few of the negative results of forgetting this little setting:

  • Slower performance due to debug code
  • App uses much more memory
  • Client-side scripts are not cached
Posted by Daniel Root

Friday, March 30, 2007

One of our favorite .NET books is "Framework Design Guidelines" by Krzysztof Cwalina and Brad Abrams.  In fact, it's required reading here at LifeCycle, and we try to check all code with FxCop to adhere to as much of the guidelines as possible.   Here is an excelent video presentation on many of these principals by Krzysztof.  It's a little long- 3 hours- so you may want to break up your viewing a bit,  but this guy is an absolute genius and what he has to say can go a long way in making or breaking your applications and APIs. 

Posted by Daniel Root

Monday, March 12, 2007

Last month I mentioned a couple upcoming tools for "next generation unit testing", but it should come as no suprise that Microsoft is also working on a similar tool of their own. From the maker of MbUnit, Pex is a unit testing framework that auto-generates test inputs for you. So, if you write a test like this:

[PexTest]public void MyTest(string input){...}


Then Pex is smart enough to generate tests for the full range of values for "input":

MyTest(""); MyTest(null); MyTest("somevalue");


Add in auto-correction, and the result is a pretty impressive test-driven development story. Unfortunately, this is currently only a Microsoft Research project. Hopefully it sees the light of day sometime soon (and not just for Team System!).

Posted by Daniel Root

Tuesday, February 20, 2007

Simile TimelineA recent post over on Scott Hanselman's blog turned me on to Simile Timeline, a open source Javascript API for adding cool timelines to web pages.  Think Google Maps, but for timelines.  It features a brilliant UI, and very extensible, well written client code.  Following the directions on the site, it's pretty easy to get started using it from ASP.NET- simply add the javascript reference and a bit of code to wire it up and you're all set.  But moving beyond the simple demo, I encountered a few issues and solutions that may be helpful:

Reference the Script from the Page Header. Simile Timeline requires you to reference the script from an include inside the <head> tag of your page.  This is because it uses the script include's url to determine the location of other scripts, images, and CSS files used by the app.  It is also possible to set this prefix in javascript, but your script includes should be in <head> anyway.

When generating XML from a HTTP Handler or web page, set the content type to text/xml.   The example that comes with Simile uses a static XML file for the event data, but in many cases you may want to generate this XML from a database in .NET.  This is easy enough to do by looping through a DataReader and writing out XML.  However, if you do not set Response.ContentType = "text/xml", then in FireFox, it will not parse the result as XML, and the events will not display.  IE is more lenient apparently, but this is still a good idea.

Prevent IE XmlHttp from caching results by adding a timestamp to the URL.  Internet Explorer's built-in XmlHttp class caches data, so that after one request to mysimilexml.aspx, the data is cached until the browser is restarted.  This is a problem if your data changes frequently, and can be aggrivating when testing. There is probably a way to adjust this in IE, but why have your users modify their browser settings?  In the javascript, add a timestamp to the URL to force a new request each time:

var eventsUrl = "ScheduleSimileXML.aspx?preventCache=" + currentDate.getFullYear() + "" + currentDate.getMonth() + "" + currentDate.getDate() + "" + currentDate.getHours() + "" + currentDate.getMinutes() + "" + currentDate.getSeconds()

Eventually, I'd like to see a real ASP.NET control wrapping this, but for now this is a very usable and handy API.

Posted by Daniel Root

One of the most useful tools for .NET development is Lutz Roeder's .NET Reflector, now in version 5.  It uses reflection to peek inside .NET assemblies and disassembles the IL back into C# or VB code for those times that you need an in-depth look into any .NET library.  Ever wonder what the code for System.String looked like? This release adds some really nice features:

  • Formatted code comments- doubles as a documentation browser for XML code-commented members
  • 'Expand members' in disassembler lets you see code for an entire class at once- previously you had to look at each method separately.
  • New analyzer features shows where classes are instantiated and exposed.
  • Search Google or MSDN for a member

In addition to helping you debug code, this is also a great learning tool.  What better way to understand framework development than to peek inside The Framework itself?

 

 

Posted by Daniel Root

Tuesday, February 13, 2007

LifeCycle regularly uses FxCop to check our code for conformance to the Microsoft Patterns & Practices Design Guidelines.  This tool analyzes an assembly against rules governing good naming, security, and performance.  Where a problem is found, FxCop gives you a link to more MSDN guidance on the issue.  Not only a great quality assurance tool, but a good learning tool as well. 

But on the horizon are a crop of new code analysis tools that take the concept to the next level.  CodeIt.Right takes a similar approach- analyzing code and providing a list of violations.  However, CodeIt.Right also bakes in refactoring.  Not only does it tell you your Serializeable type should inherit ISerializable, but with one click, it will make the fix for you. 

NStatic analyzes code and reports on violations in an extremely readable graphical overlay displayed ontop of your code.  As far as I can tell, the violations it targets tend to be more subtle flaws in logic within procedures.

Neither is ready for prime time- CodeIt.Right is in beta and was a little buggy in my testing and NStatic isn't available to the public at all yet.  Still, if your interested in writing quality code, these are two products to keep bookmarked.

Posted by Daniel Root

Thursday, February 01, 2007

So, our Action Pack came this week, and I installed Office 2007.  I'm loving the sleek new ribbon UI goodness, but one thing was bugging me in Outlook 2007's email editor.  When composing a new email, the font size looked way too big.  It was set to Tahoma 10, and when I sent the message, it looked fine.  Not a huge problem, but I want WYSIWYG!  I Googled, but apparently I'm the only one picky enough to care.

It turns out it's zoomed to 200% by default, but the zoom tool isn't there!  To fix:

Outlook -> New -> RT Click top of ribbon -> Customize Quick Access -> Customize -> All Commands -> Zoom -> Add

The zoom button should appear in the top left. Then click inside the message, click the zoom button, and choose 100%.

Seems like this could be a problem if users crank their font down when composing, and send tinsy little hard-to-read emails. 

Posted by Daniel Root

Monday, January 29, 2007

Scott Guthrie has a new post with a nice 25 minute video introduction into the next version of Visual Studio, showing off the almost fully-baked LINQ-to-SQL functionality with an ASP.NET example.   I can't wait to code this way!

Posted by Daniel Root

© 2006 LifeCycle Solutions, LLC | All Rights Reserved