Archives

  • Categories

  • Meta

    Wire-framing with PowerMockups

    August 28th, 2011

    As a web developer, there are often times when you want to get across a layout or display transitions and interactions interactively to a client in order to speed up the design process and encourage rapid feedback and iteration cycles. I have tried a number of wire-framing tools ranging from straight up PSDs to Balsamiq to Expression Blend SketchFlow, each of which definitely has their pros and cons in relation to ease of use, speed to develop, ability to incorporate feedback etc.

    A little while ago I came across a wire-framing tool which is a plug-in for Office PowerPoint at http://www.powermockup.com/. These guys have put together a tool which works seamlessly with PowerPoint and enables users to very quickly and easily create wireframes which can then easily be distributed. Thanks to the inbuilt functions of PowerPoint, clients or users can then amend the files with their own comments, or move things around themselves and return.

    I figured one of the easier ways to test this would be to do a wireframe version of the site the tool came from :) . For those interested, this is the PowerPoint file I created.

    I was amazed that with no training, and no reading or education, I was able to start getting effective very quickly. The whole site was done in less than an hour! See what I mean about rapid iterations for feedback cycles? I need to play a little more with some of the inbuilt animations of PowerPoint to see how easily integrated easing animations can be brought into things but I am very hopeful.

    Overall I was very impressed with the tool; I shall definitely be using and recommending it with other clients and developers (those on the Microsoft stack at least).

    Enabling Sliding Expiration With Windows Identity Foundation & MVC

    May 25th, 2011

    It appears that out of the box Windows Identity Foundation only allows fixed length for sessions. So if your STS service is configured to expire after 15 minutes (the default is 60 minutes) then your security token will be invalid after 15 minutes from the first time you log on regardless of whether or not your session was active.

    Currently the only way to implement sliding expiration is manually through code. I banged my head against this for a number of hours yesterday and did find a number of solutions out there none of them complete. In the end adding this code to the global.asax of the web site did the trick. It requires reissuing the security token at which point you can set when the token IsValidTo property of the token to whatever you require.

     

    protected void SessionAuthenticationModule_SessionSecurityTokenReceived(object sender, SessionSecurityTokenReceivedEventArgs e)

    {

        var sessionToken = e.SessionToken;

        SymmetricSecurityKey symmetricSecurityKey = null;

     

        if (sessionToken.SecurityKeys != null)

            symmetricSecurityKey = sessionToken.SecurityKeys.OfType<SymmetricSecurityKey>().FirstOrDefault();

     

        Condition.Requires(symmetricSecurityKey, "symmetricSecurityKey").IsNotNull();

     

        if (sessionToken.ValidTo > DateTime.UtcNow)

        {

            var slidingExpiration = sessionToken.ValidTo - sessionToken.ValidFrom;

     

            e.SessionToken = new SessionSecurityToken(

                        sessionToken.ClaimsPrincipal,

                        sessionToken.ContextId,

                        sessionToken.Context,

                        sessionToken.EndpointId,

                        slidingExpiration,

                        symmetricSecurityKey);

     

            e.ReissueCookie = true;

         }

         else

         {

            var sessionAuthenticationModule = (SessionAuthenticationModule) sender;

     

            sessionAuthenticationModule.DeleteSessionTokenCookie();

     

            e.Cancel = true;

          }

    }

    Mindscape Phone Elements giveaway

    March 15th, 2011

    Those fantastic (and seriously clever) folks at Mindscape are giving away Developer licences for their Windows Phone 7 Phone Elements products. As a pleasant surprise for our launch we’re offering free licenses to any developer who wants to try the very best suite of WP7 controls on the market

    This product set, worth $299, is the world’s first comprehensive suite of Windows Phone 7 controls – great standard controls, powerful charting capabilities and a slick gesture library

    They are limiting the offer  to 750 licences so don’t hang about, get one now :)

    Apple relaxes restrictions on IOS third party development tools

    September 10th, 2010

    Yesterday Apple launched a statement relaxing there previous restrictions on third party development tools.

    This is great news for MonoTouch developers as it looks like the future is much clearer now..

    Integrating StructureMap with WCF 4.0 REST Services

    August 16th, 2010

    Ok first things first this post borrows a lot of code from  Jimmy Bogard’s post from a couple of years ago entitled Integrating StructureMap With WCF so credit where credits due. However there are a couple of minor changes that you need to make in order to get StructureMap to work properly with your WCF RESTful service.

     

    Create A Custom Instance Provider

    This code is identical to Jimmy’s original code.

    public class StructureMapInstanceProvider : IInstanceProvider

    {

        private readonly Type _serviceType;

     

        public StructureMapInstanceProvider(Type serviceType)

        {

            _serviceType = serviceType;

        }

     

        #region IInstanceProvider Members

     

        public object GetInstance(InstanceContext instanceContext)

        {

            return GetInstance(instanceContext, null);

        }

     

        public object GetInstance(InstanceContext instanceContext, Message message)

        {

            return ObjectFactory.GetInstance(_serviceType);

        }

     

        public void ReleaseInstance(InstanceContext instanceContext, object instance)

        {

        }

     

        #endregion

    }

     

    Create A Custom Service Behaviour Class

    This code is identical to Jimmy’s original code.

    public class StructureMapServiceBehaviour : IServiceBehavior

       {

           #region IServiceBehavior Members

     

           public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)

           {

               foreach (var endpointDispatcher in

                   serviceHostBase.ChannelDispatchers.OfType<ChannelDispatcher>().SelectMany(

                       channelDispatcher => channelDispatcher.Endpoints))

               {

                   endpointDispatcher.DispatchRuntime.InstanceProvider =

                       new StructureMapInstanceProvider(serviceDescription.ServiceType);

               }

           }

     

           public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase,

                                            Collection<ServiceEndpoint> endpoints,

                                            BindingParameterCollection bindingParameters)

           {

           }

     

           public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)

           {

           }

     

           #endregion

       }

     

    Create A Custom Service Host

    This code is almost identical to Jimmy’s. The only difference is that your custom class should inherit from the WebServiceHost class rather than the normal ServiceHost class for normal WCF Services.

    public class StructureMapWebServiceHost : WebServiceHost

    {

        public StructureMapWebServiceHost()

        {

        }

     

        public StructureMapWebServiceHost(object singletonInstance, params Uri[] baseAddresses) : base(singletonInstance, baseAddresses)

        {

        }

     

        public StructureMapWebServiceHost(Type serviceType, params Uri[] baseAddresses) : base(serviceType, baseAddresses)

        {

        }

     

        protected override void OnOpening()

        {

            Description.Behaviors.Add(new StructureMapServiceBehaviour());

            base.OnOpening();

        }

    }

     

    Create A Custom Service Host Factory

    Once again this code is almost identical to Jimmy’s. The only difference is that we inherit from WebServiceHostFactory rather than the usual ServiceHostFactory class.

    /// <summary>

    /// StructureMap Service Host Factory for WCF REST Services

    /// </summary>

    public class StructureMapWebServiceHostFactory : WebServiceHostFactory

    {

        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)

        {

            return new StructureMapWebServiceHost(serviceType, baseAddresses);

        }

    }

     

    Wiring Up Our Route

    In our Global.asax file create our route using the StructureMapWebServiceHostFactory rather than the normal WebServiceHostFactory.

    public class Global : HttpApplication

    {

        void Application_Start(object sender, EventArgs e)

        {

            IoC.RegisterDependencies();

     

            RegisterRoutes();

        }

     

        private void RegisterRoutes()

        {       

            RouteTable.Routes.Add(new ServiceRoute("ReferenceData", new StructureMapWebServiceHostFactory(), typeof(ReferenceData)));

        }

    }

    MVC 3 Preview Is Out…

    July 28th, 2010

      Scott Gu announced yesterday that the new MVC 3 Preview has been released which includes the new Razor View engine…

    Download it from here..

    Isolating Your Configuration Files For Testability

    July 27th, 2010

     

    Ben Hall over at CodeBetter just posted a nice article on using the Castle Dictionary Adapter to isolate your code from the ConfigurationManager class to make your unit tests easier to write.

    I thought I might take the opportunity to talk about a technique that we use to isolate our code from ConfigurationManager and also other system classes such as the system DateTime, using the language constructs built within the .Net Framework version 3.5 and above. I’m not saying that this technique is better than the Castle Dictionary Adapter method but it just highlights an alternative approach that is possible without using third party assemblies.

    Ok so using Ben’s example, because I’m too lazy to think up my own, we have an application configuration value for our EnableNewsLetterSignup.

    <add key="EnableNewsletterSignup" value="false"/>

    In our code we pull out the value using the static method on the ConfigurationManager class like so.

    public bool Signup(string email)

    {

        if (!Boolean.Parse(ConfigurationManager.AppSettings["EnableNewsletterSignup"]))

            return false;

     

        return true; // technically this would go off to an external web service

    } 

    Ok so nothing new here but when it comes to testing this code it means that we have to have a configuration file for our unit test project (which is bad) and we can only ever test one path through the code without changing the value of the configuration file. Which means we some untestable code without doing some configuration Kung Fu on our config file which is more work than we should have to do.

    Wrapping It Up

    The technique we use is to wrap our class up in a static wrapper class which we will call Config. For our corresponding application setting we add a public static field of the same name for clarity, of type Func<string>. Now the important thing is we give it it’s default behaviour which in this case is to go off and use our old friend ConfigurationManager to determine whether or not our newsletter is enabled or not.

    public static class Config

    {

        public static Func<string> EnableNewsletterSignup = () => ConfigurationManager.AppSettings["EnableNewsletterSignup"];

    }

     

    Writing Our Code

    Now going back to our code where we use the application setting it will now look something like this.

    public bool Signup(string email)

    {

        if (!Boolean.Parse(Config.EnableNewsletterSignup()))

            return false;

     

        return true; // technically this would go off to an external web service

    } 

     

    Testing Our Code

    So now when we want to unit test this piece of code we simply change the default behaviour of our Config class to the behaviour we want to test. See line 5 below, where we force it to return false for the purpose of our unit test. We now have total control over what our supposedly configuration value is without ever having to touch the file system.

       1: [Test]

       2: public void If_our_newsletterSignup_is_not_enabled_we_should_not_be_signed_up()

       3: {

       4:     // Arrange

       5:     Congig.EnableNewsletterSignup = () => "false";

       6:  

       7:     // Act

       8:     var isSignedUp = _classUnderTest.Signup("emailaddress@foo.com");

       9:  

      10:     // Assert

      11:     Assert.IsFalse(isSignedUp);

      12: }

     

    Other Uses

    As I said earlier this technique can also be quite useful for isolating other system dependant classes such as code that uses the DateTime.Now property. Sometimes if you want to logic concerning dates and times it can be pretty hard to control the flow of the code because the DateTime is generated by the system. How for example do you test something if you need to be some date in the future or some date in the past. The code below can be used in the same way to isolate our tests from the underlying call to the DateTime.Now which can be overriden as required to give the behaviour we want.

    public static class SystemDateTime

    {

       public static Func<DateTime> Now = () => DateTime.Now;

    }

    Conclusion

    This approach offers an alternative solution to using the Castle Dictionary Adapter,  and although it requires writing slightly more code it does mean that it is one less assembly that you have to reference in your project which can be a good thing sometimes.

    Razor – Unit Testing Your Views in MVC2 with QUnit

    July 19th, 2010

    Ok this is a bit of a follow up from my earlier blog about the newly announced MVC view engine Razor from Scot Guthries blog a couple of  weeks ago. Below is a quote that Scott has made in the comments to the original post.

    “The Razor parser and view engine can be instantiated and used outside of the ASP.NET application domain.  This means you can directly instantiate and use it within a unit test project without any dependencies on running ASP.NET.

    From a unit testing perspective you can indicate the view template you want to run, supply it with any dependencies, and then pass your own test models/viewmodels to it and have it run and render back a string to you. You could then verify that the correct content came back.  This would isolate the views from your controllers and any data access, and allow you to also isolate them from the runtime environment.  View engines in ASP.NET MVC VNext (both Razor and the .ASPX one) will also support and integrate with dependency injection as well.”

    Let’s start with talking about the current testing story with the current MVC framework. Now clearly you want to put as much logic into your controller as possible which is currently testable with the current MVC framework. But on the  modern MVC websites that I’ve been working on there ends up being a considerable amount of JQuery in most pages.

    This is where I hear you shout “but what about QUnit you can test your JQuery with that”  Yes you can but do I do it..No I don’t.  I never really got QUnit it always seemed great in theory but in reality it seemed like too much work to implement.

    Let me elaborate. All the examples I could find when I was starting out with QUnit involved testing some JavaScript discreet function that did some work and returned a value.  For example a function that added two numbers together and gave you the total back. QUnit works really well for that kind of thing. However I don’t find myself writing much of that kind of  logic in JQuery when I am using MVC. I know its possible to do it in JQuery but most of the time I try to push that kind of logic back into the .NET world and onto the server  where it belongs rather than in the browser.

    So typically I find myself writing JQuery that does fairly trivial stuff. Hiding and showing stuff and manipulating items in the Dom. Now when I say trivial it is still important. If you hide your submit button when it should be displayed you have broken your page.

    Now it is possible to test this logic with QUnit, but for each test or  group of tests  you had recreate the HTML for your page or part of your page to test your JavaScript against. It is this that always seemed a bit lame to me. You were never really testing against your view proper but a mock up of your view.  Not only is it a lot more work to write your tests initially but there is a lot more maintenance work to do going forward. Any change to your HTML mark up in your view needs to be replicated across your test HTML.  Now I know you have to do maintenance with your .NET tests but most of the time we have compile-time checking. If you change the name a property on a class and you don’t update your unit test it won’t compile. Change the name of a div in your mark up and forget to implement that in your test HTML and there is nothing to tell you that there is a mismatch.

    To counter this John Teague over at Los Techies outlines a technique that you can use to generate your markup automatically. To be honest I haven’t used this approach as it still seems like a lot of extra hard work, but it’s worth considering.

    Therefore going back to Scott Guthrie’s  comment that we will now be able to  isolate the view from the controller pass in some data and render back a screen  as HTML. This is just fantastic, and for me the last piece in the puzzle with regards to testing. With this functionality it will should be relatively trivial to produce the markup that we can run our QUnit tests against and it means that we are actually testing our view rather than a mock up of it.

    Well done Microsoft I think this is a positive step, and I can’t wait to get my hands on the framework. Keep up the good work.

    Wiring Up A UIScrollView With Interface Builder And Monotouch

    July 18th, 2010

     

    So you want to add a scrollable view to your iPhone/iPad application and you want to use the power of Interface Builder to make it easier. This is how you do it.

    In this example we are going add a vertically scrolling window to an iPhone screen in portrait mode.

    Start by adding your UIScrollView to your view using Interface Builder. It is not possible to actually scroll the view itself within Interface Builder, so select the UIScrollView and move it up so half the view is off the screen. Drag the edge of the screen to make it longer and then add your extra controls to the bottom. Once you are finished drag the view back to its original position so that you can see the top of the screen again.

    Now in Interface Builder select your UIScrollView and look at its size in the Attribute Inspector window. Make a note of the views height, in this example assume it is 756 pixels. Because we don’t want horizontal scrolling in this example the width should be the same as the standard iPhone screen (320 pixels) .

    Finally in Interface Builder make sure you add an outlet between your ViewController and your UIScrollView.

    Go back to your .NET code and open up your view controller. In your ViewDidLoad method override add the following code to set the initial frame and the content size of you scroll view. Notice that the content size has the full dimension of the entire scrollable view eg. 320 pixels wide and 756 pixels high.

    public override void ViewDidLoad()

    {

        scrollView.Frame = new RectangleF(0,0, 320, 460);

     

        scrollView.ContentSize = new SizeF(320, 756);

    }

     

    Now fire up your application in the iPhone Simulator and you should now have a working scrollable view. 

    Command Line Script for Calling REST Based Web Services

    July 13th, 2010

    I have been working with REST based web services recently and whilst reading the very useful and interesting article A Guide to Designing and Building RESTful Web Services with WCF 3.5 hosted on the Microsoft web site. Came across this useful little JavaScript script that can be called from the command line to invoke your  RESTful web services.

    The code is shown below.

    if (WScript.Arguments.length < 2)

    {

       WScript.echo("Client HTTP Request Utility\n");

       WScript.echo("usage: httprequest method uri [options]");

       WScript.echo("  -f filename");

       WScript.echo("  -h headerName headerValue");

       WScript.Quit(1);

    }

    var method = WScript.Arguments.Item(0);

    var uri = WScript.Arguments.Item(1);

    var req = new ActiveXObject("MSXML2.XMLHTTP");

    var filename = null;

    req.Open(method, uri, false);

    
    

    WScript.echo("********* Request ********* ");

    WScript.echo(method + " " + uri + " HTTP/1.1");

    for (i=2; i < WScript.Arguments.length; i++)

    {

        var option = WScript.Arguments.Item(i);

        if (option == "-f")

            filename = WScript.Arguments.Item(i+1);

        if (option == "-h")

        {

            WScript.echo(WScript.Arguments.Item(i+1) + ": " +

                WScript.Arguments.Item(i+2));

            req.setRequestHeader(WScript.Arguments.Item(i+1),

                WScript.Arguments.Item(i+2));

        }

    }

    try

    {

           if (filename != null)

           {

    
    

              var fso = new ActiveXObject("Scripting.FileSystemObject");

              var file = fso.OpenTextFile(filename, 1, false);

              var fileContents = file.ReadAll();

              file.Close();

              WScript.echo(fileContents);

              req.Send(fileContents);

              printResponse(req);

           }

           else

           {

              req.send();

              printResponse(req);

           }

    }

    catch(e)

    {

    
    

       WScript.echo("******* Response ********* ");

       WScript.echo(e.message);

    }

    function printResponse(req)

    {

    
    

       WScript.echo("******* Response ********* ");

       WScript.echo("HTTP/1.1" + " " + req.status + " " + req.statusText);

       var headers = req.getAllResponseHeaders();

       WScript.echo(headers);

       WScript.echo(req.responseText);

    }

    To perform a GET simply type from the command line:

    HttpUtility.js get http://localhost:1189/Service.svc/

    where HttpUtility.js is the file name containing the JavaScript code shown above and the URL of our REST service.

    To perform a POST:

    HttpUtility.js post http://localhost:1189/Service.svc/ –f message.xml -h Content-Type application/xml

    where the –f argument specifies the filename with the message contents and the –h argument indicates the header name and header value.

    The source code can be downloaded from here.