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.

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).

    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.

    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.