Archive for the ‘Uncategorized’ Category


You are currently browsing the archives for the Uncategorized category.

Archives

  • Categories

  • Enabling Sliding Expiration With Windows Identity Foundation & MVC

    Wednesday, 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;

          }

    }

    Isolating Your Configuration Files For Testability

    Tuesday, 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.

    MvcConf – Virtual ASP.Net MVC Conference

    Friday, July 9th, 2010

    Check out the free online MVC Conference here . There’s more information over at Los Techies to.

    Visual Studio Rename Shortcut

    Wednesday, June 16th, 2010

    This is more for me than anything else as I can never remember the keyboard short cut to use the build in “Rename” functionality that is built into Visual Studio 2008, and probably 2010 though I haven’t tested it.

    Anyway its Shift + Alt + F10

    IIS 6 Binding Error

    Monday, November 9th, 2009

    I’ve just been playing around with IIS until finally I couldn’t start my web site as each time I got the following exception:

    The virtual site ’1′ has been invalidated and will be ignored because valid site bindings could not be constructed, or no site bindings exist.

    It turned out that I had broken the IIS Bindings.

    To get it working again I had to do the following:

    1. Right click on the web site properties
    2. Navigate to the Web site tag.
    3. Select the Advanced Button.

    In the end the settings on this screen had got messed up by resetting them so that they looked like this got it working again for me.

    IIS


    Get Free Typemock licenses – ASP.NET bundle launch

    Tuesday, May 19th, 2009

    Unit Testing ASP.NET? ASP.NET unit testing has never been this easy.

    Typemock is launching a new product for ASP.NET developers – the ASP.NET Bundle - and for the launch will be giving out FREE licenses to bloggers and their readers.

    The ASP.NET Bundle is the ultimate ASP.NET unit testing solution, and offers both Typemock Isolator, a unit test tool and Ivonna, the Isolator add-on for ASP.NET unit testing, for a bargain price.

    Typemock Isolator is a leading .NET unit testing tool (C# and VB.NET) for many ‘hard to test’ technologies such as SharePointASP.NET,MVCWCF, WPF, Silverlight and more. Note that for unit testing Silverlight there is an open source Isolator add-on called SilverUnit.

    The first 60 bloggers who will blog this text in their blog and tell us about it, will get a Free Isolator ASP.NET Bundle license (Typemock Isolator + Ivonna). If you post this in an ASP.NET dedicated blog, you’ll get a license automatically (even if more than 60 submit) during the first week of this announcement.

    Also 8 bloggers will get an additional 2 licenses (each) to give away to their readers / friends.

    Go ahead, click the following link for more information on how to get your free license.

    Web Development Interviews

    Thursday, April 2nd, 2009

    Now I realise that perhaps, this being a business blog on our business website, that maybe the tone of the posts I am making at present should be a little more sensitive to the business we are trying to garner. Guys, let me know and I will remove these at the drop of a hat. But I am a strong believer in getting to know the “people” you are working with. As the agile manifesto says “People over process” (or as they say it “Individuals and interactions over processes and tools “).

    Well, I spend waaaaaay too much time doing loads of really serious stuff, which I thoroughly enjoy, but every now and again I come across something that is absolutely brilliant and needs to be shared. This is one of them.

    The guys over at xtranormal have done, quite simply, an astonishing job of producing a stunning web application. I urge you, go, waste an evening, say something, anything and post the results in the comments of this blog. I would love to see what you come up with.

    Me, being a passionate and somewhat geeky and opinionated web developer, built this as my first offering. I will post more should I get another evening to play :) .

    Enjoy

    Why SCRUM will never be the same to me again

    Wednesday, April 1st, 2009

    In my first foray into SCRUM we have had a great deal of success in ensuring widespread understanding of development issues and progress. This has led to a great sense of cohesive development, with everyone aware of and looking out for other issues and I would wholeheartedly recommend it to anyone.
    While outlining this to a colleague at work I came up with the following summary of my experience with SCRUM.

    • Catchup – gives everyone a chance to understand what happened yesterday and intentions for today’s development, keeps everyone informed.
    • Understanding – sharing intentions and discussing risks and issues found during development, at a very high level, has helped the team approach things in a great way with a real sense of developing as a team.
    • No Timelines – this is a SCRUM meeting, not a project management meeting. Estimates, and deadlines are not discussed in the confines of the SCRUM meeting. If anyone is having issues, it is raised offline with the project manager where appropriate.

    Of course, within seconds, my colleague had noted the acronym that comes out of that lot. And that is why SCRUM meetings will never be the same for me again.

    Anyone who works with me should need no more than one guess as to whom the insightful developer is :)

    The best iPod docking station in the world – EVER!

    Friday, March 13th, 2009

    I realise that this is neither development nor business focussed, but some things just have to be shared anyway.

    I have never wanted an iPod – of any variety. I bow down before Apple for their mastery of the UX and simplicity in interaction. Without doubt they rule. However I have always found that cheaper and more fully featured options have abounded too. But…….

    Today I came across the best iPod docking station in the world – EVER! and now I think I really want one, just for the docking station. I hope these guys take this to mass market production, because they will make a fortune.

    Enjoy it…….. and then leave a comment on their site requesting one :)