Monday, May 24, 2010

WCF Security and RIA Security in general

This is a very lazy post. I just read two really good articles on RIA (Rich Internet Application) Security and Wcf Security.  

My Lead In Intro:
Lets face it when it comes to client-side code (by this I mean anything running in a client's browser, javascript, Silverlight, Flash etc) it running in an insecure zone and you cannot prevent it from being disassembled, examined, and maliciously manipulated.  This boils down to: Its a waste of time trying to write clever security code in these kinds of apps.  Time is better invested in securing your Wcf Services.


PS: As a side bar, I spoke to a Mt Eden developer in January that didn't believe me when I was explaining the simplicity of implementing secure Wcf Services was not possible without considerable effort and code. You know who you are. This has been available since 3.5 service pack 1.

Cheers ;-)

Sunday, May 23, 2010

WPF Validation Strategies

Out of the box I can see three main validation strategies.
  1. Throw exceptions from within properties of the data bound object.
  2. Use the IDataErrorInfo interface on data bound objects.
  3. Use Custom validation rules - subclass of System.Windows.Controls.ValidationRule.
The validation processing happens in the above order, with the exception of custom validation rules which have a ValidationStep property which controls the stage at which they are applied. The reality is probably a combination of these will be the way to go. Ideally throwing exceptions in properties is not a great idea and sometimes a given data object does not implement the IDataErrorInfo interface and cannot be partialed.

My preferred combination is use IDataErrorInfo where you can, this pushes some validation back to the business object so it cannot be avoided.In some situations its better to encapsulate the validation rule into a ValidationRule subclass so it can be shared among other like types.

Here's a demo of the three validation methods:

Of course the red border and asterisk is customisable by altering the style/template.

The first test box is validated using IDataErrorInfo interface.  This is implemented by the source object the textbox is binding to.  

The Model name text box is validated using exceptions.  If an exception is thrown while trying to set the bound property the ExceptionValidationRule will show the red border.

The Unit Cost field is validated using a custom validation rule that derives from ValidationRule.

Here's what the Xaml looks like for the 3 text-boxes:

                <TextBox 
                    Grid.Column="1" 
                    Margin="10" 
                    Text="{Binding Path=ModelNumber, NotifyOnValidationError=True, ValidatesOnDataErrors=True}" />
...
<TextBox 
                    Grid.Column="1" 
                    Grid.Row="1" 
                    Margin="10" 
                    Text="{Binding Path=ModelName, NotifyOnValidationError=True, ValidatesOnExceptions=True}" />
...
<TextBox 
                    Grid.Column="1" 
                    Grid.Row="2" 
                    Margin="10">
                    <TextBox.Text>
                        <Binding 
                            NotifyOnValidationError="true" 
                            Path="UnitCost">
                            <Binding.Converter>
                                <local:PriceConverter />
                            </Binding.Converter>
                            <Binding.ValidationRules>
                                <local:PositivePriceRule 
                                    IsNullAndEmptyAllowed="False" 
                                    Max="99999.99" 
                                    Min="1000.00" />
                                <ExceptionValidationRule />
                            </Binding.ValidationRules>
                        </Binding>
                    </TextBox.Text>
                </TextBox>

For Exception Validation and for IDataErrorInfo there is a convenient short-hand syntax that can be added to the binding mark-up.  But for custom validation rules you must use the long-hand syntax for binding so you can reference your custom validation rule (in this example the PositivePriceRule).

When using the IDataErrorInfo interface you must implement two members: a string property "Error" and a default indexer property that takes a string indexer and returns a string.  This idea is WPF will call this interface passing in the bound property name and if an instance of a string is returned then an error condition results; which then shows the red border style.  Here's the relevant code:

        /// <summary>
        /// Gets an error message indicating what is wrong with this object.
        /// Not used by WPF.
        /// </summary>
        /// <returns>
        /// An error message indicating what is wrong with this object. The default is an empty string ("").
        /// </returns>
        public string Error {
            get { return null; }
        }

        /// <summary>
        /// Gets the error message for the property with the given name.
        /// </summary>
        /// <returns>
        /// The error message for the property. The default is an empty string ("").
        /// </returns>
        /// <param name="columnName">The name of the property whose error message to get. </param>
        public string this[string columnName] {
            get { return this.Validate(columnName); }
        }

        private string Validate(string propertyName) {
            switch (propertyName) {
                case "ModelNumber":
                    bool invalid = this.ModelNumber.ToCharArray().Any(c => !char.IsLetterOrDigit(c));
                    return invalid ? "The Model Number can only contain letters or digits." : null;

                default:
                    // return valid by default
                    return null;
            }
        }

WPF does not use the Error property, it will only call the default indexer.

Throwing exceptions from within properties doesn't really need further explanation, just works as expected.

Implementing a custom validation rule is pretty straight forward also. The only requirement is to override the abstract function "Validate()". Here's the relevant code from my PositivePriceRule class:

    public class PositivePriceRule : ValidationRule {
        ...
        /// <summary>
        /// When overridden in a derived class, performs validation checks on a value.
        /// </summary>
        /// <param name="value">The value from the binding target to check.</param>
        /// <param name="cultureInfo">The culture to use in this rule.</param>
        /// <returns>
        /// A <see cref="T:System.Windows.Controls.ValidationResult"/> object.
        /// </returns>
        public override ValidationResult Validate(object value, CultureInfo cultureInfo) {
            decimal price = 0;
            var stringValue = value as string;

            if (string.IsNullOrEmpty(stringValue)) {
                return this.IsNullAndEmptyAllowed ? 
                    new ValidationResult(true, null) : 
                    new ValidationResult(false, "Null and/or Empty not allowed.");
            }

            try {
                if (stringValue.Length > 0) {
                    // Allow number styles with currency symbols like $.
                    price = decimal.Parse(stringValue, NumberStyles.Any);
                }
            } catch (Exception) {
                return new ValidationResult(false, "Illegal characters.");
            }

            if ((price < this.Min) || (price > this.Max)) {
                return new ValidationResult(false, "Not in the range " + this.Min + " to " + this.Max + ".");
            }

            return new ValidationResult(true, null);
        }
}

There's nothing to stop you from using a combination of all three techniques.  Most commonly using ValidatesOnExceptions and ValidatesOnDataErrors together as follows:

                <TextBox 
                    Grid.Column="1" 
                    Margin="10" 
                    Text="{Binding Path=ModelNumber, NotifyOnValidationError=True, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}" />

Or using the long-hand syntax combining all three techniques:

                <TextBox 
                    Grid.Column="1" 
                    Grid.Row="2" 
                    Margin="10">
                    <TextBox.Text>
                        <Binding 
                            NotifyOnValidationError="true" 
                            Path="UnitCost">
                            <Binding.Converter>
                                <local:PriceConverter />
                            </Binding.Converter>
                            <Binding.ValidationRules>
                                <local:PositivePriceRule 
                                    IsNullAndEmptyAllowed="False" 
                                    Max="99999.99" 
                                    Min="1000.00" />
                                <ExceptionValidationRule />
                                <DataErrorValidationRule />
                            </Binding.ValidationRules>
                        </Binding>
                    </TextBox.Text>
                </TextBox>

In summary, it seems to me to prefer using IDataErrorInfo and ValidatesOnDataErrors where ever possible pushing the validation logic into the bound business objects.  Where exceptions are possible use ValidatesOnExceptions.  And if there is a strong reason to, create a custom rule to keep the validation in the presentation layer of your application. Sometimes this makes sense when there are more rules you want to impose than those provided by the bound data object.

More Advanced Validation...
Here's a great article from MSDN magazine covering more advanced validation options.

This covers validation binding groups which is handy to control when validation occurs for a group of controls and bindings. (If a control's value is dependent on a valid value in another control).


Monday, May 10, 2010

Xml Serialization



10-May-2010
Here's a basic example of serialising (Yes that's right in this part of the world that's how its spelt), an object to Xml:
[Edit: BTW you will need to add a reference to System.Runtime.Serialization in addition to the standard C# console app references).


namespace XmlSerialisation {
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Xml.Serialization;
    using System.Xml;

    public class Program {
        public static void Main(string[] args) {
            var subject = new KeyValuePair<int, string>(21, "Full House Aces High");

            var builder = new StringBuilder();
            using (var writer = new StringWriter(builder)) {
                var serialiser = new XmlSerializer(typeof(KeyValuePair<int, string>));
                builder.AppendLine();
                builder.AppendLine("XmlSerializer:");
                serialiser.Serialize(writer, subject);
                builder.AppendLine();
            }

            using (var writer = new StringWriter(builder)) {
                using (var xmlWriter = new XmlTextWriter(writer)) {
                    var wcfSerialiser = new System.Runtime.Serialization.DataContractSerializer(typeof(KeyValuePair<int, string>));
                    builder.AppendLine();
                    builder.AppendLine("WCF Serialisation:");
                    wcfSerialiser.WriteObject(xmlWriter, subject);
                    builder.AppendLine();
                }
            }

            Console.WriteLine(builder.ToString());
        }
    }
}

Here's the output of the program:

XmlSerializer:
<?xml version="1.0" encoding="utf-16"?>
<KeyValuePairOfInt32String xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:xsd="http://www.w3.org/2001/XMLSchema" />

WCF Serialisation:
<KeyValuePairOfintstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xml
ns="http://schemas.datacontract.org/2004/07/System.Collections.Generic"><key>21<
/key><value>Full House Aces High</value></KeyValuePairOfintstring>


One other thing I was trying to prove with this code is the different behaviours of the two different serialisers. The standard XmlSerializer serialises based on public properties (and takes into account Xml attributes you may have decorated your members with, for example [System.Xml.Serialization.XmlElement("ReplacementMemberName")]).

The DataContractSerializer looks at fields for its serialisation process, and will ignore the System.Xml.Serialization attributes.

You also have a Json serialiser at your disposal too, see here for more info.

[Edit 28-June-2010]
Here's an example of Deserialisation:


    private static T SetUpSampleData<T>(string sampleDataFile) where T : class, new()
        {
            if (File.Exists(sampleDataFile))
            {
                // var serialiser = new System.Xml.Serialization.XmlSerializer(typeof(MainWindowController));
                var serialiser = new System.Runtime.Serialization.DataContractSerializer(typeof(MainWindowController));
                using (var stream = new FileStream(sampleDataFile, FileMode.Open, FileAccess.Read))
                {
                    using (var reader = XmlReader.Create(stream))
                    {
                        // var deserialisedObject = serialiser.Deserialize(reader);  // XmlSerialiser
                        var deserialisedObject = serialiser.ReadObject(reader);      // WCF DataContract Serialiser
                        return deserialisedObject as T;
                    }
                }
            }

            return null;
        }

Friday, May 7, 2010

Favourite Developer Tools Demo

7 May 2010


Today I demo'ed to the dev team a list of tools I have found very useful over the last few years. Here's a rundown in no particular order.

  • Code Metrics in Visual Studio
  • Xaml Formatter
  • Regionerate
  • StyleCop
  • Resharper
  • NCover
  • NUnit Gui
  • Ghost Docs
  • Reflector
  • NDepend
  • XamlPadX



Visual Studio Code Metrics Tool
Its only available in Premium and Ultimate. Its accessed from the Other Windows option in the view menu.



It gives some common / basic statistics about your code. Cyclomatic Complexity is a measure of the number of pathways through your code, this increases the number of nested conditional statements you have. It is generally accepted that this number should be less than 20 for a member. Class coupling: I read on on a wiki somewhere this should be absolutely no more than 30. This seems high to me. Suffice to say the less the easier it is to maintain and test. Inheritance should be less than 6. Check out Wikipedia  and other top google results for tolerance recommendations.


Use this analysis process to improve the usability and maintainability of your code. The simplier one method is, the easiser it is to test and consume.


Xaml Formatter
It does exactly what it says on the tin.






It puts attributes on their own line unless there is only one, and alphabetises the attributes. It will also point out "possibly" unused x:Name and x:Keys for review.
This is a very basic tool (that needs work, and I believe Craig volunteed ;-) ), so its free, see my Essential Tools page for downloading.


Regionerate
It sorts and arranges members within a class. This is a fantastic tool and definitely in my top 3 favourites. See the Regionerate page for more info. Its a free tool, but Rauchy would really like to eat so donate him a pizza.

From ugly to ...



Ah, Pretty.


See my Essential Tools page for downloading a customised style sheet that is compatible with StyleCop.


Keeping your code in a consistent predictable order will make it more approachable, easier for others to learn it, and maintain it. Not to mention those of us with bad memories and we forget what it does after 2 weeks, you know who you are... ;-)


StyleCop
This is a great tool to advise and enforce a consistent style across all your code. See here for more info the Stylecop site and the StyleCop for Resharper  site. It used to be known as FxCop and was originally designed and written by one of the senior Microsoft CLR Architects. Its totally free.
This is a must have for use along side the built in Code Analysis built into Visual Studio premium. See my Essential tools summary page for a link to a stylecop config file almost fully compliant with the  Microsoft Framework Design Guidelines (or even better still buy the book).


This is a snippet of code where you can see the warnings generated by Stylecop in the Errors/Warnings task list, and also the integration into Resharper giving the green underline indicating a Stylecop warning present on that line.







Resharper
Resharper is an enormous cache of goodness that will have you screaming like a 3year old when its taken away. For more information see the JetBrains site. This is another that is easily in my top 3 favourite tools. I've been using it for more than 3 years now and I'm addicted. Believe the hype on the Jetbrains site, you easily recoup the cost of the licence inside 4 weeks in productivity savings. Here's a list of my favourite features.



Renaming: The Refactor-Rename feature will rename comments (optionally) automatically rename references in xml member documentation comments and related members. Ie: if you rename a property it will ask if you would like to rename its backing field also.



Type Navigation with Ctrl+T - easy simple and obvious.



Suggested fixes, actioned by pressing Alt+Enter+Enter. All default actions can be performed against the entire solution with the Code Clean Up Tool.



Excellent Unit Testing interface.



Superior Intelli-Sense.



Find Usages of a member or type across an entire solution.


This is but a small subset of the features in this very easy to use tool.


NCover
I have used this tool previously for better code coverage feedback and stats. Read their  web site for more detail. My exposure to it is limited; I've used it mostly through a add-in to Visual Studio called  Test Driven.Net. The amount of statistics recorded is superior to what you get out of the box with Visual Studio, and includes a graph showing your test passes over time and code coverage stats over time. Its not a free tool, but as stated provides far superior stats than Studio does.





NUnit Gui

A nice simple interface for running tests. It pulls in source code if it finds it on your local drive and Pdb's are present. Can be scripted into the build process. Also an easier to use tool for testers to ensure all tests pass before they start their own tests. See their web site for more info.It has the ability to run tests in parallel (unlike Resharper's unit test runner). Tests can also be given time out values as attributes, Resharper's test runner also ignores these. NUnit is an open source program and has been easily the most popular unit testing framework for .Net.


Ghost Docs
This is a fantastically simple and surprisingly clever tool. Its a free tool and you can download it here. It will add xml documentation comments to members and type on key combination (Ctrl+Shift+D by default). Normally it will make a surprisingly good guess at a summary description for your method. It will even pull down comments from a base class or interface. At the very least it will insert a template allowing quick entry of documentation.

This shows the default the xml documentation for the ToString override. It has pulled this comment from the System.Dll assembly.


Reflector

This is the other tool easily in my top 3 favourite tools. Its invaluable for easily finding types and members, your search can be an exact match or a partial. It also shows full xml comments for every type and member.
Probably the best feature is its ability to disassemble an assembly back into C# code. This is a great learning and debugging tool. I believe the pro edition is able to allow you to debug into a third party assembly although I have never tried. There is a free edition and a Pro edition that you can licence for a small fee considering the power, here's the web site.





NDepend
This is a very extensive tool, there's far more to say about it than just 2 or 3 sentences. Here's their website.

Suffice to say that it is an analysis tool for looking at types and assemblies at a high level. I have found it to be useful for two purposes: discovering and analysing an assembly or solution written by someone else upon which I am expected to add to. Secondly, its very useful to add polish to your own framework API's. It makes it easy to find members that should not be public, unused, or are too complex. I quite often use the"egg" diagram in Cyclomatic complexity mode (as a unit of measure instead of the default Lines of Code) this immediately shows me large sections that I need to refactor into more maintainable code.




The above diagram shows the "Egg" diagram in lines of code mode. You can see an excessively large method in the top left of the diagram. Sometimes lines of code is not the best measure of size of a method. Lots of lines of code might (emphasis on might) be acceptable but certainly not too much complexity. Thats where changing the mode to Cyclomatic complexity is very useful.


When refining and polishing a reusable DLL or framework I find take a good close look at the extensive report ndepend produces. In particular the grid that highlights any statistic that is in the top 15% for that stat for the DLL. These top 15% stats are highlighted in pink. Just because they are highlighted doesn't mean they are a problem, just need to be considered. This is the only complaint I have against this otherwise awesome tool. There is no way to annotate these and possibly ignore them for the next time the analysis is done.



Finally, the last feature I want to show is the CQL language built into ndepend. It gives you SQL like query syntax across your libraries looking for certain stats. For example:

You can see the CQL statement in the top left pane and the results in the below pane and also visually highlighting the selected methods. Custom queries can be built into the analyse run process.
This tool is not free, see their website for more info.


XamlPadX
This tool has limited use in my opinion but I have used it religiously for playing around with snippets of xaml and for extracting the xaml style code from the default Microsoft controls for control customisation. I quickly find that I would rather take my snippet of xaml I am working on and copy it into a Visual Studio test project instead. But Studio does not have support for extracting control styles like XamlpadX does. I did find some source code on the net to perform just this function however, but in this case I'm I'd rather not reinvent a good working tool.







This is a free tool, here's the link.


And thats it. Go forth and multiply.