Paulo Morgado

.NET Development & Architecture

This Blog

Syndication

Search

Tags

News

Unit Test Today! Get Typemock Isolator!

Projects

Books

 

Visitors

Visitor Locations

Community

Email Notifications

Archives

Profile

Disclaimer

The opinions and viewpoints expressed in this site are mine and do not necessarily reflect those of Microsoft, my employer or any community that I belong to. Any code or opinions are offered as is. Products or services mentioned are purchased by me, made available to me by my employer or the manufacturer/vendor which doesn't influence my opinion in any way.

February 2007 - Posts

TypeMock.NET Version 3.7.0 is now available

 

TypeMock announced that Version 3.7.0 of Type.NET is now available.

A few of the new features included in this release are:

  • You can now mock mscorlib interfaces. Enterprise Edition only
  • Vista support is now complete.
  • You can fire Multiple instances of Event . Professional version only.
  • Integration with QASystem AQTime.
  • It is possible to mock hidden base methods using Mock.CallBase
  • Automatic Support for Singletons:
    When using Natural TypeMocks™, TypeMock will automatically detect Singletons and mock them accordingly.
    There is no need to mock them separately.
  • More Reflective Mock Expectations. More expectations methods were added: ExpectUnmockedGet and ExpectUnmockedSet.

For more details see release notes.

I've been using a beta version of TypeMock.NET 3.7 and I'm very happy with it.

Posted Wed, Feb 21 2007 8:50 by Paulo Morgado | with no comments

Reflector 5 Released

Just read on Scott Hanselman's blog that Reflector 5 is out.

Posted Tue, Feb 20 2007 22:48 by Paulo Morgado | with no comments

Microsoft Virtual PC 2007 is out

Go to http://www.microsoft.com/windows/virtualpc/ and find all about it.

Posted Tue, Feb 20 2007 17:54 by Paulo Morgado | with no comments

Developer Tools for Internet Explorer

For the past months I've been developing ASP.NET infrastructure (authentication, authorization, profile, membership and resource providers). My job is not building web pages. My job is make the lives of web page developers a lot easier (well, they might not agree with me on that).

Nevertheless, when developing authentication providers I need to know when and where to redirect requests and to control how many postbacks are occurring.

To help developers on their tasks there are a few tools for Internet Explorer that can be used.

Internet Explorer Developer Toolbar Beta 3

This a free tool from Microsoft that helps you mostly with HTML issues.

The announced features are:

  • Explore and modify the document object model (DOM) of a Web page.
  • Locate and select specific elements on a Web page through a variety of techniques.
  • Selectively disable Internet Explorer settings.
  • View HTML object class names, ID's, and details such as link paths, tab index values, and access keys.
  • Outline tables, table cells, images, or selected tags.
  • Validate HTML, CSS, WAI, and RSS Web feed links.
  • Display image dimensions, file sizes, path information, and alternate (ALT) text.
  • Immediately resize the browser window to a new resolution.
  • Selectively clear the browser cache and saved cookies. Choose from all objects or those associated with a given domain.
  • Choose direct links to W3C specification references, the Internet Explorer team weblog (blog), and other resources.
  • Display a fully featured design ruler to help accurately align and measure objects on your pages.
  • Find the style rules used to set specific style values on an element.
  • View the formatted and syntax colored source of HTML and CSS.
  • Style Tracer: Right mouse click on a style value for an element and select Style Tracer to find the style rule that is effecting that value.
  • CSS Selector Matches: View a report of all style rules set and how many times they are used on the current page.
  • View Source: View the formatted and syntax colored source of the original page, currently rendered page, element or element with the styles that are effecting it.

    You can find more information on the Internet Explorer Developer Toolbar at its Channel 9 Wiki page.

    I had to uninstall the beta 3 version because it either hangs or kills Internet Explorer.

    If you need HTTP debugging, you'll need the Fiddler Tool, but that's outside of Internet Explorer.

    Web Development Helper

    This is a free tool from Nikhil Kothari that provides HTTP tracing, client-side script diagnostics and tracing, as well as an immediate window.

    For ASP.NET developers, when developing against your site on your local development machine, this tool provides the ability to view ViewState, ASP.NET trace messages, contents of your cache etc.

    The following is a list of features offered by the tool:

    • A warning when either debug or trace have been turned on. Ability to hide trace information from the page, and view it in a separate dialog, so it does not get in the way of your page's layout.
    • Ability to view the page's view state (in various forms: raw, parsed, and decoded) to help you optimize your state management logic.
    • Ability to view items stored in cache, and remove them for testing purposes.
    • Ability to shutdown the application (unloading the associated AppDomain), in order to test starting it from a clean state.
    • Ability to log all HTTP (and HTTPS) traffic between the browser and your server, and view request and response details, including those performed via XMLHttpRequest.
    • Ability to view the live HTML DOM using a DOM Inspector that allows viewing all elements, selected elements, or elements matching ID or CSS class. For each element, you can see the markup, attributes, and style attributes.
    • Ability to view rich error information for script errors (full call stack, script URL and line number), as well as a script immediate window to execute some script against the current document.

    I haven't tested this tool myself but I saw a friend of mine using it and it messed with all those characters (ãçõ) that we, Portuguese people, have the hasty habit of using. So, I never even downloaded it.

    HttpWatch

    This is a tool from Simtec Limited and has both a Basic (free) and a Professional (paid) version.

    HttpWatch Feature List

    Support is provided by e-mail or telephone.

    IEWatch

    This is a tool from IEWatch Software LLC and has no free version.

    IEWatch Feature List

    HTTP Features

    • Captures HTTP and HTTPS - HTTP(s) headers including authentication headers, status codes, Cookies, URLs, POST data, Query Strings and Response Content are recorded.
    • Export Data - The HTTP Log can be saved in various formats, including XML, comma separated and text format. The XML structure is described in the XML Schema.
    • Filters - IEWatch allows the most extensive filtering, including filters on HTTP headers and response content. You can store up to seven Filter definitions.
    • Find in HTTP Log - HTTP search functionality that displays the results in separate panes. Unlike the filter operation, the Find in HTTP Log function can be applied after browsing to repeatedly search in the HTTP log.
    • Dynamic HTTP Header help - Comprehensive help for HTTP headers and status codes are available by simply pressing the F1-key.
    • Compare Requests - IEWatch allows comparing two requests using an external diff utility, for example Microsoft® WinDiff.
    • HTTP Notes - You can use notes to tag specific HTTP requests. Notes can be useful to relate HTTP requests to HTML pages.
    • HTTP Performance Charts - Use the Timeline Chart to spot performance bottlenecks and to tune the performance of your web site.
    • Automation Interface - You can use the automation interface to integrate IEWatch with your favorite testing framework.
    • Docking Windows - Configure your work area with Visual Studio® style docking windows.

    HTML Features

    • Tree view of the HTML structure - The tree view reflects exactly the structure of the HTML page even if the page contains many sub documents. You can drill down on HTML elements to display details on links, images, scripts, style sheets, applets, ActiveX objects and forms.
    • Page Summary - The Page Summary window displays statistical information on the web page including page load time and page weight.
    • Image List - IEWatch shows you the image size, height, width and the download time of the image in one glance.
    • HTML Designer - Allows visual HTML modification by clicking and editing items in the web page.
    • Rapid Prototyping - You can modify the HTML Style Sheets and Scripts of any web page to quickly test code or develop prototypes without having to create development environments.
    • Script Debugging - Use the Immediate window to trace debug messages, evaluate variables or issue commands.
    • Highlight HTML elements - Locate and highlight HTML elements in the HTML code window. This feature applies to any link, image, applet, ActiveX control or form element.
    • HTML Spotlight - This feature allows quick pinpointing of any element in the HTML code by directly clicking in the web page (Patent Pending).
    • Docking Windows - Configure your work area with Visual Studio® style docking windows.

    IEWatch Tools

    • Capture Screenshot - Take screenshots of a complete web page or Internet Explorer window and email or save the screenshot.
    • Window Transparency - You can apply transparency to the IE window which is useful for comparing a modified page or image to the original. Additionally you can apply transparency to the IEWatch window to monitor HTTP traffic while viewing the web page.
    • Resize IE Window - This tool allows developers to resize and fine tune web pages to different screen sizes.
    • Color Picker - You can pick the color of any pixel on the screen or you can choose a color in the color palette. This tool integrates seamlessly with the rapid prototyping features.

    Support is provided by e-mail through a web form. There is also an online FAQ.

  • Your Own

    And you can always build your own Browser Helper Object (BHO).

    Posted Sun, Feb 18 2007 22:41 by Paulo Morgado

    Unit Testing and Mock Frameworks

    I'm not a big fan of Test Driven Development (TDD), but I love Unit Testing.

    But to be productive on unit testing I need a good framework for Mock Objects. I can't expect to be productive and have to build a lot of mock classes to test other classes. And, who tests the mock classes?

    Mock objects simulate the behavior of real objects when they are difficult or impossible to obtain.

    I've been testing a few mock frameworks and this is my opinion (*) on the ones I've tested.

    NMock

    I've been introduced to NMock by Jean-Paul Boodhoo and his series of articles (MSDN) and shows (dnrTV).

    NMock is an open source project that you can use, providing you abide to their conditions.

    NMock is expectation based and has one really neat feature that I like: the ability to scope the mocks. I can write a test like this:

    using (Mockery mockery = new Mockery())

    {

        ISomeInterface instance = mockery.NewMock<ISomeInterfac>();

        Expect.Once.On(instance).Method("SomeMethod").With(Is.EqualTo(SomeValue)).Will(Return.Value(true));

        Assert.IsTrue(instance.SomeMethod(SomeValue));

    }

    As you can see, you just define a mock scope by instantiating a Mockery object and disposing of it in the end. In between, you just declare what you expect to happen.

    What I don't like is the fact that I don't have compile time checking on the mocked members. If I need to do some refactoring on ISomeInterface I will have to go all over my tests and change the strings defining ISomeInterface's members.

    At this time NMock doesn't handle mocking Generics, which makes it useless to me.

    Support is mainly provided through a community group.

    NMock also seems to be a dead project at this time.

    Rhino.Mock

    Through MockObjects.com I came to Rihno.Mocks. Rihno.Mocks is the result of Ayende's open source project and free to use, providing you abide to his conditions.

    As I understand it, Rhino.Mocks has dropped the scope feature present in NMock but, besides the expectation mechanism, it has a recording mechanism. It's as easy as follows:

    MockRepository mocks = new MockRepository();

     

    IDemo demo = mocks.CreateMock<IDemo>();

    // Setting up an expectation for a call to IDemo.VoidNoArg   

    demo.VoidNoArg();   

    mocks.ReplayAll();   

    // Fullifying the expectation for call to IDemo.VoidNoArg   

    demo.VoidNoArg();

     

    mocks.VerifyAll();

    However, the last version of Rhino.Mocks I tested didn't support mocking Generics, which (as I said before) makes it useless to me. But there's hope, a new version is on the way.

    Support is mainly provided through a community group.

    TypeMock.NET

    This is my favorite. Have you ever thought you could do this?

    string username = "test";

     

    using (RecordExpectations recorder = RecorderManager.StartRecording())

    {

        recorder.ExpectAndReturn(HttpContext.Current.ApplicationInstance.User.Identity.Name, username);

    }

     

    string expected = username;

     

    Assert.AreEqual(expected, HttpContext.Current.ApplicationInstance.User.Identity.Name);

     

    TypeMock.MockManager.Verify();

    Well, you will on the next release.

    And you can mock classes with generic methods:

    public class Test { public T DoIt<T>(T t) { return t; } }

     

    [TestMethod()]

    public void NaturalMockTest()

    {

        MockManager.Init();

        Mock testMock = MockManager.Mock(typeof(Test));

     

        Test t = new Test();

     

        Assert.AreEqual(3, t.DoIt(3));

        Assert.AreEqual("something", t.DoIt("something"));

    }

    TypeMock has 3 versions: Community, Professional and Enterprise. The Community version is free but you will have to pay for the other two.

    TypeMock supports two types of mocks: Reflective Mocks and Natural Mocks™.

    TypeMock's Reflective Mocks by declaring the behavior of classes using its members' names:

    public bool IsAuthenticated(string name, string password)

     

    {

        Logger.Log(Logger.NORMAL, "Entering Authentication");

        try

        {

            // do something

            int Results = DoSelect(statement);

            bool isOk = Results == 1;

            if (isOk)

            {

                Logger.Log(Logger.NORMAL, "User Authenticated " + name);

            }

            else

            {

                Logger.Log(Logger.SECURITY, "User login failed " + name);

            }

            return isOk;

        }

        catch (Exception ex)

        {

            Logger.Log(Logger.FAILED, "Login system failure", ex);

            // handle exception

        }

    }

     

    [TestMethod]

    public void Authenticated()

    {

        Authentication authenticator = new Authentication();

        // Initialize Type Mocks (This can be done in the [Setup])

        MockManager.Init();

        // the Logger class is now being mocked

        Mock logMock = MockManager.Mock(typeof(Logger));

        // set up our expectations for 2 Log calls in IsAuthenticated

        // 1) "Entering Authentication" Log at first line

        // 2) "User login failed user" Log

        logMock.ExpectCall("Log");

        logMock.ExpectCall("Log");

     

        // authentication should fail

        Assert.IsFalse(authenticator.IsAuthenticated("user", "password"));

        // Verify that all calls were made (This can be done in the [Teardown])

        MockManager.Verify();

    }

    Natural Mocks™ on the other hand, support recording of expectations:

    [TestMethod]

    public void Authenticated()

    {

        Authentication authenticator = new Authentication();

        // set up our expectations for 2 Log calls in IsAuthenticated

        // 1) "Entering Authentication" Log at first line

        // 2) "User login failed user" Log

        using (RecordExpectations recorder = RecorderManager.StartRecording())

        {

            // CAUTION: ALL calls here are mocked!!!

            Logger.Log(Logger.NORMAL, null); // 1

            Logger.Log(Logger.NORMAL, null); // 2

        }

        // Thats it folks

     

        // authentication should fail

        Assert.IsFalse(authenticator.IsAuthenticated("user", "password"));

        // Verify that all calls were made (This can be done in the [Teardown])

        MockManager.Verify();

    }

    Too bad you can only have this on the Professional and Enterprise versions, but you'll get other stuff like code coverage and NAnt and MSBuild support.

     

    TypeMock doesn't support mock scopes. Also makes no use of Generics forcing us to a constant use of casts.

    TypeMock has support forums in its site and a great e-mail support. And they listen to suggestions (at least to, mine).


    This is just my opinion on these mock frameworks and not an extensive analysis of mock frameworks or even the ones mentioned.

    Posted Sat, Feb 17 2007 23:51 by Paulo Morgado | 12 comment(s)

    ASP.NET Controls - The Bridge between Client and Server-Side

    Nuno has just published his second article on a series about ID generation for ASP.NET controls.

    Posted Thu, Feb 8 2007 15:45 by Paulo Morgado | with no comments

    WSDL Merger

    António Cruz posted his tool to merge WSDL definitions into a single WSDL file.

    Posted Thu, Feb 8 2007 10:40 by Paulo Morgado | 2 comment(s)

    ASP.NET Controls - Understanding id generation

    Nuno has just published his first article on a series about ID generation for ASP.NET controls.

    Posted Tue, Feb 6 2007 1:54 by Paulo Morgado | with no comments

    What's wrong with ASP.NET provider model? - The RoleProvider

    Again, the lack of IIdentity in the API.

    With identities like the WindowsIdentity, the user's username (the name property) has no use for the system. The important part is the user's token.

    If you would follow the path (using Reflector) from the call to Roles.GetRolesForUser() until the reply from WindowsTokeRoleProvider.GetRolesForUser(string username), you would see the following steps:

    1. System.Web.Security.Roles.GetRolesForUser() gets the current user's username from the current user's identity.
    2. System.Web.Security.Roles.GetRolesForUser(string username) is called with the name from the previously obtained identity.
    3. If the default role provider is the WindowsTokenRoleProvider, WindowsTokeRoleProvider.GetRolesForUser(string username) is called.
    4. WindowsTokeRoleProvider.GetRolesForUser(string username) gets the current user's username from the current user's identity. If the provided username matches the name in the current identity, the token is retrieved from the identity and used to get the user's roles. If it's not a match, an exception is thrown.

    Wouldn't it be better if it was just as simple as this?

    1. System.Web.Security.Roles.GetRolesForUser() gets the current user's identity and uses it to call WindowsTokeRoleProvider.GetRolesForUser(IIdentity user).
    2. WindowsTokeRoleProvider.GetRolesForUser(IIdentity user) checks if the provided user is a WindowsIdentity. If it is, the token is retrieved from the identity and used to get the user's roles. If it's not, an exception is thrown.

    This enhancement could be achieved within the Orcas timeframe, just by adding a few overloads to the Roles and RoleProvider classes.

    public class RoleProvider
    {
        // ...
    
        /// <summary>
        /// Gets a list of the roles that a specified user is in for the configured applicationName.
        /// </summary>
        /// <param name="user">The identity to return a list of roles for.</param>
        /// <returns>
        /// A string array containing the names of all the roles that the specified user is in for the configured applicationName.
        /// </returns>
        public virtual string[] GetRolesForUser(IIdentity user)
        {
           return this.GetRolesForUser(user.Name);
        }
    
        /// <summary>
        /// Gets a value indicating whether the specified user is in the specified role for the configured applicationName.
        /// </summary>
        /// <param name="user">The user identity to search for.</param>
        /// <param name="roleName">The role to search in.</param>
        /// <returns>
        /// true if the specified user is in the specified role for the configured applicationName; otherwise, false.
        /// </returns>
        public virtual bool IsUserInRole(IIdentity user, string roleName)
        {
            return IsUserInRole(user.Name, roleName);
        }
    }
    
    public static class Roles
    {
        // ...
    
        /// <summary>
        /// Gets a list of the roles that the currently logged-on user is in.
        /// </summary>
        /// <exception cref="T:System.Configuration.Provider.ProviderException">Role management is not enabled.</exception>
        /// <exception cref="T:System.ArgumentNullException">There is no current logged-on user.</exception>
        /// <returns>
        /// A string array containing the names of all the roles that the currently logged-on user is in.
        /// </returns>
        public static string[] GetRolesForUser()
        {
              return Roles.GetRolesForUser(Roles.GetCurrentUser());
        }
    
        /// <summary>
        /// Gets a list of the roles that the currently logged-on user is in.
        /// </summary>
        /// <param name="user">The identity to return a list of roles for.</param>
        /// <exception cref="T:System.Configuration.Provider.ProviderException">Role management is not enabled.</exception>
        /// <exception cref="T:System.ArgumentNullException">There is no current logged-on user.</exception>
        /// <returns>
        /// A string array containing the names of all the roles that the currently logged-on user is in.
        /// </returns>
        public static string[] GetRolesForUser(IIdentity user)
        {
            // ...
            
            roles = Roles.Provider.GetRolesForUser(user);
    
            // ...
        }
    }

    Then, the existing providers could be optimized according this new arhitecture.

    If you agree with me, vote in my suggestion.

    Posted Mon, Feb 5 2007 23:04 by Paulo Morgado | with no comments

    Visual Studio Team Edition Bug: Incorrect creation of unit test for public property with a private

    I just opened this bug in Connect. If you are experencing it too, vote to be fixed.

    Posted Mon, Feb 5 2007 0:27 by Paulo Morgado | with no comments

    Great tool: Refactor! for ASP.NET beta 2.1.3 is now available (free download to all)

    The public build of Refactor! for ASP.NET is here:

    http://www.devexpress.com/refactorasp

    This version works in VS 2005 and is suitable for public consumption.

    Refactor! for ASP.NET is a free and supported product from Developer Express. It includes 25 refactorings, nine of which are dedicated to ASP.NET development (the other 16 work in VB and C# code-behind files).

    Usage

    After installing, start VS, open an ASP.NET project and simply select or move the caret to the code you want to change.

    A smart tag will appear indicating one or more available refactorings. Use the mouse or press Ctrl+` (Ctrl plus the back-tick key). You may create an alternate shortcut binding to the "CodeRush.Refactor" command on the
    Keyboard page of the VS 2005 Options dialog. If you press the Refactor! key (Ctrl+`), you'll see a menu of available refactorings for the code selection or element at the caret. If only one refactoring exists, that refactoring will be applied instantly and you'll see a red arrow indicating which refactoring was applied.

    Training Videos

    12-minute training video (1024x768):
    http://www.devexpress.com/Products/NET/IDETools/RefactorASP/Presentation/Refactor_for_ASP_NET/

    Same training video, full size (for larger monitors):
    http://www.devexpress.com/Products/NET/IDETools/RefactorASP/Presentation/Refactor_for_ASP_NET_Full/

    Screen Shots

    Support

    ASP.NET developers should contact support@devexpress.com with any questions, issues, or suggestions concerning this product.

    Developer Express has also established a newsgroup at news.devexpress.com: devexpress.public.refactor.asp

    Their developers monitor this newsgroup.

    Content

    This drop includes 25 refactorings, nine of which are dedicated to ASP.NET development:

    • Add Validator
    • Extract ContentPlaceHolder
    • Extract ContentPlaceHolder (and create master page)
    • Extract Style (Class)
    • Extract Style (id)
    • Move to Code-behind
    • Move Style Attributes to CSS
    • Rename Style
    • Surround with Update Panel

    This drop also includes 16 standard refactorings that work inside *.cs and *.vb code-behind files (most of these refactorings also work on code placed inside <script> tags):

    • Extract Method
    • Extract Property
    • Flatten Conditional
    • Inline Temp
    • Introduce Constant
    • Introduce Local
    • Move Declaration near Reference
    • Move Initialization to Declaration
    • Reorder Parameters
    • Rename
    • Replace Temp with Query
    • Reverse Conditional
    • Safe Rename
    • Simplify Expression
    • Split Initialization from Declaration
    • Split Temporary Variable

    Known Issues

    • Extract Style (Class) and Extract Style (id) are not available inside content pages. We will address this in a future release.
    • Surround with Update Panel does not modify the Web.Config file. We are still deciding whether it makes sense to change this or whether it makes more sense to suppress availability of the refactoring if the project is not set up to exploit AJAX.

    Posted Sun, Feb 4 2007 21:13 by Paulo Morgado | with no comments