Do you want to “change” your Optus details? Just login. Here are the usernames & passwords.

Security No Comments

For reasons I’ll detail in a separate post I had to enter today in an Optus shop.

And, in a pure display of ignorance to any basic security measures, they had all the usernames and passwords for all the systems where the dealers could connect and do changes to accounts, create new accounts or remove them printed and stuck at the top of the screen.

An no, this was not on a computer somewhere in the back of the store but on a computer in the middle of the room full of people.

optus 

(I’ve reduced the size and quality of the image enough to have all the information impossible to read.)

Not only that I took this picture with my mobile but I managed to get friendly enough to play with the computer after the dealer logged in to a system that I could use to change my personal details (or anyone else’s details). I even did a view source on the (poorly coded) code and tried to hack some URLs together to avoid a post back on the page.

Uh, who, me? Never…

So where do you keep your passwords?

Microsoft SDC Open Day

Personal, Readify No Comments

On Monday the 6th of April Microsoft Australia organized the SDC Open Day 2009 event (SDC stands for [Microsoft] Software Development Centre, part of the Microsoft Services (Australia).

For over six years, Microsoft Australia’s Solutions Development Centre has been successfully delivering complex custom-developed applications for customers. We follow a set of processes that have enabled us to build high-performing teams delivering quality solutions. At the SDC Open Day we talked about how we have achieved this success, sharing our processes and techniques with an audience of software development professionals.

In the presentations below we provide an overview of the SDC, a day in the life for the team and details on how we approach each of the key disciplines in an SDC project team.

Together with few others like Tom Hollander, Prasadi de Silva (they are Microsoft so they don’t really count), , Bruce, Sarah from DevTest and Simon and Emma from Avanade we were invited to do talks on different aspects of the software development process in the SDC from Project Management, Development, Testing to Setup and Deployment.

The videos from the day are all published now. The fifth one in the list is my presentation :) however I can’t seem to be able to play it as I continuously get an error.

Leaving Readify: Got a new job & new responsibilities

Personal, Readify No Comments

It’s public now that as of the 15th of May I’ve resigned from the position of Senior Consultant in Readify.

I’ve worked with some of the best minds in the industry from Darren, Mitch, PaulG and PaulS (who is still Temporarily Offline), Philip, Damian, Tatham, Francois (who’s now enjoying his trip around the world), Aymeric and lots, lots more.

I’ve worked with some great people from outside Readify like Tom Hollander, Rocky Heckman, Bruce McLeod, to mention only a few..

I think this was the best, coolest and most enjoyable job I’ve ever had, with involvement in various projects from fixing simple (sometimes crappy) VB.Net apps to technical lead of large projects, performance reviews and improvements, security reviews and guidance, threat modelling new or existing systems, architecture and design of new systems, architecture reviews, complete or partial refactoring and rewrites of applications, mentoring, guidance, training, talking, presenting or attending loads of conferences, whinging, crying (not really) and contesting or challenging technical decisions (most of the times offering alternatives), building awesome relationships with my teams and my customers (oh, well, at least that’s what I believe I did :))

Even more I also received an MVP award in Development Security.

I’ve loved my position and the people I’ve been working with.

But now it’s time to move on to a new challenge and a new role. I’ve accepted a new role as a (full-time) Solutions Architect and 2IC with Class Financial Systems. More or less I’m going back into financial systems where most of my background and experience was before I’ve joined Readify.

I’ll have a great new set of challenges from leading a new team to delivering a new project from zero to hero (or great success). I kind of started to forget what it means to be part of a project form end to end. I’ll also try to use this opportunity to learn, apply, present and (cross-fingers) be approved as a Microsoft Certified Architect: Solutions.

I truly hope I’ll keep in good contact with all Readify, Microsoft, friends and partners and I hope to see most of you at user groups, TechEd, CodeCamp, MVP Summit and other conferences.

WCF Dynamic Client Proxy – Implementing IDisposable

WCF, WCF Dynamic Proxy No Comments

As my good friend and Readify colleague Buddhike observed the generated WCF Dynamic Proxy was not implementing IDisposable. This is a bit scary as I was quite sure I had that implementation prepared done already so all I can image is that for some reason (no source control?) I’ve been working on an older code base.

So, here is a new implementation that is implementation that implements IDisposable. The only trick is that you have to cast the received proxy to IDisposable in order to use it in a using statement. As a difference from the WCF implementation, the dynamic proxy does not throw at all from the implementation of the IDisposable so it’s safe to use in a using statement:

IService1 service = WCFClientProxy<IService1>.GetReusableFaultUnwrappingInstance("Service1");
using (service as IDisposable)
{
    service.MyOperation1("a", 0);
}

Please download the new version of WCF Client Proxy 1.3.1.

WCF Dynamic (ClientBase) Proxy part three: Connection Pooling and Automatic Disposing

.Net, WCF, WCF Dynamic Proxy 1 Comment

A while ago I published a small and neat Dynamic Proxy that could be used to automatically create for you implementation of the (WCF) ClientBase<T> so you would not have to generate that from the service interface and hand-coded or even bother to maintain.

One of it’s great advantages was that you could ask for a “Reusable” proxy which was basically a wrapper around the proxy that you didn’t have to close/dispose in case of a fault.

As you might know WCF requires that you dispose of the proxy if there is any type of fault detected. Doing this is a pain in any type of code as you have to manage that connection life-time while actually all you care most of the times is that you talk to the service and not the life-time of your connection. The WCF Client Proxy was also doing this management for you allowing you so simply focus on your business and not on opening/closing your connections.

However there are moments in which you also want to specifically close your proxy for example using a using statement. Because the WCF Client Proxy was returning you the exact interface that you requested and if that interface was not implementing IDisposable you had to reside on a trick and cast the received proxy to IDisposable (as the proxy generates that behinds the scenes for you anyway) and use it like this:

IService1 service = WCFClientProxy<IService1>.GetReusableInstance("Service1");
using((IDisposable)service)
{
    service.MyOperation1();
}

This was again a bit ugly as you have to care about the connection and you can’t just use it as any other interface. You do have to be aware that your interface represents a WCF service that you want to dispose of.

One other potential scenario that several people hit is in websites that talk to external WCF services and you use the same service from within the same page several times (for example from different controls). In practice in this scenario you will open/close the same proxy multiple times during the lifetime of the page.

Connection Pooling

In order to simplify the management of WCF connections during the lifetime of a webpage or even a WCF Operation Call and reduce the overhead of caring to dispose of proxies I’ve now added a ProxyConnectionPool class to the dynamic proxy that can be enabled to automatically pickup all the created WCF connections and pool them (as in return the same one back to you if you use it from the same thread and it’s safe to reuse).

To enable the connection pooling all you have to do is:

ProxyConnectionPool.EnableConnectionPool = true;

Now every time you do a call do GetReusableInstance or other methods on the WCFClientProxy the connection you receive might be a pooled one (same tread only pooling) or a new one just registered with the pool. This should improve your performance as creating WCF Proxies is an expensive process that you want to avoid as much as possible.

Disposing the pool

Once you finish your work on that thread you can simply ask the connection pool to dispose all the WCF connections from the pool using:

ProxyConnectionPool.Current.Dispose();

Automatic disposing

If you use WCF inside a website to call other WCF services you should then simply include the following module in your web.config so you get automatic disposing of all WCF connections created on each page request (with peace of mind included).

<system.web>
    <httpModules>
        <add name="WcfConnectionPool" type="ACorns.WCF.DynamicClientProxy.Pool.WcfConnectionPoolHandler,ACorns.WCF.DynamicClientProxy"/>
    </httpModules>
</system.web>

This module will automatically enable the connection pool for you and make sure all the WCF proxies created are nicely disposed at the end of each page request. This truly allows you to focus on writing your business code and not bothering about connection management of your WCF services. Your code will now become:

IService1 service = WCFClientProxy<IService1>.GetReusableInstance("Service1");
service.MyOperation1();

Let someone else deal with the fact that you use WCF :)

Licence

I was requested several times about the licence this code is. Here is my official statement:

This package is provided "AS IS," without express or implied warranty of any kind, and may be used and modified.

This package may be used in corporate applications without any pretence.

However I would appreciate if you would drop me a line to let me know you are using it to corneliu at acorns.com.au or even donate some money by PayPal to the same address :)

Download

Here is the latest version of the WCF Client Proxy 1.3.0

Writing a super fast deep-property reader/writer using delegates

.Net, Visual Studio 1 Comment

For a while now I’ve been writing to write a non-reflection based property reader that allows me to read properties of an object in a deep hierarchy.

So lets say you have the following simple class hierarchy:

public class FirstLevel
{
    public string Leaf { get; set; }
}
public class SecondLevel
{
    public FirstLevel First { get; set; }
}
public class Root
{
    public SecondLevel Prop { get; set; }
}

Then you want to read the Leaf from the FirstLevel by looking at the Root level and all you have is the path to the property: “SecondLevel.FirstLevel.Leaf”.

Using reflection is a simple process of recursively going through the object, finding the proper property doing a GetValue on it and then repeating the process until you find your property. This is ok but it’s very slow. Very very slow.

Your other two alternatives if you don’t want the bear the hit of reflection is to code emit a method that would resemble something like this:

public static string GetLeaf(Root root)
{
    SecondLevel secondLevel = root.Prop;
    if ( secondLevel != null )
    {
        FirstLevel firstLevel = secondLevel.First;
        if ( firstLevel != null )
        {
            return firstLevel.Leaf;
        }
    }
    return null;
}

Or use dynamically created delegates to map to the get_Property and set_Property methods generated for each property.

 

using System;
using System.Reflection;

namespace ACorns.Utils
{
    public interface IPropertyAccessor
    {
        object GetValue(object target);
        void SetValue(object target, object value);
    }

    public interface IPropertyAccessor<TargetObject, FinalProperty>
    {
        FinalProperty GetValue(TargetObject target);
        void SetValue(TargetObject target, FinalProperty value);
    }

    /// <summary>
    /// Super-dooper, super-fact deep property extractor.
    /// You can use it to get/set properties deep in an object hierarchy without using reflection.
    /// Please cache the returned IPropertyAccessor if you want to reuse it.
    /// Good performance is only achived with cached IPropertyAccessor(s)!
    ///
    /// Usage: IPropertyAccessor accessor = PropertyExtractor.GetAccessor(typeof(Root), "Prop.First.Leaf", true);
    /// accessor.GetValue(target);
    /// </summary>
    public static class PropertyExtractor
    {
        public static IPropertyAccessor<TargetObject, FinalProperty>
            GetAccessor<TargetObject, FinalProperty>(Type targetType, string propertyNames)
        {
            return GetAccessor<TargetObject, FinalProperty>(targetType, propertyNames, true);
        }
        public static IPropertyAccessor<TargetObject, FinalProperty>
            GetAccessor<TargetObject, FinalProperty>(Type targetType, string propertyNames, bool throwOnNull)
        {
            IPropertyAccessor internalPropertyAccessor = GetAccessor(targetType, propertyNames, throwOnNull);

            Type accessorType = typeof(TypedPropertyAccessor<,>).MakeGenericType(typeof(TargetObject), typeof(FinalProperty));
            IPropertyAccessor<TargetObject, FinalProperty> propertyAccessor =
                (IPropertyAccessor<TargetObject, FinalProperty>)Activator.CreateInstance(accessorType, internalPropertyAccessor);

            return propertyAccessor;
        }
        public static IPropertyAccessor GetAccessor(Type targetType, string propertyNames, bool throwOnNull)
        {
            string[] deepPropertyNames = propertyNames.Split(‘.’);
            IPropertyAccessor internalPropertyAccessor = GetAccessor(targetType, deepPropertyNames, 0, throwOnNull);
            return internalPropertyAccessor;
        }

        private static IPropertyAccessor GetAccessor(Type targetType, string[] deepPropertyNames, int level, bool throwOnNull)
        {
            string property = deepPropertyNames[level];

            PropertyInfo propertyInfo = targetType.GetProperty(property);

            // Create a delegate to a get_ method. The delegate looks like
            // Func<TargetType, PropertyType> func to a property like class TargetType { public PropertyType { get; } }
            Type getterDelegateType = typeof(Func<,>).MakeGenericType(targetType, propertyInfo.PropertyType);
            Delegate getDelegate = Delegate.CreateDelegate(getterDelegateType, propertyInfo.GetGetMethod());

            IPropertyAccessor accessor;

            level++;
            if (level < deepPropertyNames.Length)
            {
                // Recursive detect the down the property
                IPropertyAccessor nextLevelAccessor = GetAccessor(propertyInfo.PropertyType, deepPropertyNames, level, throwOnNull);

                Type accessorType = typeof(PropertyAccessor<,>).MakeGenericType(targetType, propertyInfo.PropertyType);
                accessor = (IPropertyAccessor)Activator.CreateInstance(accessorType, getDelegate, nextLevelAccessor, throwOnNull);
            }
            else
            {
                Type setterDelegateType = typeof(Action<,>).MakeGenericType(targetType, propertyInfo.PropertyType);
                Delegate setDelegate = Delegate.CreateDelegate(setterDelegateType, propertyInfo.GetSetMethod());

                Type accessorType = typeof(LeafPropertyAccessor<,>).MakeGenericType(targetType, propertyInfo.PropertyType);
                accessor = (IPropertyAccessor)Activator.CreateInstance(accessorType, getDelegate, setDelegate);
            }

            return accessor;
        }

        #region TypedPropertyAccessor
        internal sealed class TypedPropertyAccessor<T, U> : IPropertyAccessor<T, U>
        {
            private readonly IPropertyAccessor _next;

            public TypedPropertyAccessor(IPropertyAccessor next)
            {
                _next = next;
            }

            public U GetValue(T target)
            {
                return (U) _next.GetValue(target);
            }

            public void SetValue(T target, U value)
            {
                _next.SetValue(target, value);
            }
        }
        #endregion

        #region Recursive Property Accessors
        internal sealed class PropertyAccessor<T, U> : IPropertyAccessor
        {
            private readonly Func<T,U> _readDelegate;
            private readonly IPropertyAccessor _next;
            private readonly bool _throwOnNull;

            public PropertyAccessor(Func<T, U> readDelegate, IPropertyAccessor next, bool throwOnNull)
            {
                _readDelegate = readDelegate;
                _throwOnNull = throwOnNull;
                _next = next;
            }
            public object GetValue(object target)
            {
                object result = _readDelegate((T)target);
                if (result == null)
                {
                    if (_throwOnNull)
                        throw new NullReferenceException("Property ‘" + _readDelegate.Method.Name + "’ on ‘" +
                            typeof(T).Name + "’ returned null.");
                    else
                        return default(U);
                }
                return _next.GetValue(result);
            }
            public void SetValue(object target, object value)
            {
                object result = _readDelegate((T)target);
                if (result == null)
                {
                    if (_throwOnNull)
                        throw new NullReferenceException("Property ‘" + _readDelegate.Method.Name + "’ on ‘" +
                            typeof(T).Name + "’ returned null.");
                    else
                        return;
                }
                _next.SetValue((U)result, value);
            }
        }
        internal sealed class LeafPropertyAccessor<T, U> : IPropertyAccessor
        {
            private readonly Func<T, U> _readDelegate;
            private readonly Action<T, U> _setDelegate;

            public LeafPropertyAccessor(Func<T, U> readDelegate, Action<T, U> setDelegate)
            {
                _readDelegate = readDelegate;
                _setDelegate = setDelegate;
            }
            public object GetValue(object target)
            {
                object result = _readDelegate((T)target);
                return result;
            }
            public void SetValue(object target, object value)
            {
                _setDelegate((T)target, (U)value);
            }
        }
        #endregion
    }
}

To use it you would request an IPropertyExtractor and then ask it to do a GetValue for you:

[TestMethod]

public void ExtractPropertyFromLeafFixture()

{

    Root r = new Root();

    r.Prop = new SecondLevel();

    r.Prop.First = new FirstLevel();

    r.Prop.First.Leaf = "original value";

    IPropertyAccessor accessor = PropertyExtractor.GetAccessor(typeof(Root), "Prop.First.Leaf", false);

    Assert.IsNotNull(accessor);

    object value = accessor.GetValue(r);

    Assert.AreEqual("original value", value.ToString());

    accessor.SetValue(r, "new value");

   
    value = accessor.GetValue(r);

    Assert.AreEqual("new value", value.ToString());

}

The beauty of this approach is that once the IPropertyAccessor is created (using Reflection) in the beginning,  the Get/Set on it is done via a set of direct delegate calls to the property and calls via the interface to the next level.

The callstack is thus very small and efficient:

image

Make sure you cache this accessor if you need it again at a later time as creating it is expensive.

The performance should be as good as you can get without using code emitting.

CodeCampOz 2009 is on: 04th of April – 05th of April

Readify No Comments

CodeCampOz is again on this year in the good old same Wagga-Wagga.

Mitch just announced the dates for this year’s CodeCampOz: 04th of April to 05th of April.

Attendance is free and we are open for registrations.

I’ll see you all there.

Windows 7 Beta Now Available

Readify No Comments

It’s official: Just minutes ago Steve Balmer declared that Windows 7 Beta is available now for download. For now it will be available to MSDN subscribers only.

Head now to MSDN and get your own copy.

Feedback can be provided on the Microsoft TechNet Forums in the newly created Windows 7 Beta forums.

The installation package for Windows 7 Beta x86 is just 2.4Gb. I’ve just started my download …

How to get a discount on your next Microsoft Exam?

Personal, Readify No Comments

The best discount for your next exam can be obtained via Andrew Coates who has 15 vouchers for free MCP exams.

If you’ve missed his offer I then have another offer for you: 10% off your next Microsoft exam and a free re-take (if God forbidden you fail the first attempt).

To get your 10% discount head over to http://www.learnandcertify.com/, click on “Get My Exam Offer Voucher code today” and enter the MVP Certification Promotion Code: AUD68E69 to receive the voucher code for your next exam. (Offer valid for Australia only.)

Please also drop me an email once you do the exam so I can congratulate you.

(all the other Terms and Conditions and legal small print will apply)

I’m now a Microsoft MVP: Developer Security

Personal, Readify 2 Comments

Happy New Year everyone. I hope the Christmas & New Year break was good for you and Santa brought you loads of presents.

Santa was a bit late for me but it arrived on the 2nd of January with an MVP Award.

So I’m officially a “Developer Security MVP” (in the Developer Tools category).

My thanks go to Rob Farley from LobsterPot for nominating me, the great Readify Team for their continuous support and to Adam Cogan for challenging and inspiring me.

« Previous Entries