Today in work I had a requirement where I wanted to output binary content to the response output stream.  I also want to stay with the MVC Controller for serving this content and so wanted a result I could add my data to and return it.  To my knowledge there is a ContentResult, but with this the Content property is of type string, and is not what I wanted.  I this particular case, I am physically GZipping content and then writing out to the Response.OutputStream

Previous to this I have been seeing and using examples where you assign a GZipOutputStream as a Filter on the Response dynamically.  For some strange reason on the Live environment the header and filter where being ignored on the response yet on the test, builds and sandbox everything worked as expected and the dynamic resources got GZipped.

So I had to go another way and what I came up with was to physically GZip the output content and send it to the response with the accompanying header.  I cannot see why this would not work on the server as the content is physically being served already GZipped opposed to applying a filter which can obviously be removed somewhere in the pipeline.  Any way after some reading I found some evidence that a library, http://www.icsharpcode.net/OpenSource/SharpZipLib/ , yields far better results than the out of the box one from .NET, so for this example I have a dependency on this assembly.  Apart from that I have added a couple of properties which allow for the conditional Compression and also a list of headers to give a little more flexibility.  So here is the code:

    /// <summary>
    /// A content result which can accept binart data and will write to the output
    /// stream.  If GZip is set to true the content will be GZipped and the relevant
    /// header added to the response HTTP Headers
    /// </summary>
    public class BinaryContentResult : ActionResult
    {
        public byte[] Data { get; set; }
        public NameValueCollection Headers { get; set; }
        public bool Gzip { get; set; }


        public override void ExecuteResult(ControllerContext context)
        {
            foreach (string s in Headers.Keys)
            {
                context.HttpContext.Response.AddHeader(s, Headers[s]);
            }

            if (Gzip)
            {
                using (var os = new GZipOutputStream(context.HttpContext.Response.OutputStream))
                {
                    os.Write(Data, 0, Data.Length);
                }
                context.HttpContext.Response.AddHeader("Content-Encoding", "gzip");
                context.HttpContext.Response.AddHeader("X-Compressed-By", "Custom-Compressor");
            }
            else
            {
                context.HttpContext.Response.BinaryWrite(Data);
            }

            context.HttpContext.Response.End();
        }
    }


.NET | ASP.NET MVC | C#
Tuesday, February 16, 2010 7:29:48 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer

If you have not read about it yet or seen it or used it, please visit Davy Brion’s Blog here and download the Agatha project.  Another link I need to mention is the following, Integrating Strcuture Map With WCF.  Basically what I have attempted to do is create an Agatha.Common.InversionOfControl.IContainer implementation for Agatha which uses StrcutureMap as the IOC Container.  I am also not hosting the WCF Service inside a Web Application but in an actual WCF Service Application which I wanted to use the Service Host Factory as demoed in the above link.

The implementation for the Container was relatively straight forward in most parts and allowed me to use some newer features of StructureMap which I do not currently use yet in my job; well I say newer, newer to me!!.  I have read on Davy Brion’s blog that he is intending to write this Agatha IOC Container for Structure Map, and I look forward to it, but in the mean time I thought I would have a crack at it myself.

While writing the Container for StructureMap I had to make a small change/addition to the Agatha source code, on the interface for the IContainer to make sure that a method had a generic type constraint.  The method:

void Register<TComponent,TImplementation>()

A compile time error was raised which stated that there was no information to allow for boxing/unboxing.  To solve this I added the following constraint:

void Register<TComponent,TImplementation>() where TImplementation : TComponent

Once added the compile time error went, but I was still left with another issue which at this stage of writing this post I am of the opinion that I need to also make a small addition to StructureMap.  I look forward to it, if it is not already available but it would be good to find out that it is already accounted for.  The operation which I am talking about is the removal of an instance from the IOC Container.  The interface for the Agatha IOC IContainer has a method called Release which takes an object instance as a parameter and with the Castle WInsor you can release an instance.

    public interface IContainer
    {
        void Register<TComponent, TImplementation>(Lifestyle lifestyle) where TImplementation : TComponent;
        void Register(Type componentType, Type implementationType, Lifestyle lifeStyle);
        void RegisterInstance<TComponent>(TComponent instance);
        void RegisterInstance(Type componentType, object instance);
        void Release(object component);
        TComponent Resolve<TComponent>();
        object Resolve(Type componentType);
    }

After doing a bit more searching I cannot find a function which fits this criteria exactly.  There is the EjectAllInstancesOf<T> method, but the one I ended up using is the following:

        public void Release(object component)
        {
            //throw new NotImplementedException();
            _strcutureMapContainer.Model.EjectAndRemove(component.GetType());
        }
 

This is a method on the IContainer interface and I am using the component to get its type and releasing all instances of it within the IOC Container.  I am not 100% sure this is what other implementation of IOC are doing with this particular type of function.  Never the less, this does work fine and I am now up and running with the Agatha library inside a WCF Service Application Project using a ServiceHostFactory and configuring a StructureMap IOC Container for use with Agatha.

I have not made the most consistent approach to the StructureMap usage as I have mixed preferred and deprecated methods.  This is because I am not 100% sure how to map the new style of Lifeycle management between Castle Windsor and StructureMap. I look forward to seeing the actual implementation which goes into the Agatha project so I can see where I could have improved my attempt.  Here is the finished code of my attempt.

Hope this is of some help,

Cheers,

Andrew

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using sm = StructureMap;
using Agatha.Common.InversionOfControl;

namespace Agatha.StructureMap
{
    public class Container : Agatha.Common.InversionOfControl.IContainer
    {
        private readonly sm.IContainer _strcutureMapContainer;

        private Dictionary<Lifestyle, sm.InstanceScope> _lifeStyleMappings = new Dictionary<Lifestyle, sm.InstanceScope>
        {
            {Lifestyle.Singleton, sm.InstanceScope.Singleton},
            {Lifestyle.Transient, sm.InstanceScope.Transient}
        };

        private Dictionary<Lifestyle, sm.Pipeline.ILifecycle> _lifeStyleLifeCycleMappings = new Dictionary<Lifestyle, sm.Pipeline.ILifecycle>
        {
             {Lifestyle.Singleton, new sm.Pipeline.SingletonLifecycle()},
            {Lifestyle.Transient, new sm.Pipeline.UniquePerRequestLifecycle()}
        };

        public Container() : this(new sm.Container()) { }

        public Container(sm.IContainer structureMapContainer)
        {
            _strcutureMapContainer = structureMapContainer;
        }

        public void Register(Type componentType, Type implementationType, Lifestyle lifeStyle)
        {
            _strcutureMapContainer.Configure(x => x.For(componentType).LifecycleIs(_lifeStyleMappings[lifeStyle]).Use(implementationType));
        }

        public void Register<TComponent, TImplementation>(Lifestyle lifestyle) where TImplementation:TComponent
        {
            _strcutureMapContainer.Configure(x => x.ForRequestedType<TComponent>()
                .CacheBy(_lifeStyleMappings[lifestyle])
                .TheDefaultIsConcreteType<TImplementation>());
        }

        public void RegisterInstance(Type componentType, object instance)
        {
            _strcutureMapContainer.Configure(x => x.ForRequestedType(componentType).Use(instance));
        }

        public void RegisterInstance<TComponent>(TComponent instance)
        {
            _strcutureMapContainer.Configure(x => x.For<TComponent>().Use(instance));
        }

        public TComponent Resolve<TComponent>()
        {
            return _strcutureMapContainer.GetInstance<TComponent>();
        }

        public object Resolve(Type componentType)
        {
            return _strcutureMapContainer.GetInstance(componentType);
        }

        public void Release(object component)
        {
            //throw new NotImplementedException();
            _strcutureMapContainer.Model.EjectAndRemove(component.GetType());
        }
        
    }
}


.NET | Architecture | C# | WCF
Wednesday, February 10, 2010 10:16:44 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer

Files

Please download the example solution for this post from the following url.

http://lab.andrewrea.co.uk/ResourcesExampleMvc.rar

Summary

Ok, I have been writing this one as I went, whilst thinking and deving so my opinion on this has changed from when I started writing this to what I ended up with and I have to say I am quite chuffed with the outcome as it yields some other possibilities which I want to now blog about, but to cut a long story/blog post short I have made a Http Handler which accepts some parameters so it can locate a resource file, enumerate through its properties and output them as JavaScript variables to the Response Output Stream. This allows me to expose resources the application is using to client script so I am not duplicating any of them and making maintenance and additions much easier.

I have also wrapped in a bit of token based security, although I do kind of ensure that what is attempted to be enumerated is a resource file by passing the type into a ResourceManager I have added the token based security regardless.  Another good option would be to encrypt the url like the common .axd resource handler does, but either way I have used a token based approach using HMAC and SHA1.

Example usage:

<%= Html.ClientResourceLink<ResourcesExampleMvc.Core.Resources.Global>("jsloc.axd","fr") %>

Example output:

<script type="text/javascript" src="/jsloc.axd?typeName=ResourcesExampleMvc.Core.Resources.Web.Controllers.Home.Home&culture=fr&token=2E935FA9EF23865A9A57B437EC9A7CCE62A7712B&timestamp=1260744495"></script> 

The handler at work:

var cache_date = "13 December 2009 23:57";
var GlobalString1 = "French Global String 1";

image

Finally I have made a HtmlHelper which will generate the relevant link / links I need.  So the blog that I started writing, dev’d and changed my mind…

here goes…

I have been looking at different examples on the web relating to client side localisation.  The two main points I see are:

  1. Add secondary resources inside JavaScript files (This leads to duplication of resources)
  2. Make a call to the Resource Manager inside delimiters inside the mark-up. (This is fine as long as you are not using separate JavaScript Files)

I might be wrong, but from what I can see on the Resource Manager, there is only a set way of getting access to a resource, and that is by its name, so if I want to get several related items, I need to know the keys of each.  As I am writing this I am now starting to think if what I originally wanted to do is as efficient as I first thought.

Basically I thought that inside each Resource file that is defined, each key could be prefixed with some kind of grouping information, e.g. HomeController , so I could have the following keys:

  • HomeController_WelcomeText
  • HomeController_Button1
  • HomeController_Button2

With this I then thought of making a way to query the resources, so I could apply a prefix and then get in return all matched keys.  I would do this by reflection and looping over each property, storing its name and value.

So to summarise I was stuck in the way of thinking one resource file and differentiating based on the string key.  DOH!, thinking about it now, I think the best and most clean solution is to use a separate resource file per each localisable entity i.e. a Form, or Controller etc…  If you think about it also, this will make things much more organised when you get to a point where you have thousands of resources.  Having them logically separated in line with the entity which will be localised makes good sense.  Not only that it also make the task I was thinking about much easier.

The Idea

If you think about ASP.NET MVC for example, and the following. You will always have resources which are common or global and then you will have resources which are specific to a certain part of the project, e.g. Home Controller.

I want to be able to output any localisation that I need so that I can consume with JavaScript without any unnecessary AJAX calls.  More so I only want to output the required keys from the global resources and the resources specific to the area which it is currently being executed, i.e. Home Controller.

The format which I am thinking for the output of the client side localisation is simply a included JavaScript file with the contents simply declared variables which match the name of those inside the resource files i.e.

var Global_Resource_Key_1 = "Hello World";
var Global_Resource_Key_2 = "Hello Galaxy";
var Local_Resource_Key_1 = "Local Number 1";
var Local_Resource_Key_2 = "Local Number 2";

Going back to what I said above, these will be output by a method using reflection to iterate through each of its properties to then generate the required output.  Once the iteration has complete it would be wise to store the resulting collection in Cache or Application object.  I am thinking that the generation of the script will be using a HttpHandler, allowing for the variables to be dynamic inside the mark-up and script  declaration.

Thinking about it more, this is exactly why we are given the special .NET folders of :

  • App_GlobalResources
  • App_LocalResources

These are great, but, I need to have the resource files inside another assembly so that they can be referenced both from the web and also internally from the calling assembly.  So inside a test project I have done the following to setup:

image

  • Create a MVC Application
    • Delete the Account View and Controllers
    • Move the Controllers, Global.asax.cs and Models to the Class Library project
  • Create a separate Class Library Project
    • Create a folder for resources
    • Create a Global Resources and also a Resource file per Controller with the relevant folder structure
    • Created a Configuration folder and class to handle the secret key for hmac’ing and cache timeout
    • Created an Extension Method folder and HtmlHelper class which will be a shortcut for the deveoper to use which will generate the link
    • Created a HttpHandlers folder and the actual handler which I will use to generate and cache the relevant properties

Also, I have omitted any DI/IOC for the purposes of this example. I will go through each of the Class Library project sections separately.

Create a folder for resources & Create a Global Resources and also a Resource file per Controller with the relevant folder structure

Having a separate folder in the resource means I can consume these from the web application but also from any models which are inside the assembly or business data for example where I may state the resource for validation attributes like those used in the DataAnnotations or the MVAB (Microsoft Validation Application Block).

I have but the global resource file directly inside this folder and then created sub folders to reflect different parts of the application which the one being in this instance, Web and then even further by controller.  I think grouping the resources by Controller for the web is a logical step, and along with a global resource file, you are pretty much covered.

image

When you build the solution, .NET will logically group your assemblies by culture, so have many resource files still means they will compile down into one assembly, which is great.

Created a Configuration folder and class to handle the secret key for hmac’ing and cache timeout

I could quite as easily have used the AppSettings but I thought that it would be good to give this attempt its own configuration section, which I could extend and keep encapsulated in the future.  The two things which I am using this section for at the moment is to store the key I will use to generate the HMAC hashes and also the sliding timeout for the cache of the resources.  The secret key can be anything you want, but I needed it in a centralised place so i can ensure the same one is used to generate and also compare.  There is not much to the Configuration Section accept a couple of required attributes and the syntax for retrieving the value declared in the config file.

<clientResourceConfiguration 
	resourceSlidingTimeout="20" 
	resourceHmacKey="470F0BE4675941baBEFBC1134CC1FEAF28C47C15D71543b8A9F57360CFFCD33B"/>

The secret key / resourceHmacKey here is simply two GUIDs stripped of the curlies and dashes and concatenated together.  To reference this configuration inside the code, I have placed a static property on the MvcApplication class inside the Global.asax.cs file.  Seemed like a logical place to put it, and of course made it a singleton.

    public class MvcApplication : System.Web.HttpApplication
    {
        private static ClientResourceConfiguration _clientResourceConfiguration = null;

        public static ClientResourceConfiguration ClientResourceConfiguration
        {
            get
            {
                if (_clientResourceConfiguration == null)
                {
                    _clientResourceConfiguration = (ClientResourceConfiguration)ConfigurationManager.GetSection("clientResourceConfiguration");
                }
                return _clientResourceConfiguration;
            }
        }

...

Created an Extension Method folder and HtmlHelper class which will be a shortcut for the developer to use which will generate the link

This is simply to make it easier for the developer to create the link.  You can simply add the type you want to parse, the name of the handler which is mapped in the config file and the culture.  In this implementation I have designed it to expect the two letter culture name and then go on to resolve the specific culture.  I know it would have been easier to just specify the specific culture but I dev’d this with a work related problem I had and wanted to simulate the environment in which I have to work with.

I have created an overloaded method so that if I need to I can force clear the cache for a specific handler.  As I will show you further down I also output the date it was cached, again simply for diagnostic purposes.

The token here is simply so i can be sure that the resource file which is being requested has been authorized by the server, as it is the server which is the only entity that has the secret key and can create such links.  I have included a timestamp which makes the HMAC hash different each time.  The validation of this token will only occur if the requested resource is not in the cache, as I make the assumption that is if it is in the cache, then it has to have been generated for a valid reason by the server.

Oh and there is a small method in there I found on Brad Abrams site which simply gives me back the number of seconds since 1970, which acts as a timestamp.

    public static class HtmlHelpers
    {
        public static string ClientResourceLink<T>(this HtmlHelper helper, string handler, string twoLetterCultureName)
        {
            return ClientResourceLink<T>(helper, handler, twoLetterCultureName, true);
        }

        public static string ClientResourceLink<T>(this HtmlHelper helper, string handler, string twoLetterCultureName, bool cache)
        {
            var typeName = typeof(T).FullName;
            var timeStamp = GetTimeStamp().ToString();
            var valueToHash = String.Concat(typeName, twoLetterCultureName, timeStamp);
            var token = CryptoHelper.Hmac(valueToHash, MvcApplication.ClientResourceConfiguration.ResourceHmacKey, HashType.SHA1);
            var url = String.Format("~/{0}?typeName={1}&culture={2}&token={3}&timestamp={4}",
                handler,
                typeName,
                twoLetterCultureName,
                token,
                timeStamp);
            if (!cache)
            {
                url += "&cache=ncache";
            }
            return String.Format("<script type=\"text/javascript\" src=\"{0}\"></script>",
                new UrlHelper(helper.ViewContext.RequestContext).Content(url));
        }

        /// <summary>
        /// From Brad Abrams : http://blogs.msdn.com/brada/archive/2004/03/20/93332.aspx
        /// </summary>
        /// <returns></returns>
        private static int GetTimeStamp()
        {
            TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
            int timestamp = (int)t.TotalSeconds;
            return timestamp;
        }
    }

The CryptoHelper class is one which “I made earlier,” and which I blogged about here http://www.andrewrea.co.uk/2009/10/05/ACryptographyHelperClassForHashingAndForKHMACKeyedHashMessageAuthenticationCode.aspx.  It is simply a helper method wrapping around some types and methods inside the System.Security.Cryptography namespace.  You will see some example usages in the summary above.

Created a HttpHandlers folder and the actual handler which I will use to generate and cache the relevant properties

This is basically the crooks of the solution and it is the handler.  I have used the .axd extension simply because it is already recognised and is ignored my the MVC route handler. 

Below is the entry I have used to configure the Http Handler for GET only and an example path to map it to

<add verb="GET" path="/jsloc.axd" validate="false" type="ResourcesExampleMvc.Core.HttpHandlers.ClientSideResourceHttpHandler,ResourcesExampleMvc.Core" />

It is in this class where I handle:

  • The parameters passed in
  • The validation of the token
  • The cache of the resources for the client
  • The generation of the resources

I simply set the Response.ContentType to text/javascript and then write out the information through a StreamWriter.  The first variable I add is the CacheDate and then followed by the resources themselves, as they appear inside the resource file.  A point to mention here is if you have defined any of the keys in the resource files with spaces in they will be replaced with underscores.

Major Point : You must set the scope of your Resource File, which ever one you want the Handler to parse as Public, this is due to me put Binding Flags on the reflection as Public and Static.  I suppose I could have added Internal, but not sure, so I will leave for now as Public.

    public class ClientSideResourceHttpHandler : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            string typeName = context.Request.QueryString["typeName"];
            string twoLetterCultureName = context.Request.QueryString["culture"];
            string token = context.Request.QueryString["token"];
            string timestamp = context.Request.QueryString["timestamp"];
            string nocache = context.Request.QueryString["nocache"];
            var timeout = MvcApplication.ClientResourceConfiguration.ResourceSlidingTimeout;

            string key = GetKey(typeName, twoLetterCultureName);

            if (context.Cache[key] == null || !String.IsNullOrEmpty(nocache))
            {
                var type = Type.GetType(typeName);
                var resourceManager = new ResourceManager(type);

                if (!ValidateToken(typeName, twoLetterCultureName, timestamp, token))
                    throw new SecurityException("Invalid token submitted for client resource");

                var list = new List<KeyValuePair<string, string>>();
                var properties = type.GetProperties(
                    System.Reflection.BindingFlags.Public |
                    System.Reflection.BindingFlags.Static);

                foreach (var property in properties)
                {
                    if (property.PropertyType == typeof(string))
                    {

                        list.Add(
                            new KeyValuePair<string, string>(property.Name,
                                resourceManager.GetString(property.Name.Replace("_", " "),
                                GetCulture(twoLetterCultureName))
                                )
                        );
                    }
                }

                context.Cache.Insert(key, list, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(timeout));
            }

            context.Response.ContentType = "text/javascript";
            WriteOutClientResources(context.Response.OutputStream, (List<KeyValuePair<string, string>>)context.Cache[key]);
            context.Response.End();
        }

        #endregion

        private void WriteOutClientResources(Stream outputStream, List<KeyValuePair<string, string>> values)
        {
            using (var sw = new StreamWriter(outputStream))
            {
                sw.WriteLine(String.Format("var cache_date = \"{0}\";", DateTime.Now.ToString("f")));
                foreach (var item in values)
                {
                    sw.WriteLine(String.Format("var {0} = \"{1}\";", item.Key, item.Value));
                }
                sw.Flush();
            }
        }

        private bool ValidateToken(string typeName, string twoLetterCultureName, string timestamp, string token)
        {
            var valueToHmac = String.Concat(typeName, twoLetterCultureName, timestamp);
            var valueToCompare = CryptoHelper.Hmac(valueToHmac, MvcApplication.ClientResourceConfiguration.ResourceHmacKey, HashType.SHA1);
            return valueToCompare.Equals(token);
        }

        private string GetKey(string controllerName, string twoLetterCultureName)
        {
            return String.Format("{0}!{1}", controllerName, twoLetterCultureName);
        }

        private CultureInfo GetCulture(string twoLetterCultureName)
        {
            switch (twoLetterCultureName)
            {
                case "fr":
                    return CultureInfo.CreateSpecificCulture("fr-FR");
                default:
                    return CultureInfo.CreateSpecificCulture("en-GB");
            }
        }
    }

If you did not want the overhead of a Handler, or you do not want the actual dynamic script reference, then there is nothing stopping you in cutting this write down, and making a HtmlHelper which simply parsing a type and outputs the JavaScript variables directly to the requesting resource, so instead of an include script tag, it would output a script block directly in the dom.  Personally I just like the script tag and the visual reduction in code in the view source, I am unsure of any performance gain if any. 

So that is basically it, this is something I am definitely going to test drive and among other things, use it for other purposes.  One idea I had was to use this to generate Client Side objects based on say the models. I will do this for the next post I hope.



.NET | C# | JavaScript
Sunday, December 13, 2009 11:53:19 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer

This is the second in a small series I am writing on programmatic drawing inside Silverlight.  The first post I did on this was an analogue clock and it can be found here:

http://www.andrewrea.co.uk/2009/08/12/ProgrammaticDrawingWithSilverlight2030AnAnalogueClock.aspx

The code for this can be downloaded from the following link: http://lab.andrewrea.co.uk/DigitalClock.rar

In this post I will create a digital clock, with the disjointed digits you see in those stereotypical red digit alarm clocks.  The way I tackled this was look at the individual component parts and their grouping to ultimately give the representation of time or any other numerical value.  So each digit of the display is made up of individual bars with angle ends.  One of the key things with the angle ends, is that they are at a 45 degree angle, so that when brought together they line up with one another.

Image

image

Working In Silverlight

The parts of this inline with the code files are as follows:

  • IDigitalDigitPiece
  • IDigitalDigit
  • IDigitalState
  • IDigitalClockView

The second one in the list is the Digit State.  From the above examples you can see that each digit is made up of 7 component pieces, and each one represents their assigned digit by using different combinations of these digits.  In this case I have assigned two properties to each Digit being the OnColor and the OffColor.

The IDigitState has the following signature:

    public interface IDigitState
    {
        void Handle(IDigitalDigit digit);
    }

An example of one of the states is the following.  They simply assign the the OffColor or the OnColor to the Color property of the DigitalDigitPiece.

    public class FourState : IDigitState
    {

        #region IDigitState Members

        public void Handle(IDigitalDigit digit)
        {
            digit.DigitalDigitPieces[0].DigitColor = digit.OffColor;
            digit.DigitalDigitPieces[1].DigitColor = digit.OnColor;
            digit.DigitalDigitPieces[2].DigitColor = digit.OnColor;
            digit.DigitalDigitPieces[3].DigitColor = digit.OnColor;
            digit.DigitalDigitPieces[4].DigitColor = digit.OffColor;
            digit.DigitalDigitPieces[5].DigitColor = digit.OnColor;
            digit.DigitalDigitPieces[6].DigitColor = digit.OffColor;
        }

        #endregion
    }

I have pasted both the code for the digit and the digit piece below.  In hind sight I think it would have been better to use examples which display the binding.  The digit code displays how I am positioning the pieces after any resize or load events and the digit piece displays the code which shows how I am creating the shape of the pieces which make up the digit.

public partial class DigitalDigit : UserControl, IDigitalDigit
    {
        public List<DigitalDigitPiece> DigitalDigitPieces { get; protected set; }

        private double _sepDiameter;

        public double SepDiameter
        {
            get { return _sepDiameter; }
            set
            {
                if (value != _sepDiameter)
                {
                    _sepDiameter = value;
                    Draw();
                }
            }
        }

        private Color _sepColor;

        public Color SepColor
        {
            get { return _sepColor; }
            set
            {
                if (value != _sepColor)
                {
                    _sepColor = value;
                    Draw();
                }
            }
        }

        private Color _onColor = Colors.Red;

        public Color OnColor
        {
            get { return _onColor; }
            set { _onColor = value; }
        }

        private Color _offColor = Colors.Black;

        public Color OffColor
        {
            get { return _offColor; }
            set { _offColor = value; }
        }

        private double _pointSize = 10;

        public double PointSize
        {
            get { return _pointSize; }
            set
            {
                if (value != _pointSize)
                {
                    _pointSize = value;
                    Draw();
                }
            }
        }

        private Color _digitColor = Colors.Red;

        public Color DigitColor
        {
            get { return _digitColor; }
            set
            {
                if (value != _digitColor)
                {
                    _digitColor = value;
                    Draw();
                }
            }
        }

        public DigitalDigit()
        {
            InitializeComponent();
            CreateDigits();
            SizeChanged += new SizeChangedEventHandler(DigitalDigit_SizeChanged);
            Loaded += new RoutedEventHandler(DigitalDigit_Loaded);
        }

        void DigitalDigit_Loaded(object sender, RoutedEventArgs e)
        {
            Draw();
        }

        void DigitalDigit_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            Draw();
        }

        protected void Draw()
        {
            foreach (var digit in DigitalDigitPieces)
            {
                digit.PointSize = PointSize;
            }

            AlignDigits();
        }

        protected double LongHeight
        {
            get
            {
                return (ActualHeight / 2) - _pointSize;
            }
        }

        protected void AlignDigits()
        {
            if (ActualWidth > 0 && ActualHeight > 0)
            {
                DigitalDigitPieces[0].Orientation = DigitalDigitPieceOrientation.Horizontal;
                DigitalDigitPieces[0].Height = ActualWidth - (DigitalDigitPieces[0].PointSize * 2);
                DigitalDigitPieces[0].SetValue(Canvas.LeftProperty, DigitalDigitPieces[0].PointSize);
                DigitalDigitPieces[0].PointSize = PointSize;

                DigitalDigitPieces[1].SetValue(Canvas.LeftProperty, 0D);
                DigitalDigitPieces[1].Height = LongHeight;
                DigitalDigitPieces[1].SetValue(Canvas.TopProperty, (double)DigitalDigitPieces[0].Width / 2);
                DigitalDigitPieces[1].PointSize = PointSize;

                DigitalDigitPieces[2].SetValue(Canvas.LeftProperty, (double)ActualWidth - DigitalDigitPieces[2].Width);
                DigitalDigitPieces[2].Height = LongHeight;
                DigitalDigitPieces[2].SetValue(Canvas.TopProperty, (double)DigitalDigitPieces[0].Width / 2);
                DigitalDigitPieces[2].PointSize = PointSize;

                DigitalDigitPieces[3].Orientation = DigitalDigitPieceOrientation.Horizontal;
                DigitalDigitPieces[3].Height = ActualWidth - (DigitalDigitPieces[3].PointSize * 2);
                DigitalDigitPieces[3].SetValue(Canvas.LeftProperty, DigitalDigitPieces[3].PointSize);
                DigitalDigitPieces[3].SetValue(Canvas.TopProperty, (((double)DigitalDigitPieces[2].GetValue(Canvas.TopProperty)) + (double)(DigitalDigitPieces[2].Height - DigitalDigitPieces[2].PointSize)));
                DigitalDigitPieces[3].PointSize = PointSize;

                DigitalDigitPieces[4].SetValue(Canvas.LeftProperty, 0D);
                DigitalDigitPieces[4].Height = LongHeight;
                DigitalDigitPieces[4].SetValue(Canvas.TopProperty, (((double)DigitalDigitPieces[3].GetValue(Canvas.TopProperty)) + (double)(DigitalDigitPieces[3].Width / 2)));
                DigitalDigitPieces[4].PointSize = PointSize;

                DigitalDigitPieces[5].SetValue(Canvas.LeftProperty, (double)ActualWidth - DigitalDigitPieces[4].Width);
                DigitalDigitPieces[5].Height = LongHeight;
                DigitalDigitPieces[5].SetValue(Canvas.TopProperty, (((double)DigitalDigitPieces[3].GetValue(Canvas.TopProperty)) + (double)(DigitalDigitPieces[3].Width / 2)));
                DigitalDigitPieces[5].PointSize = PointSize;

                DigitalDigitPieces[6].Orientation = DigitalDigitPieceOrientation.Horizontal;
                DigitalDigitPieces[6].Height = ActualWidth - (DigitalDigitPieces[6].PointSize * 2);
                DigitalDigitPieces[6].SetValue(Canvas.LeftProperty, DigitalDigitPieces[3].PointSize);
                DigitalDigitPieces[6].SetValue(Canvas.TopProperty, (((double)DigitalDigitPieces[5].GetValue(Canvas.TopProperty)) + (double)(DigitalDigitPieces[5].Height - DigitalDigitPieces[5].PointSize)));
                DigitalDigitPieces[6].PointSize = PointSize;
            }
        }

        protected void CreateDigits()
        {
            DigitalDigitPieces = new List<DigitalDigitPiece>();
            for (var i = 0; i < 7; i++)
            {
                var piece = new DigitalDigitPiece();
                DigitalDigitPieces.Add(piece);
                LayoutRoot.Children.Add(DigitalDigitPieces[i]);
            }
        }

        #region IDigitalDigit Members

        public void SetState(IDigitState state)
        {
            state.Handle(this);
        }

        #endregion

        public void Update()
        {
            Draw();
        }
    }

 public partial class DigitalDigitPiece : UserControl
    {
        private double _angle = 0D;

        private double _pointSize = 10;

        public double PointSize
        {
            get { return _pointSize; }
            set
            {
                if (value != _pointSize)
                {
                    _pointSize = value;
                    Draw();
                }
            }
        }

        private Color _digitColor;

        public Color DigitColor
        {
            get { return _digitColor; }
            set
            {
                if (value != _digitColor)
                {
                    _digitColor = value;
                    Draw();
                }
            }
        }

        private DigitalDigitPieceOrientation _orientation;

        public DigitalDigitPieceOrientation Orientation
        {
            get { return _orientation; }
            set
            {
                if (value != _orientation)
                {
                    _orientation = value;
                    Draw();
                }
            }
        }

        private Polygon _polygon;

        public Polygon Polygon
        {
            get { return _polygon; }
            set { _polygon = value; }
        }

        public DigitalDigitPiece()
        {
            _digitColor = Colors.Red;
            _orientation = DigitalDigitPieceOrientation.Vertical;
            _polygon = new Polygon();

            InitializeComponent();
            SizeChanged += new SizeChangedEventHandler(DigitalDigitPiece_SizeChanged);
            Loaded += new RoutedEventHandler(DigitalDigitPiece_Loaded);

            LayoutRoot.Children.Add(_polygon);
        }

        void DigitalDigitPiece_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            Draw();
        }

        void DigitalDigitPiece_Loaded(object sender, RoutedEventArgs e)
        {
            Draw();
        }

        protected void Draw()
        {
            Width = _pointSize * 2;

            _polygon.Points = new PointCollection
            {
                 new Point(Width / 2,0),
                 new Point(Width, _pointSize),
                 new Point(Width, Height - _pointSize),
                 new Point(Width/2,Height),
                 new Point(0,Height-_pointSize),
                 new Point(0, _pointSize),
                 new Point(Width/2,0)
            };
            _polygon.Fill = new SolidColorBrush(DigitColor);
            _polygon.Stroke = new SolidColorBrush(Colors.Black);
            _polygon.StrokeThickness = 1D;

            var rotate = new RotateTransform();
            rotate.CenterX = _pointSize;
            rotate.CenterY = _pointSize;
            if (_orientation == DigitalDigitPieceOrientation.Horizontal)
            {
                if (_angle == 0 || _angle == 90)
                    _angle = -90;
            }
            else
            {
                if (_angle == -90)
                    _angle = 90;
                else
                    _angle = 0;
            }

            rotate.Angle = _angle;
            _polygon.RenderTransform = rotate;

        }
    }

The actual view is simply a user control which contains instances of the digits inside and arranges them accordingly.  The class which I have not mentioned is the separator class and that is simply two ellipses which I have added control for, both for size and the colour inside the containers.

<UserControl x:Class="DigitalClock.DigitalClockView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:custom="clr-namespace:DigitalClock">
    <Grid x:Name="LayoutRoot" Background="Black">
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition />
        </Grid.RowDefinitions>
        <custom:DigitalDigit x:Name="Hour1" Grid.Column="0" PointSize="20" OnColor="Beige" />
        <custom:DigitalDigit x:Name="Hour2" Grid.Column="1" PointSize="20" OnColor="Beige"/>
        <custom:DigitalClockSeparator x:Name="sep1" Grid.Column="2" HorizontalAlignment="Center" />
        <custom:DigitalDigit x:Name="Minute1" Grid.Column="3" PointSize="20" />
        <custom:DigitalDigit x:Name="Minute2" Grid.Column="4" PointSize="20" />
        <custom:DigitalClockSeparator x:Name="sep2" Grid.Column="5" HorizontalAlignment="Center"/>
        <custom:DigitalDigit x:Name="Second1" Grid.Column="6" PointSize="20" />
        <custom:DigitalDigit x:Name="Second2" Grid.Column="7" PointSize="20" />
    </Grid>
</UserControl>

I found a couple of gotchas and a big one includes that upon an exception, SilverLight will continue to try and render what it has even after an exception and it looks likes values default to zero, which admittedly seems logical.  Take a peek at this screen print from the above app during development.

image 

Tis all for now,

Cheers,


Andrew



.NET | C# | Silverlight
Sunday, November 22, 2009 11:22:03 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer

An extremely important procedure when working with WCF Services or any remote proxy is to close the service when you are finished using it.  I have been working a lot with Structure Map of late as opposed to Microsoft Unity and one thing which I wanted to have a look at was, injecting an instance of the service proxy into my controllers.  Now before I started one thing was circling in my mind, my normal usage when it came to WCF would be that I wrap the proxy inside a using statement, guaranteeing that it would be disposed of correctly. 

Since I am now injecting this service proxy into the constructor, it became apparent that I now needed a finish line where I could dispose of the service proxy after it had been used. Currently, what seems to be working is, as obvious as this sounds, placing the logic inside an override of the base controller’s Dispose method. 

There were a few ideas going through my head but unfortunately this was not sticking out at all, not sure why.  It was only when my attention was brought to the controller factory that it came clear.  The first attempt, which was successful, was to override the ReleaseController method of the Controller Factory.  Inside here I checked whether the controller could be assigned from IDisposable, and if so, cast and call.  This method meant I needed to implement the IDisposable interface on the Controller, well here is something which I SHOULD HAVE KNOWN:

Controller implements IDisposable –> doh! arrghhh

Yeh, not sure why this was not immediately obvious to me but hey ho, you live and learn , so I now removed the unnecessary override inside the Controller Factory and simply override the Dispose method inside the controller. 

        protected override void Dispose(bool disposing)
        {
            (_forumService as IDisposable).Dispose();
            base.Dispose(disposing);
        }

Great stuff, so now when my controller is released my service proxy is also cleaned up.  This is great timing for me and at present works fine.  I am using request/response objects so any information which needs to be dealt with inside a transaction is encapsulated inside the request object which are flat-ISH data transfer objects which can then be processed on the server.

You will notice, or should anyway that without this call to dispose, you wcf service application will not know that the client connection has been terminated.  I have seen that there is obviously a limit to concurrent connections that the service will handle, and when all are in progress, further requests are queued up. Now I have this, and also the service proxy injected, the controller is nice and slick.

Here is an example of what my controller now looks like using the injection of the service proxy:

    public class ForumController : Controller
    {
        private readonly IForumService _forumService;

        public ForumController(IForumService forumService)
        {
            _forumService = forumService;
        }

        public ActionResult Index(int id, int? pageIndex, int? pagseSize)
        {
            var request = new GetForumRequest
            {
                ForumId = id,
                Query = new PagedQueryDto
                {
                    PageIndex = pageIndex ?? 0,
                    PageSize = pagseSize ?? 10,
                    SortOrder = new SortOrderCollection
                    {
                         new SortOrder
                         {
                              ColumnName = "Id",
                              Ascending = false
                         }
                    }
                }
            };

            GetForumResponse response = (GetForumResponse) _forumService.ProcessRequest(request);

            return View(response);
        }

        protected override void Dispose(bool disposing)
        {
            (_forumService as IDisposable).Dispose();
            base.Dispose(disposing);
        }
    }

Once I am further along with more request/response objects I will be putting this sample application up onto Google Code.  This is a project I am deving for the purposes of helping me learn more about Enterprise Architecture with specific focus on the following:

  • Domain Driven Design
  • Domain Events
  • Services
  • Dependency Injection and Inversion Of Control
  • Messaging Systems

Anyways, hope this is of some help,

Cheers for now,

Andrew


Monday, October 12, 2009 12:03:09 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer

Another post I am writing shortly will demo why I came to write this short helper class.  I basically wanted a short routine which would allow me to generate a hash and later a KHMAC from the well known Hashing Algorithms including:

  • MD5
  • SHA1
  • SHA256
  • SHA384
  • SHA512

The KHMAC is slightly different to a hash, in that it adds another structured layer to the hashing process.  The formula for making the KHMAC is: HMAC(K,m) = H((K ⊕ opad) ∥ H((K ⊕ ipad) ∥ m)) which I found at wikipedia here. At the time of reading this article I was going to transpose the pseudo code on the page to a C# method, until I discovered that Microsoft has already done this in the .NET Cryptography Assembly.  The above bulleted points are implementations of HashAlgorithm .  The ones which we need to use to implement KHMAC are all implementations of a derived class of KeyedHashAlgorithm , which include:

  • HMACMD5
  • HMACSHA1
  • HMACSHA256
  • HMACSHA384
  • HMACSHA512

The code for the helper class is as follows:

public static class CryptoHelper
    {
        public static string Hash(string value, HashType hashType, string salt)
        {
            return Hash(value + salt, hashType);
        }

        public static string Hash(string value, HashType hashType)
        {
            switch (hashType)
            {
                case HashType.SHA1:
                    return Hash(new SHA1CryptoServiceProvider(), value);
                case HashType.SHA256:
                    return Hash(new SHA256CryptoServiceProvider(), value);
                case HashType.SHA384:
                    return Hash(new SHA384CryptoServiceProvider(), value);
                case HashType.SHA512:
                    return Hash(new SHA512CryptoServiceProvider(), value);
                default:
                    return Hash(new MD5CryptoServiceProvider(), value);

            }
        }

        public static string Hmac(string value, string secretKey, HashType hashType)
        {
            byte[] key = Encoding.ASCII.GetBytes(secretKey);

            switch (hashType)
            {
                case HashType.SHA1:
                    return Hash(new HMACSHA1(key), value);
                case HashType.SHA256:
                    return Hash(new HMACSHA256(key), value);
                case HashType.SHA384:
                    return Hash(new HMACSHA384(key), value);
                case HashType.SHA512:
                    return Hash(new HMACSHA512(key), value);
                default:
                    return Hash(new HMACMD5(key), value);
            }
        }

        private static string Hash(HashAlgorithm algor, string value)
        {
            var tmpSource = ASCIIEncoding.ASCII.GetBytes(value);
            var tmpHash = algor.ComputeHash(tmpSource);

            var builder = new StringBuilder();
            for (var i = 0; i < tmpHash.Length; i++)
            {
                builder.Append(tmpHash[i].ToString("X2"));
            }
            return builder.ToString();
        }
    }

The enum which I have created is literally to enable the use of the well known hashing algorithms.

    public enum HashType
    {
        MD5,
        SHA1,
        SHA256,
        SHA384,
        SHA512
    }

For the purposes of demonstration I have iterated through the enum types and used each one with a set routine of applying the hash or KHMAC to a specific value and outputted the result.  In the screen shot below you can clearly see the difference in the size of the resulting KHMAC.  One of the “key” things I read about the KHMAC is that the secret key has to be the same length as the block size of the hashing algorithm.  What this means is that if the key is shorted it will pad it, and if longer it will hash it, automatically adjusting the size of the key to the max length allowed. 

        static void Main(string[] args)
        {
            int recordID = 65536;

            foreach (var enumType in Enum.GetNames(typeof(HashType)))
            {
                HashType hashType = (HashType) Enum.Parse(typeof(HashType), enumType);

                string hashValue = CryptoHelper.Hash(recordID.ToString(), hashType);
                string hashValueWithSalt = CryptoHelper.Hash(recordID.ToString(), hashType, "SALT");
                string hmacValue = CryptoHelper.Hmac(recordID.ToString(), "SECRET_KEY", hashType);

                Console.WriteLine(enumType);
                Console.WriteLine("=".PadRight(50,'='));
                Console.WriteLine();
                Console.WriteLine("Hash           : {0}", hashValue);
                Console.WriteLine("Hash With salt : {0}", hashValueWithSalt);
                Console.WriteLine("Hmac           : {0}", hmacValue);
                Console.WriteLine();
                Console.WriteLine();
            }

            Console.ReadLine();
        }

The output

image

I remember having to use something similar with Amazon web services which required the provision of a token with each call and this token was a concatenation of a few bits of information and then hashed using SHA1.  The above solution is more secure that this, but SHA1 is still extremely secure.  I have also seen ebay do something similar for the authentication of the requests and it is really very clever but in actual fact rather straight forward.  Imagine you supply the following information with a call to a web service:

  • UserID
  • TimeStamp
  • KHMAC

The client side and library would have the secret key with which to generate the KHMAC and the value to hash would be the concatenation of the UserID and Timestamp .  Obviously you could add more distinguishing values to determine the value to be hashed.  Because of the inclusion of the time stamp it means that the hashed value will differ each time even if the value stays the same.  The process to authenticate this request would be as follows:

  1. Client generates the KHMAC
  2. Client sends the UserID, TimeStamp and KHMAC
  3. Server receives the web service request
  4. Server looks up user’s secret key using the user id supplied
  5. Server generates a KHMAC using the UserID, TimeStamp and the secret key retrieved from the data store
  6. Server compares the newly generated KHMAC with the one supplied by the client

The comparison will then show you whether or not the call is genuine. 

Hope this helps,

Cheers for now,

Andrew



.NET | C#
Monday, October 05, 2009 11:13:48 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer

The first part in this series which I would like to do can be found here:

Part 1 : Socket Programming with C#, JAVA, C++ and Action Script 3.0 – Establishing a base connection and communication with C# Server and AS3

The files for this solution can be downloaded here: WCFCallbackExample

I am looking into how you can work with network communication with sockets using the different languages and this post will use C# and more specifically WCF.  In this post I will look at the bi directional capability of WCF using the NetTcpBinding, I will follow up this post in the near future with an example using the Duplex WS binding (WSDualHttpBinding).  If you are in the area of Application Development and say wanting to use this for example with a chat application, the NetTcpBinding requires that both the client and the service use WCF, so for interoperability that is not really of much use, but there is more than one way to skin a cat for sure.

In this post and the example solution I am making use of threading for the purposes of the example so I can simulate many clients, as opposed to launching the application many times.  I will be making use of the Thread class, ThreadPool class, WaitHandle class, ManualResetEvent class and using a ParamterizedThreadStart and WaitCallBack delegates.  I have also made an extension method which the mode value of an IList<T>.

The theme of this example will be voters casting these vote.  Once all the votes are in, in this case 10, the votes will be counted and all the voters will be informed of the winning candidate.

NetTcpBinding

For the code in this example I am not using the configuration files, I am instantiating and configuring on the fly programmatically as I want to get a feel for accomplishing tasks both programmatically and through xml configuration as both have their benefits dependant on the situation.  The basic idea which I want to demonstrate first of all goes like this.

  1. Instantiate and open a service host to accept incoming messages
  2. Instantiate a client a proxy a call to the listening service
  3. On the server side I want to process the message call from the client and then call-back to the client using the method which I define with an interface(the contract).

The Program

The files which make up this small program include the following:

  • IVote
  • IVoteCallback
  • Client
  • ListExtension
  • Proxy
  • Server
  • ServiceHost

image

I have separated the client from the proxy, first because lol it is a proxy but also each one has a different responsibility, what you end up with though is Client calls Vote on Proxy, Proxy calls Vote on the Service.  So it is exactly that “a proxy,” i.e. the middle person.

I have used the following class for a generic Service Host from the following book, Programming WCF Services.

    public class ServiceHost<T> : ServiceHost
    {
        public ServiceHost()
            : base(typeof(T))
        { }

        public ServiceHost(params string[] baseAddresses)
            : base(typeof(T), Convert(baseAddresses))
        { }

        public ServiceHost(params Uri[] baseAddresses)
            : base(typeof(T), baseAddresses)
        { }

        static Uri[] Convert(string[] baseAddresses)
        {
            Converter<string, Uri> convert = delegate(string address)
            {
                return new Uri(address);
            };

            return Array.ConvertAll(baseAddresses, convert);
        }
    }

The call-back

This is very much an event, and as such many client can subscribe to this event.  It is the service’s responsibility to ensure all subscribers of this event are notified upon the invocation of some trigger, “Don’t call us we shall call you.”

As much as this is an event, the way you program this as opposed to normal CLR Event Subscription and Invocation is different and slightly more management is required with regards to concurrency.

The contract for the call-back is simply the following:

    public interface IVoteCallback
    {
        [OperationContract]
        void OnVotesCounted(string winner);
    }

The server will invoke this method on the clients, and the clients themselves will inherit from this interface so the server can invoke the method on it.  The implementation of this method is up to the client, but it is the responsibility of the Service Host to invoke it.

The Service Contract

The following contract is what the service needs to use, and also any proxy that is made for this service. The client invokes the contract on the proxy and in turn the proxy invokes the contract on the service.

    [ServiceContract(Name = "WCFCallbackExample.Contract.IVote",
        Namespace="uk.co.andrewrea",
        SessionMode=SessionMode.Required,
        CallbackContract=typeof(IVoteCallback))]
    public interface IVote
    {
        [OperationContract(IsOneWay=true)]
        void PlaceVote(string name);
    }

This interface requires some specific attributes for the purposes of:

  1. Being a service contract
  2. Providing operation contracts for a service
  3. Allowing the service to be used in a Duplex hosting scenario, i.e. the service host can send messages to the client as well as the client can send messages to the service
  4. Information for WCF to recognise what call-back it is dealing with.

The session mode is set to required so a call-back can be sent to the client, this is also true of the WSDualHttpBinding.

Also I will mention why I have made the operation in this contract one way below.

The Server

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall,
        ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class Server : ServiceHost<Server>, IVote
    {
        //A collection of votes from the clients.  
        //The candidate name is the string object value
        private static List<string> _votes
            = new List<string>();

        //A list of the callbacks which the server should invoke
        //allowing the clients to be notified
        private static List<IVoteCallback> _callbacks
            = new List<IVoteCallback>();

        //For the purposes of syncronization
        private static object _syncLock = new Object();

        public Server()
            : base()
        {

        }

        public Server(params string[] addresses)
            : base(addresses)
        {

        }

        #region IVote Members

        /// <summary>
        /// This method will be proxied and called by the client
        /// </summary>
        /// <param name="name"></param>
        public void PlaceVote(string name)
        {
            lock (_syncLock)
            {
                //Get the callback from the client
                IVoteCallback callback = OperationContext.Current
                    .GetCallbackChannel<IVoteCallback>();

                //If the service does not already contain the callback add it
                if (!_callbacks.Contains(callback))
                    _callbacks.Add(callback);

                //Add the vote
                _votes.Add(name);

                //I do not want to block here, so I accept the vote and 
                //call the method to count the votes on another thread
                //
                //I origianlly used the below BUT making the operation IsOneWay
                //Achieves the same thing.  Without this or the IsOneWay,
                //this will block the client thread.
                //ThreadPool.QueueUserWorkItem(new WaitCallback(CheckVoteCount));

                if (_votes.Count == 10)
                {
                    System.Threading.Thread.Sleep(2000);
                    VotesCounted();
                }
            }
        }

        /*
         * 
         * This was called by the ThreadPool, see above
        private void CheckVoteCount(object state)
        {
            if (_votes.Count == 10)
            {
                System.Threading.Thread.Sleep(2000);
                VotesCounted();
            }
        }
         * */

        #endregion

        /// <summary>
        /// This is the callback.  It will loop through all of them and
        /// invoke.  This is the method which updates the clients
        /// </summary>
        private static void VotesCounted()
        {
            Action<IVoteCallback> invoke =
                delegate(IVoteCallback clientCallback)
                {
                    clientCallback.OnVotesCounted(_votes.MostOccurences<string>());
                };

            _callbacks.ForEach(invoke);

        }
    }

The server is keeping a list of:

  • Votes
  • Call-backs

I have plumbed in some thread safety, as each call made to the service will be from a different thread.  You will notice that there is some code I have commented out but left in there.  This is because I wanted to explain the purpose of why I have not used it and what I have used instead.  What I was doing there was ensuring that the method did not block the client thread, so I did the work of the client and then kicked off another thread to check whether or not it should count the votes.  After doing this though, I thought about the IsOneWay attribute property which did exactly what I require.  If you specify this on an operation context, the client will call and forget about the method, i.e. it will not block as it does not care about is outcome so in this way I was able to leave the check for the votes inside the client method and this did not affect the client in terms of time.

Above when I said this was like the CLR Event model in a way, I would now say that through its implementation, it is more like the Java Event Model where you specifically add listeners and the object loops through its subscribers and calls the method the listener has provided as the call-back.  I realise under the covers this is what the clr event model will do, but from a coding point of view, it is more Java’esque – The Observer Pattern.

I will show the source for the extension method, MostOccurences<T> below.

The Proxy

    public class Proxy : DuplexClientBase<IVote>, IVote
    {
        public Proxy(InstanceContext context,
            Binding binding,
            EndpointAddress endpointAddress)
            : base(context, binding, endpointAddress)
        {

        }

        #region IVote Members

        public void PlaceVote(string name)
        {
            Channel.PlaceVote(name);
        }

        #endregion
    }

I have inherited both from the service contract but also from the DuplexClientBase<T> as opposed to the ClientBase<T> which allows the client to accept call-backs from the service.  As a proxy should, the PlaceVote method calls the PlaceVote of the service.  Although I have specified a constructor which allows the supply of a Binding, I am only using NetTcpBinding for this program but I have supplied it, as this is a constructor of the base class.  The InstanceContext is used directly for the call-back, so the service can identify what object instance to use for the call-back method.

The Client

    public class Client : IVoteCallback,IVote
    {
        private Proxy _proxy;
        private string _voterName;
        private ManualResetEvent _handle;

        public Client(string voterName, string serviceEndpointAddress, ManualResetEvent handle)
        {
            _voterName = voterName;
            _handle = handle;
            InstanceContext context = new InstanceContext(this);
            _proxy = new Proxy(context,
                new NetTcpBinding(),
                new EndpointAddress(serviceEndpointAddress));

        }

        #region IVoteCallback Members

        public void OnVotesCounted(string winner)
        {
            Console.WriteLine(String.Format("{0} has been notified the winner is {1}",_voterName, winner ));
            _handle.Set();
        }

        #endregion

        #region IVote Members

        public void PlaceVote(string name)
        {
            _proxy.PlaceVote(name);
            Console.WriteLine(String.Format("From {0}: I have placed my vote for {1}!", _voterName, name));
        }

        #endregion
    }

A lot of this code, is specific just to this example but it is the instantiation of the proxy and in turn the invocation of its method, and the implementation of both the Service Contract and the Call-back contract which are important.  The threading elements are just to provide synchronization and are used so I can test the service with multiple clients(threads). 

The Extension Method (ListExtenions.cs)

        public static T MostOccurences<T>(this IList<T> list)
        {
            Dictionary<T, int> count = new Dictionary<T, int>();
            foreach (T obj in list)
            {
                if (!count.ContainsKey(obj))
                {
                    count.Add(obj, 1);
                }
                else
                {
                    count[obj]++;
                }
            }

            return count.Where(x => x.Value.Equals(count.Max(k=>k.Value))).FirstOrDefault().Key;
        }

This will give me the value of the IList<T> which occurs most often, and its use is so I can see the candidate who won.

Program.cs

This is the main program where I implement the work.  Again the threading stuff is just for the purposes of the example.

    class Program
    {
        private static Server server;

        private static string netServerAddress = "net.tcp://localhost:8000";
        private static string endpointAddress = "net.tcp://localhost:8000/VotingService";
        private static Random rnd;

        private static string[] candidates = new string[]{
            "Candidate 1",
            "Candidate 2",
            "Candidate 3"
        };

        private static ManualResetEvent[] handles = new ManualResetEvent[10];
        private static Thread[] threads = new Thread[10];
        
        static void Main(string[] args)
        {
            rnd = new Random();

            StartService();

            for (int i = 0; i < 10; i++)
            {
                handles[i] = new ManualResetEvent(false);
                threads[i] = new Thread(new ParameterizedThreadStart(CreateClientAndVote));
                threads[i].Start(i);
            }

            Console.WriteLine("Waiting for votes to come in...");

            WaitHandle.WaitAll(handles);

            server.Close();

            Console.WriteLine("Voting has ended");

            Console.ReadLine();
        }

        static void StartService()
        {
            server = new Server(netServerAddress);
            server.AddServiceEndpoint(
                "WCFCallbackExample.Contract.IVote",
                new NetTcpBinding(),
                endpointAddress);
            server.Open();
        }

        static void CreateClientAndVote(object state)
        {
            int number = (int)state;
            Client newClient = new Client(String.Format("Voter #{0}", number + 1), endpointAddress, handles[number]);
            newClient.PlaceVote(candidates[(int)(rnd.Next(candidates.Length))]);
        }
    }

image

And thats it.  I hope this is of some help and/or interest.

Cheers for now,

Andrew.



.NET | C# | WCF
Wednesday, August 26, 2009 6:23:44 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer

Download the source project

Image

image

Working in Silverlight

 

 

I have seen a lot of comparisons made between ActionScript and Silverlight with specific focus on the difference in lines of code, and more specifically when referring to the drawing api.  What I thought I would do is do a little drawing and in this example I have developed a teeny tiny interface for a clock view, which has a method of simply SetTime(DateTime time)  and I have made one implementation of this Clock view which is an analogue clock.  I have used some simple ellipse equations to allow for dynamic resize and redraw and in hind sight I would refactor my code so as not to keep adding and removing the shapes which are UIElements.  I will make some more clocks with this refactoring present.  It does feel like a gauge control is on the way also, there are so many gauge controls out there including the, cool, free ones from Microsoft, well they are charting controls but never the less and absolutely amazing freebie.

So the whole purpose of this post is about programmatic drawing as opposed to using the XAML equivalent, which I might say would be worth looking at to replicate this example! 

The Code

So to the code, first I have defined a short interface as follows:

namespace SilverlightClock
{
    public interface IClockView
    {
        void setTime(DateTime time);
    }
}

Next is the xaml mark-up, and the only thing I have amended is the Root UIElement which I have used a Canvas as opposed to the default Grid.  This lets me set things out using the Canvas.LeftProperty and Canvas.TopProperty.

<UserControl x:Class="SilverlightClock.AnalogueClock"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="300">
    <Canvas x:Name="LayoutRoot" Background="White">

    </Canvas>
</UserControl>

Next is the mark-up and class diagram for the actual UserControl - AnalogueClock.

image  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightClock
{
    public partial class AnalogueClock : UserControl, IClockView
    {
        private DateTime _time = new DateTime(2000, 1, 1, 18, 15, 50);
        private double hour;
        private double minute;
        private double second;

        public AnalogueClock()
        {
            InitializeComponent();
            SizeChanged += new SizeChangedEventHandler(AnalogueClock_SizeChanged);
            Loaded += new RoutedEventHandler(AnalogueClock_Loaded);
        }

        void AnalogueClock_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            Draw();
        }

        void AnalogueClock_Loaded(object sender, RoutedEventArgs e)
        {
            Draw();
        }

        void Draw()
        {
            LayoutRoot.Children.Clear();
            var step = 360 / 60;
            var innerRadiusX = (Width * 0.7) / 2;
            var innerRadiusY = (Height * 0.7) / 2;
            var outerRadiusX = (Width * 0.8) / 2;
            var outerRadiusY = (Height * 0.8) / 2;
            var textRadiusX = (Width * 0.9) / 2;
            var textRadiusY = (Height * 0.9) / 2;
            var outerCasing = new Ellipse();
            outerCasing.Stroke = new SolidColorBrush(Colors.Black);
            outerCasing.Width = (Width * 0.8);
            outerCasing.Height = (Height * 0.8);
            outerCasing.SetValue(Canvas.LeftProperty, Width * 0.1);
            outerCasing.SetValue(Canvas.TopProperty, Height * 0.1);
            LayoutRoot.Children.Add(outerCasing);

            for (var i = 0; i < 60; i++)
            {
                var line = new Line
                {
                    Stroke = new SolidColorBrush(Colors.Black),
                    X1 = (Width / 2) + Math.Sin((step * i) * (Math.PI / 180)) * innerRadiusX,
                    Y1 = (Height / 2) + Math.Cos((step * i) * (Math.PI / 180)) * innerRadiusY,
                    X2 = (Width / 2) + Math.Sin((step * i) * (Math.PI / 180)) * outerRadiusX,
                    Y2 = (Height / 2) + Math.Cos((step * i) * (Math.PI / 180)) * outerRadiusY
                };


                if (i % 5 == 0)
                {
                    line.X1 = (Width / 2) + Math.Sin((step * i) * (Math.PI / 180)) * ((Width * 0.6) / 2);
                    line.Y1 = (Height / 2) + Math.Cos((step * i) * (Math.PI / 180)) * ((Height * 0.6) / 2);

                    var textblock = new TextBlock();
                    textblock.Text = i == 0 ? "12" : ((double)(i / 60D) * 12D).ToString();

                    var textX = (Width / 2) + Math.Sin(-((step * i + 180) % 360) * (Math.PI / 180)) * textRadiusX;
                    var textY = (Height / 2) + Math.Cos(-((step * i + 180) % 360) * (Math.PI / 180)) * textRadiusY;

                    textblock.SetValue(Canvas.LeftProperty, textX - textblock.ActualWidth / 2);
                    textblock.SetValue(Canvas.TopProperty, textY - textblock.ActualHeight / 2);

                    LayoutRoot.Children.Add(textblock);
                }

                LayoutRoot.Children.Add(line);
            }


            DrawHourHand();
            DrawMinuteHand();
            DrawSecondHand();
            DrawMilliSeconds();
            DrawLogo();
        }

        private void DrawLogo()
        {
            var textBlockLogo = new TextBlock();
            textBlockLogo.Text = "andrewrea.co.uk";
            textBlockLogo.FontFamily = new FontFamily("Arial");
            textBlockLogo.FontSize = 9D;
            textBlockLogo.SetValue(Canvas.LeftProperty, (Width - textBlockLogo.ActualWidth) / 2);
            textBlockLogo.SetValue(Canvas.TopProperty, (Height - textBlockLogo.ActualHeight) / 3);
            LayoutRoot.Children.Add(textBlockLogo);
        }

        private void DrawHourHand()
        {
            //Change hour value to percentage for use with 360
            double hourPercentage = (hour + (minute / 60D)) / 12D;

            //Get the Hour degree value
            double hourDegree = 360 * hourPercentage;

            DrawHand(Width / 5.5D, Height / 5.5D, -hourDegree, Colors.Black, 3);
        }

        private void DrawMinuteHand()
        {
            //Change minute value to percentage for use with 360
            double minutePercentage = (minute + (second / 60D)) / 60;
            //Get the minute percentage
            double minuteDegree = 360 * minutePercentage;

            DrawHand(Width / 4.5D, Height / 4.5D, -minuteDegree, Colors.Blue, 2);
        }

        private void DrawSecondHand()
        {
            double secondPercentage = second / 60D;
            //Get the minute percentage
            double secondDegree = 360 * secondPercentage;

            DrawHand(Width / 3.5D, Height / 3.5D, -secondDegree, Colors.Red, 1);
        }

        private void DrawMilliSeconds()
        {
            //Figure out the second hand
            double millisecond = _time.Millisecond;
            //Change minute value to percentage for use with 360
            double millisecondPercentage = millisecond / 1000;
            //Get the minute percentage
            double millisecondDegree = 360 * millisecondPercentage;

            var milliContainer = new Ellipse();
            milliContainer.Width = (Width * 0.1D) + 1;
            milliContainer.Height = (Height * 0.1D) + 1;
            milliContainer.Stroke = new SolidColorBrush(Colors.Black);
            milliContainer.SetValue(Canvas.LeftProperty, (Width * 0.65) - (Width * 0.05D));
            milliContainer.SetValue(Canvas.TopProperty, (Height * 0.65) - (Height * 0.05D));

            var hand = new Line
            {
                Stroke = new SolidColorBrush(Colors.Green),
                X1 = Width * 0.65,
                Y1 = Height * 0.65,
                X2 = (Width * 0.65) + -Math.Sin(-millisecondDegree * (Math.PI / 180)) * (Width * 0.05D),
                Y2 = (Height * 0.65) + -Math.Cos(-millisecondDegree * (Math.PI / 180)) * (Height * 0.05D)
            };

            LayoutRoot.Children.Add(milliContainer);
            LayoutRoot.Children.Add(hand);
        }

        private void DrawHand(double radiusX, double radiusY, double angle, Color color, double thickness)
        {
            var hand = new Line
            {
                Stroke = new SolidColorBrush(color),
                X1 = Width / 2,
                Y1 = Height / 2,
                X2 = (Width / 2) + -Math.Sin(angle * (Math.PI / 180)) * radiusX,
                Y2 = (Height / 2) + -Math.Cos(angle * (Math.PI / 180)) * radiusY
            };
            hand.StrokeThickness = thickness;

            LayoutRoot.Children.Add(hand);
        }

        #region IClockView Members

        public void SetTime(DateTime time)
        {
            _time = time;
            hour = _time.Hour;
            minute = _time.Minute;
            second = _time.Second;
            
            Draw();
        }

        #endregion
    }
}

Next is the xaml mark-up for the actual page.xaml .  Really I could have created a Presenter for this, but I haven’t.  The setup is primed for one since I am declaring an interface for an actual clock view, and like many examples in many other programming languages, a good second view for this interface would be a DigitalClock user control. I think that it would be a nice second example to use to have a deeper look into how we can skin it up to such an extent for it to resemble to classic 80’s style red digit alarm clock.

So the xaml mark-up.  This is simply the grid layout, labels and instances of the user control.

<UserControl x:Class="SilverlightClock.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
             xmlns:x2="clr-namespace:SilverlightClock"
    Width="600" Height="460">
    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="30"/>
            <RowDefinition />
            <RowDefinition Height="30" />
            <RowDefinition />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <TextBlock Text="London" Grid.Column="0" Grid.Row="0" 
                   HorizontalAlignment="Center" 
                   VerticalAlignment="Center" FontWeight="ExtraBlack"></TextBlock>
        <x2:AnalogueClock Height="200" Width="200" x:Name="ClockLondon" 
                          HorizontalAlignment="Stretch" 
                          VerticalAlignment="Stretch"
                          Grid.Column="0" Grid.Row="1"></x2:AnalogueClock>
        <TextBlock Text="New York" Grid.Column="1" Grid.Row="0" 
                   HorizontalAlignment="Center" 
                   VerticalAlignment="Center" FontWeight="ExtraBlack"></TextBlock>
        <x2:AnalogueClock Height="200" Width="200" x:Name="ClockNewyork" 
                          HorizontalAlignment="Stretch" 
                          VerticalAlignment="Stretch"
                          Grid.Column="1" Grid.Row="1"></x2:AnalogueClock>
        <TextBlock Text="Sydney" Grid.Column="2" Grid.Row="0" 
                   HorizontalAlignment="Center" 
                   VerticalAlignment="Center" FontWeight="ExtraBlack"></TextBlock>
        <x2:AnalogueClock Height="200" Width="200" x:Name="ClockSydney" 
                          HorizontalAlignment="Stretch" 
                          VerticalAlignment="Stretch"
                          Grid.Column="2" Grid.Row="1"></x2:AnalogueClock>
        <TextBlock Text="Paris" Grid.ColumnSpan="3" Grid.Row="2" 
                   HorizontalAlignment="Center" 
                   VerticalAlignment="Center" FontWeight="ExtraBlack"></TextBlock>
        <x2:AnalogueClock Height="200" Width="600" x:Name="ClockParis" 
                          HorizontalAlignment="Stretch" 
                          VerticalAlignment="Stretch"
                          Grid.ColumnSpan="3" Grid.Row="3"></x2:AnalogueClock>
    </Grid>
</UserControl>

The last part is the code behind for this page.xaml, and it is something which I think I should have probably used a storyboard for, but I am not too sure. Either way I have used a timer and it is a bit too processor intensive, I think I would want to use the Silverlight equivalent of the flash Event.ENTER_FRAME and I say equivalent because Silverlight does not use frames ;-)

namespace SilverlightClock
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();

            Loaded += new RoutedEventHandler(Page_Loaded);
        }

        void dt_Tick(object sender, EventArgs e)
        {
            ClockLondon.SetTime(DateTime.Now);
            ClockNewyork.SetTime(DateTime.Now.AddHours(-5));
            ClockSydney.SetTime(DateTime.Now.AddHours(10));
            ClockParis.SetTime(DateTime.Now.AddHours(2));
        }

        void Page_Loaded(object sender, RoutedEventArgs e)
        {
            System.Windows.Threading.DispatcherTimer dt = new System.Windows.Threading.DispatcherTimer();
            dt.Interval = new TimeSpan(0, 0, 0, 0, 100); // 500 Milliseconds
            dt.Tick += new EventHandler(dt_Tick);
            dt.Start();
        }
    }
}

I am setting the time zones using the DateTime methods and the rest is simply using the interface to set the time of the view. 

I hope this is of some use and hopefully of interest to you.

Cheers for now,

Andrew



.NET | C# | Silverlight
Wednesday, August 12, 2009 9:54:27 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer

I am currently deep into TDD with ASP.NET MVC and Moq as the mocking framework I have chosen.  I have been pondering on some valid methods in order to integrate both page index and also page size into the request. Page index and page size will be unique to each action for the purposes of this blog post and example.  I wanted to have the page index in the url, but the actual page size stored in session.  I have seen in some demonstration apps that the page size has been made constant inside the actual action and unfortunately I feel this is no good as a nice UI feature is being able to see more items per page of a list of items. 

So in the session I have put it and so I wanted to test this out and check that I am infact getting the expected results.  First off I made a simple contract for the paged data called IPagedModel and also an implementing base class called PagedModel:

    public interface IPagedModel
    {
        int TotalCount { get; }
        int TotalPages { get; }
        int PageIndex { get; }
        int PageSize { get; }
    }
    public class PagedModel : IPagedModel
    {
        private int _totalCount;
        private int _pageIndex;
        private int _pageSize;

        public PagedModel(int pageIndex, int pageSize, int totalCount)
        {
            _totalCount = totalCount;
            _pageIndex = pageIndex;
            _pageSize = pageSize;
        }

        #region IPagedModel Members

        public int TotalCount
        {
            get { return _totalCount; }
        }

        public int TotalPages
        {
            get { return (int)Math.Ceiling((decimal)_totalCount / (decimal)_pageSize); }
        }

        public int PageIndex
        {
            get { return _pageIndex; }
        }

        public int PageSize
        {
            get { return _pageSize; }
        }

        #endregion
    }

And the name of the test is this:

[TestMethod]
public void IndexAction_For_Space_1_Page_2_PageSize_2_Should_Have_PageIndex_1_PageSize_2_TotalCount_9()

I want to submit the required page number to the controller using a base 1 index and then using it inside the controller action using a zero based index. The method for the Index action which I will be testing expects an id for the object which it will be targeting but also a page number which is a nullable type in case it is not found inside the url and so will default to 0.  It is in this action where I am using the Session object to get the desired page size for the action. 

        public ActionResult Index(int id, int? pageIndex)
        {
            if (pageIndex == null)
                pageIndex = 0;

            if (pageIndex > 0)
                pageIndex = pageIndex - 1;

            int pageSize = Session["SpaceController!Index!PageSize"] == null ? 10 : Convert.ToInt32(Session["SpaceController!Index!PageSize"]);

            var space = _repository.GetSpace(id);
            if (space == null)
                return View("NotFound");

            long count;

            var forums = _repository.Get(space, pageIndex ?? 0, pageSize, out count);

            return View(new SpaceIndexViewModel(forums, pageIndex ?? 0, pageSize, (int)count));
        }

First thing is to check if the pageIndex is null and if so make it 0.  Next we want to make the conversion from a base 1 index to a base zero index which we will then use against the repository’s paging method, so basically if the page index is greater than 0, we want to minus 1 from it and use that.  We then check the session object for a valid pageSize for the action, specific to the controller.  From there on in I perform repository specific code and send the model onto the view.  To test this I want to be able to mock the controller context but also the session state and also I want to control the value return when a get on the session value "SpaceController!Index!PageSize" is made.  From looking at the Nerd Dinner application I have made a controller method to return me an instance on a controller, a test repository together with pre made test data I know and expect.  I have extended the method slightly so that I can supply both a username to indicate the HttpContext is authenticated but also session name value pairs.  I have used the Pair object for this but the NameValuePair would probably have been better.

        SpaceController CreateSpaceControllerAs(string userName, List<Pair> sessionValues)
        {
            var mock = new Mock<ControllerContext>();
            var mockSession = new Mock<HttpSessionStateBase>();
            mock.Setup(cts => cts.HttpContext.Session).Returns(mockSession.Object);
            mock.SetupGet(p => p.HttpContext.User.Identity.Name).Returns(userName);
            mock.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);

            foreach (Pair sessionValue in sessionValues)
            {
                mock.SetupGet(p => p.HttpContext.Session[sessionValue.First as string]).Returns(sessionValue.Second);
            }

            // Arrange
            var controller = CreateSpaceController();
            controller.ControllerContext = mock.Object;

            return controller;
        }

This tells the controller context to use the mock session object and also to use the supplied values for the expected get calls.  The actual test then consumes this builder method like so.

        [TestMethod]
        public void IndexAction_For_Space_1_Page_2_PageSize_2_Should_Have_PageIndex_1_PageSize_2_TotalCount_9()
        {
            var controller = CreateSpaceControllerAs(FakeForumData.FakeUser.UserName, new List<Pair>(new[]{
                 new Pair{
                      //Session Name
                      First = "SpaceController!Index!PageSize",
                      //Session Value
                      Second = 2
                 }
            }));
            // Act
            //Get first page
            ViewResult result = (ViewResult)controller.Index(1,2);

            IPagedModel model = (IPagedModel)result.ViewData.Model;

            // Assert
            Assert.AreEqual(1, model.PageIndex);
            Assert.AreEqual(2, model.PageSize);
            Assert.AreEqual(9, model.TotalCount);
        }

I am not saying I think this is the best method for storing varying page size personalization by the user, but it is something which has got me mocking the session state successfully so I am happy with that!  I hope this is of some use to others making their way though ASP.NET MVC!

Cheers

Andrew



.NET | ASP.NET MVC | C#
Monday, August 10, 2009 4:43:59 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer

I thought I would compose a short how to on programmatic web controls.  Often I have looked at the core set of controls within ASP.NET and wonder what design is required in order to get the design time mark up similar to that of the various controls.  The types of markup I am referring to includes:

  • Containers
  • Lists
  • Templates
  • Nested Controls of a certain type
  • Data bound controls
    • Only one example here, as I have wanted to do for ages and could not quite put my finger on how it was achieved.  Turns out, really simple lol

The following imports are used in these examples:

using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;

Simple Container Control

The first custom control structure I want to make is a custom panel.  Not inherited from a panel, although the same would be achieved but rather the simplest custom container. 

Desired Mark up

        <aebs:CustomPanel ID="Panel1" runat="server">
            Hell World
        </aebs:CustomPanel>
This is as simple as it gets.  This is a web control which persists any children controls or elements which you put in side.

    [ParseChildren(false)]
    [PersistChildren(true)]
    public class CustomPanel : WebControl
    {
        public CustomPanel()
        {
            //
            // TODO: Add constructor logic here
            //
        }
    }

A Control with an object list

This control is a web control but it has a list of an object, so you can add numerous types of the object to its collection.  The collection could be of a web control and if so it would be wise to inherit from a composite control as opposed to a web control.

Desired mark-up

        <aebs:ListControl1 ID="ListControl1" runat="server">
            <CustomObjects>
                <aebs:CustomObject CustomProperty="Hello World" />
                <aebs:CustomObject CustomProperty="Hello World 2" />
            </CustomObjects>
        </aebs:ListControl1>

So in design time you will see the intellisense prompt you for a tag called CustomObjects followed by nested prompts of a tag called Custom Object. 

image

    [ParseChildren(true)]
    [PersistChildren(false)]
    public class ListControl1 : WebControl
    {
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public List<CustomObject> CustomObjects { get; set; }

        public ListControl1()
        {
            //
            // TODO: Add constructor logic here
            //
        }
    }

The Custom object is nothing more than a class with a property. see here

    public class CustomObject
    {
        public string CustomProperty { get; set; }

        public CustomObject()
        {
            //
            // TODO: Add constructor logic here
            //
        }
    }

A Template Control

The mark up achieved with this type of control is like the type you see with for example the form view control which allows for:

  • Item Template
  • Insert Item Template
  • Edit Item Template

All I am doing is showing the mark-up required for the design time mark-up, so when using you will need to use the ITemplate InstantiateIn method providing a web control or html control as the container.

Desired mark-up

        <aebs:TemplateControl ID="TemplateControl1" runat="server">
            <HeaderTemplate>
                Hello Header World
            </HeaderTemplate>
            <ContentTemplate>
                Hello Content World
            </ContentTemplate>
            <FooterTemplate>
                Hello Footer World
            </FooterTemplate>
        </aebs:TemplateControl>

image

The code to achieve this is as follows.

    [ParseChildren(true)]
    [PersistChildren(false)]
    public class TemplateControl : WebControl
    {
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public ITemplate HeaderTemplate { get; set; }

        [PersistenceMode(PersistenceMode.InnerProperty)]
        public ITemplate ContentTemplate { get; set; }

        [PersistenceMode(PersistenceMode.InnerProperty)]
        public ITemplate FooterTemplate { get; set; }

        public TemplateControl()
        {
            //
            // TODO: Add constructor logic here
            //
        }
    }

You are going to want to control how each template is rendered but for the purposes of this example I am only showing the bare bones of how to achieve the mark-up.

A container control with specific object types as options

A good example of this type of control is when you use the object or sql data source control.  It allows you to specify parameters for the select, insert, update etc…  The options though which are provided to you are restricted so you can only choose parameter objects.  The key here is to specify a list property of the control with the type being a class other inherit from, not necessarily abstract.

Desired mark-up

        <aebs:ConstrainedCollection ID="Constrained1" runat="server">
            <AbstractProperties>
                <aebs:ConcreteOne />
                <aebs:ConcreteTwo />
            </AbstractProperties>
        </aebs:ConstrainedCollection>

image

The code to achieve this mark-up is as follows:

    [ParseChildren(true)]
    [PersistChildren(false)]
    public class ConstrainedCollection : WebControl
    {
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public List<AbstractClass1> AbstractProperties { get; set; }

        public ConstrainedCollection()
        {
            //
            // TODO: Add constructor logic here
            //
        }
    }

So you can see that the only difference between this and the list control example above is that I use a type for the list which is inherited by two other types being ConcreteOne and also ConcreteTwo.

A DataPanel

I have wanted to do this for a while but could not quite put my finger on how it was achieved.  Like I said up top, this turns out to be really simple.  The same could be achieved with an ObjectDataSource and a FormView but i want a light weight container which I could throw an object at and use Eval inside it.  I have many many uses for such a light weight singular object display.  Plus I also wondered how the use of Eval was achieved in Custom Controls, turns out that it is through the use the System.Web.UI.IDataItemContainer Interface.

Desired Mark-up

        <aebs:DataPanel ID="datapanel1" runat="server">
            <%# Eval("ProjectName") %>
        </aebs:DataPanel>

So I am not doing anything more than requesting a property of the object which I throw at the control.  Throwing the object at the control I do inside the Page_Load event just for demo.

    public void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataPanel.Project p = new DataPanel.Project();
            p.ProjectName = "Project 101";

            datapanel1.BoundObject = p;
            datapanel1.DataBind();
        }
    }

image

So the code to achieve this is just the simple container control above but this time I implement the interface.  For the purposes of demonstration I have also banged the class inside this type as nested too.

    [ParseChildren(false)]
    [PersistChildren(true)]
    public class DataPanel : WebControl, IDataItemContainer
    {
        public class Project
        {
            public string ProjectName { get; set; }
        }

        private object boundObject;

        public DataPanel()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public object BoundObject
        {
            set
            {
                boundObject = value;
            }
        }

        #region IDataItemContainer Members

        public object DataItem
        {
            get { return boundObject; }
        }

        public int DataItemIndex
        {
            get { return 0; }
        }

        public int DisplayIndex
        {
            get { return 0; }
        }

        #endregion
    }

Well I hope this is of some use to others,  I will try and update this post soon with examples of custom DataSource controls and also custom DataBound Controls.  When you start get into List Controls from a data source it gets real fun.

Cheers

Andrew



.NET | Architecture | ASP.NET | C#
Tuesday, March 17, 2009 5:47:28 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer

This morning I followed an Adobe Flex tutorial, well 3, about consuming Twitters restful API inside Flex.  After this it got me thinking about WCF and their Rest Starter Kit.  I looked and they are now up to Preview 2, so I downloaded it and in my spare time focused on this recently release white paper:

A Guide to Designing and Building RESTful Web Services with WCF 3.5

Installing the starter kit, which also installs some project templates, gives you a good starting point.  It also introduced me to some new concepts.  The starter kit actually generates a help page for your service which is an xml feed and XSLT Style Sheet e.g.

image

So It provides all the relevant information required i.e. the method, the uri template, the request and response schema.  I tested out a quick code up for the simplest form for consumption by C# and it worked out pretty well.  I focused on the fact that the info can be returned currently in two formats being XML and also JSON.  I wanted an abstract class to hold the URI’s for each method and also abstract methods which each derived object needs to override.

The idea is ultimately to have strongly typed helper methods for consuming restful apis.  So the tool, similar to the WSDL or SVCUTIL could be supplied with the following information:

  • namespace
  • language
  • url of help feed
  • asynchronous

What I would want to build on is the language part, as the interoperability of a rest api is huge.  If you make an implementation of the help generator in C# for example and use a Strategy pattern for the generation then this gives rise to the following:

  • C# Generation Strategy
  • VB.NET Generation Strategy
  • ActionScript Generation Strategy
  • C++ Generation Strategy
  • Pure JavaScript Generation Strategy
  • Jquery Generation Strategy (Yes I differentiated from the JavaScript option)
  • PHP Generation Strategy
  • Java Strategy
  • Python Strategy
  • Ruby on rails strategy

So you get the idea, it could be built then extended over time.  Am I getting ahead of myself here?  Is there one in production? WHO KNOWS? but it is fun never the less to jump in and have a go. 

So the quick Code Up I did is as follows:

Duplicate the type used in the REST Service and decorate with the namespace for XML Serialization needs

    [XmlRoot(Namespace="http://schemas.datacontract.org/2004/07/Swissmod.Service.Model")]
    public class Project
    {
        public string ID { get; set; }
        public string UserID { get; set; }
        public string ClientID { get; set; }
        public string ProjectTitle { get; set; }
        public string ProjectDescription { get; set; }
        public DateTime Created { get; set; }
        public DateTime LastModified { get; set; }
        public string Version { get; set; }

        public override string ToString()
        {
            StringBuilder sb1 = new StringBuilder();

            foreach (PropertyInfo pi in this.GetType().GetProperties())
            {
                sb1.AppendLine(pi.Name + " : " + pi.GetValue(this, null));
            }

            return sb1.ToString();
        }
    }

Define the abstract class for the Project Service

    public abstract class ProjectRestClient
    {
        protected string baseUrl = "http://test.@yoursite.com/ProjectService.svc/";

        public abstract Project GetProject(string id);
    }

Implement an XML Version of the Project Rest Client

    public class ProjectXmlRestClient : ProjectRestClient
    {
        public override Project GetProject(string id)
        {
            WebRequest wr = WebRequest.Create(baseUrl + id);
            wr.Method = "GET";
            wr.ContentType = "text/xml";
            WebResponse wresp = wr.GetResponse();
            XmlSerializer serializer = new XmlSerializer(typeof(Project));
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ValidationFlags = XmlSchemaValidationFlags.None;
            settings.ValidationType = ValidationType.None;
            settings.ConformanceLevel = ConformanceLevel.Auto;
            settings.IgnoreProcessingInstructions = true;
            settings.NameTable = new NameTable();
            settings.NameTable.Add("http://schemas.datacontract.org/2004/07/Swissmod.Service.Model");
            XmlReader reader = XmlReader.Create(wresp.GetResponseStream(),settings);
            Project p = (Project)serializer.Deserialize(reader);
            return p;
        }
    }

Implement a JSON Version of the Project Rest Client

    public class ProjectJsonRestClient : ProjectRestClient
    {
        public override Project GetProject(string id)
        {
            WebRequest wr = WebRequest.Create(baseUrl + id + "?format=json");
            wr.Method = "GET";
            WebResponse wresp = wr.GetResponse();
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Project));
            Project p = (Project)serializer.ReadObject(wresp.GetResponseStream());
            return p;
        }
    }

Give it a whirl

At this point I know what is going to happen, but I am just protyping to give myself ideas for when I come to make a generation tool for the actual complete feed.  IF I CAN OFCOURSE! lol :-)

    public static class Program
    {
        const string XML = "XML";
        const string JSON = "JSON";

        [STAThread]
        public static void Main(string[] args)
        {
            IUnityContainer container = new UnityContainer();
            container.RegisterType<ProjectRestClient, ProjectXmlRestClient>(XML, new ContainerControlledLifetimeManager());
            container.RegisterType<ProjectRestClient, ProjectJsonRestClient>(JSON, new ContainerControlledLifetimeManager());

            ProjectRestClient xmlCient = container.Resolve<ProjectRestClient>(XML);
            ProjectRestClient jsonCient = container.Resolve<ProjectRestClient>(JSON);

            Console.WriteLine(xmlCient.GetProject("1"));
            Console.WriteLine(jsonCient.GetProject("1"));

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }

P.S. I have used unity here for a few reasons but mainly because I love the idea of Inversion of Control and Dependency Injections.  The above simply allows me to obtain a singleton instance of either class whenever I want to execute a service method.

image

So to summarise, the only reason I am doing this is so that the consumption of the Rest service is strongly typed, I am not doing this because I think it is a necessity, simply because I think it would be extremely helpful for me.  The ability to strongly type things gives me much more happiness when working across language barriers.

Anyways,

Cheers for now,

Andrew



.NET | ASP.NET | C# | WCF
Tuesday, March 17, 2009 4:42:57 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer

I was looking for a simple way of comparing two byte arrays and it is not as 123 as you may think as methods which you may assume would return true, DO NOT.  I found a solution that does exactly what I need and is part of the framework, and I found it on the link below.  It also contains examples at the beginning which may surprise you:

http://blog.tatham.oddie.com.au/2008/07/01/comparing-byte-arrays-in-c-or-at-least-trying-to/

To summarize the method I am speaking of is the following:

public static bool SequenceEqual<TSource>(this System.Collections.Generic.IEnumerable<TSource> first, System.Collections.Generic.IEnumerable<TSource> second)
    Member of System.Linq.Enumerable

Summary:
Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.

And it was from a comment may by a guy calling himself RichB in the blog post above.  Great find!

Cheers,

Andrew



.NET | C#
Friday, February 20, 2009 11:17:10 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer

Ok, so there is no doubt that it is difficult to become a software architect and extremely difficult to become a good one.  I read people talking about experience is key, but what about the experience gathered. 

I am developing all the time, and I would class my self as a CAN DO developer who is improving each job that comes.  My issue is my inquisitiveness, in that I might have done something once before, but then I think:

“Hmm ok, but if I do it this way, or If I use this pattern or this method or this technology it will be better | it will be faster OR it will be quite cool to try even if I am unsure of the outcome!”

I have found it extremely stressful, rewarding, tiresome and fulfilling to work for myself, but in the process I have come across so many different ways to, well, SKIN A CAT.  Lets think about Object Relational Mappings ORM, now when you get to this juncture what do you choose:

  1. Create your own, writing it by hand.
    1. Well this sounds fun, but unless you are planning on working with a small data store you have quite a task ahead of you. 
  2. Create a dynamic one through reflection
    1. This is one approach recommended by the Patterns of Enterprise Architecture By Martin Fowler
  3. Create a Code Generation Policy.
    1. Now if you combine the following then you will both learn and have an extremely useful tool in which to create your ORM for present and future projects.:
      1. Point 1 above
      2. A code generation tool e.g. Code Smith
      3. Some time to learn the syntax of the Code Generator
  4. Using a Sub Framework for the ORM e.g. NHibernate, NetTiers, CLSA etc…
    1. Again you would combine this point with a code generator, or you could create by hand.  Would get tedious and prone to human error though
  5. Use ADO.NET
    1. Another option which is recommended by Martin Fowler.  ADO.NET is an extremely powerful way to work with Disconnected Data.
  6. Use LINQ to SQL
    1. Great tool, although I have read that its future is uncertain and the focus will be directed on the ADO.NET Entity Framework.  I love the delayed execution and also the PIPES and FILTERS pattern.
  7. Use the ADO.NET Entity Framework
    1. From my initial exposure, I have found this to be quite amazing.  My first exposure to it has been coupled with ASP.NET Dynamic Data.

So off the top of my head there are 7 points which can also me combined in some cases and these will handle how you communicate to your Data store, quite commonly a database.  BUT WHICH TO USE.   From a risk assessment standpoint, I think it obvious to say that 5, 6 and 7 are the least risk, as in they are tried and tested frameworks from Microsoft themselves with powerful wizards and very little setup and do not require that high a level of knowledge of programming to start using.  Using 4 and 3 together come in next with 1 and 2 bringing the most risk, BUT if you choose 1 or 2 combined with 3 then of course you have the ability to build a complete tailored approach to your Domain Model or SOA.  I am not sure if risk is the correct word, may be complexity and the requirement of experience.  I think that is a better point.

Another point is Test Driven Development.  Purists would say that you should write a test before you create the object which you want to test.  I am find with this, but what if the underlying technology you are getting into is new and you are still un aware of its capabilities.  What do you test, I would need to write some code to see its functionality first and then see where I am at with it.  Once I have an idea of what I can do, then I will then know what to test, so definitely a research stage when pursuing the bleeding edge.

I would love to find out about testing TSQL, as ,my work leads down that route often and sometimes I get stuck with a problem which requires a query that to me, is a head ache.  Ok I want everything from table A and even if it does not exists in Table B with a sub query for the conditional count yada yada yada which involves 5+ tables with complex query parameters.  Then you have the Stored procedures, the scalar, table functions, views, indexes etc…. 

I think my point with this post is the level of learning that you can get drawn into when you dig deep enough, I feel it is like you get to the edge of a cliff, and you are peering over, then all of a sudden WHOOSH, you get blown off the edge and you are surrounded with hoards of material, tutorials, reviews, white papers, books, videos, Do’s, Don’ts, Design, Discussions, Difference of opinions etc….

One thing that is always in the back of my head at the minute is I read a quote from Bjarne Strousup where he says he teaches you how to program and as a by product you learn the language.  I love this quote as it tells me that I can now apply my programming in other languages, and guess what I DO!  What a rant! Right I am signing off.  I found the following image which I thought was extremely good!

 

lightweight-system

SOURCE: http://niksilver.com/

Cheers,

Andrew


Thursday, February 12, 2009 12:43:43 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer