Null !== Steve

Steve Gentile's Tech Blog – Thoughts and Musings

Archive for the category “Uncategorized”

KnockoutJS ‘Addons’, etc…

This is not intended to be a full post – just wanted to highlight a few links to add ons to the javascript knockoutjs library I’ve been using on some recent projects:

Observable Dictionary :  github source  gist of example

Protected Observable: blog post with sample code  gist of example

KO ‘Datagrid’ : link to google group post  github source  samples

I’ll update this with more links – it would be great to have a knockoutjs community

Steve Michelotti has a KnockoutJs course of Pluralsight and an example of building a custom binding

Also just to add – I have an example of KnockoutJS with NodeJs on my github here with a few simple tests using jasmine-node for some specs, and QUnit showing some Knockoutjs test scenarios.

JavaScript Todos–Backbone with asp.net mvc

There are certainly plenty of articles, examples, etc… around creating the ‘Todos’ sample.  To learn more about different frameworks and a more complete example, check out Addy Osmani‘s examples here: http://addyosmani.github.com/todomvc/   This is a fantastic resource to learn about different available frameworks.

Most of these examples tend to use the localStorage.  Not that it’s a big deal, but I wanted to put together something very very simple that showed some connections between using Backbone.js to make calls to a backend server.  In this case, I have decided to use asp.net mvc.

The example uses IISExpress to be hosted.  To reduce some of the friction, there is no database, just a static List object on the server.  I am not handling edits in this simple example – just a GET call to show todos and POST call to add a new todo.

To get an example – you can get it on github https://github.com/sgentile/MvcBackbone

First, this is not a ‘how to use backbone’ nor a ‘how to use asp.net mvc’ – I’d probably fail you on both subject matters!  The goal here is to highlight the aspects of backbone that help in making the connection to the backend server.  Backbone is providing an abstraction over the ajax calls.  You certainly CAN use ajax directly if you want. 

So, let’s get started.   The ‘todo’ model is quite simple – see todo.js line 5 :

Todo = Backbone.Model.extend({
    // Default attributes for the todo.
    defaults: {
      content: "empty todo..."
    },
        // Ensure that each todo created has `content`.
    initialize: function() {
      if (!this.get("content")) {
        this.set({"content": this.defaults.content});
      }
    },
    
    url: "home/todos"
});

If you check the backbone.js document for Model url http://documentcloud.github.com/backbone/#Model-url

Returns the relative URL where the model’s resource would be located on the server. If your models are located somewhere else, override this method with the correct logic. Generates URLs of the form: "/[collection.url]/[id]", falling back to "/[urlRoot]/id" if the model is not part of a collection.

The key here is to let backbone know the url for Todos.  We will be making a ‘save’ call on our Todo model object when we add a new model  ( save: http://documentcloud.github.com/backbone/#Model-save ).  This will look for the url on the server:

the save will be a "create" (HTTP POST), if the model already exists on the server, the save will be an "update" (HTTP PUT).

 

The TodoFormView on line 38, handles connecting the forum submit call to our save function, which maps the form to the Todo model.  Calling ‘save’ directly on the model results in an ajax call – ie:

TodoFormView = Backbone.View.extend({
    initialize: function () {
        this.template = $("#formTemplate");
    },
    events: {
        "submit #todo-form": "save"
    },
    render: function () {
        var content = this.template.tmpl();
        $(this.el).html(content);
        return this;
    },
    save: function () {
        var val = this.$("input").val();
        var model = new Todo({ content: val });
        model.save();
        this.$("input").val('');
    }
});

The key items to see here is the save function call  – where we save the model – model.save();

So the ‘home/todos’ matches up to the HomeController Todos action – with is a new Todo, so therefore it cooresponds to the following:

        [HttpPost]
        public ActionResult Todos(Todo todo)
        {
            todo.id = Guid.NewGuid();
            TodoList.Add(todo);
            return Json(TodoList, JsonRequestBehavior.AllowGet);
        }

As you see, backbone is handling the underlying ajax POST calls to the server!

Obviously GET calls are equally as straightforward.  I have a collection of Todos defined:

Todos = Backbone.Collection.extend({
    model: Todo,
    url: "home/todos"
});

I am able to do a GET call with ‘fetch’ as seen below:

TodoListView = Backbone.View.extend({
    initialize: function () {
        _.bindAll(this, "render");
        this.collection.bind("change", this.render);
        this.collection.bind("add", this.render);
        this.collection.bind("fetch", this.render);

        todos.fetch({ add: true });
        
    },
    render: function () {
        //clear out the existing list to avoid "append" duplication
        $(this.el).empty();
        //use an array here rather than firehosing the DOM
        //perf is a bit better
        var els = [];
        //loop the collection...
        this.collection.models.forEach(function (todo) {
            //rendering a view for each model in the collection
            var view = new TodoItemView({ model: todo });
            //adding it to our array
            els.push(view.render().el);
        });
        //push that array into this View's "el"
        $(this.el).append(els);
        return this;
    }
});

The key here is the todos.fetch call.  You can learn more about collections and fetch here: http://documentcloud.github.com/backbone/#Collection-fetch

This is all for now, should be a good start – there is much to learn here obviously (ie bootstrapping). 

Next time, I hope to share more about using backbone with asp.net mvc and then add jquery mobile to the mix.  Thanks!

JavaScript: Revealing Module Pattern and Namespacing

This is a basic post regarding namespacing and revealing module pattern.  When starting a new JavaScript application it’s important to have a good starting foundation.  First let’s show how to use namespacing in JavaScript:

window._ns = window._ns || {};

_ns is attached to the global window object.  Alex MacCaw in his book ‘’JavaScript Web Applications’ describes this well:

We’re setting on the window object to ensure that it’s globally accessible.

Also, by using this pattern, it’s easy to see which global variables a script is declaring,

just look through the script for window references

Let’s show this in use, first using what is referred to as the singleton pattern:

_ns.Singleton = {
    _somethingConsideredPrivate: function () {
        document.write("Singleton doSomething complete<br/>");
    },
    doSomething: function () {
        this._somethingConsideredPrivate();
    }
};

 

_ns.Singleton.doSomething();   //note, everything is public – some use an underscore : _privateFunction : function … to denote private, but it’s still accessible

<html>
<head>
    <title>Module</title>
    
    <script src="/Scripts/Module.js" type="text/javascript"></script>
</head>
<body>
    <div>
        <script>
            _ns.Singleton.doSomething();
        </script>
    </div>
</body>
</html>

But what if we want to use the revealing module pattern which gives us the concept of private and public ?

basically we return what is public.

_ns.RevealingModule = function () {
    var privateData = {
        message: "RevealingModule doSomething complete"
    };

    var privateFunction = function () {
        document.write(privateData.message);
    };

    var doSomething = function () {
        privateFunction();
    };

    return {
        //since returned - it's public:
        doSomething: doSomething
    };

} ();   //end of module

 

It’s usage pattern as follows:

<!DOCTYPE html>

<html>
<head>
    <title>Module</title>
    
    <script src="/Scripts/Module.js" type="text/javascript"></script>
</head>
<body>
    <div>
        <script>
            _ns.Singleton.doSomething();
            _ns.RevealingModule.doSomething();
        </script>
    </div>

</body>
</html>

If you try to access the private function – it would fail:

 

_ns.RevealingModule.privateFunction();

would result in:

_ns.RevealingModule.privateFunction is not a function
[Break On This Error] _ns.RevealingModule.privateFunction(); 

I hope this helps clarifying namespacing and the revealing module pattern.  There are certainly some great resources to describe both. 

Recommended reading followup: http://www.klauskomenda.com/code/javascript-programming-patterns

Alex MacCaw’s book ‘JavaScript Web Applications’: http://shop.oreilly.com/product/0636920018421.do

‘Restoring’ Git after Upgrade to OSX Lion

I was surprised to find out my ‘git’ command didn’t work after upgrading to Lion.

It is still there (verify by checking for this directory: /usr/local/git/bin), just needs to be mapped.

I was able to find out that the git installer uses paths.d to add it to the path.

I went to /etc/paths.d and did ls  – but there was not git file.

open Terminal

cd /etc/paths/d

sudo vi git

enter /usr/local/git/bin at the top of the file (if new to vim, hit ‘I’ to enter ‘insert mode’)

hit escape – type :wq to save and quit

open new terminal – run ‘which git’

Should work now

Html5 & Silverlight– an opinionated post–‘what if’

Yes, it wouldn’t be in my character to hold off on yet another opinionated post!  Smile

Let me reference Davy Brion’s post on ‘why were going with html5 instead of silverlight’.  To break this down, what I see and continue to see is are the pros – the development environment, use of a single language (although minor I do see two here, we have XAML and C# – in same manner as Html + Javascript).  And yet the usability is down, it’s not as accessible, it’s a plug-in, etc…

And while I’m on this topic, I’d venture to say I believe the same solution I’m going to propose would be good for Adobe’s Flash/Flex applications as well.

I think the biggest concern I have isn’t whether ‘Linux’ can run Silverlight (we have Moonlight), it’s more along the lines of ‘any device anywhere’.  Let’s take the iPad or Xoom – these new devices, that I predict will continue to infiltrate businesses as they have consumers – will lead us to requests such as ‘why can’t I view this Silverlight webpart in my internal Sharepoint site that was done in Silverlight’.

There have been two tools that I know of, that in my opinion solve a big chunk of the plugin issue:  Google Web Toolkit (GWT) – and Script#.  Now, Script# was supposedly used on Microsoft’s Office on the web, but it’s currently done by one person and it’s not really supported, and it’s usage has some issues imo because of this.  So, for now I’ll just look at the model Google has provided with GWT.

GWT provides a common environment – a plugin in Eclipse – where you write java code.  There is an API to handle common dom tasks.  Similar to Silverlight, you typically would have asynchronous calls back to the server code through the GWT API.   Any client side behaviors are output as  javascript – in a best practice format.  The javascript is compressed.  The output uses compression and is minified.  In addition it created compiled javascript through Google javascript’s compiler.  That all said, I know there are issues with GWT, and my concern would be the flexibility of it, but I consider it the best conceptual solution to creating html/javascript using a single language.

So – that is my scenario – we have Silverlight that is producing a plugin that can’t run anywhere.  It can’t run on iPhone, iPad, Xoom, it can’t run on different systems.  It’s a ‘foreign entity’ in that it doesn’t comply with html standards and usability – that all said – the development environment of Silverlight is great – top of the line really – as your writing C# code and using a very flexible XAML.

My solution would be for Microsoft to shift how Silverlight is outputted.  I think the environment is good – the Blend, Silverlight, etc… dev experience is good.   My proposal would be to provide an option that the underlying Silverlight code OUTPUT generates compliant HTML5 source, compiled, compressed and minified javascript and CSS3.  So you would select your output – ‘XAP’, ‘HTML5’, ‘Mobile HTML5’, etc… and then thethe tooling would handle conversion of the events, elements, etc… in the XAML/code behind ie.  A XAML ‘storyboard/animation’ would be equated to a series of javascript animations – ie. jQuery animations.  XAML controls would output the corresponding html5 controls.  Binding would implement the html4 data binding, etc… I know this is no small task – but the benefit is huge.  Move forward a few steps, and we would have targeting capability – ‘create a HTML5 mobile equivalent’ for example. 

I think Script# was starting to take this path, it has the core fundamentals.  But just not the support it needed.  I’m not sure why Nikhil didn’t open source is at the very least.  Perhaps because Microsoft will eventually take it and use it – not sure.  It did provide what I would considering a R&D into the capabilities of taking C# to Javascript.

I want to say I’m not someone that thinks we need to hide away javascript.  I’m not necessarily looking at it that way.  I’m looking at the developers who are attached to and have been sold on all the benefits of Silverlight.  I’ve worked with Silverlight as well.  I like the client side architecture of it.  I liked working with XAML, etc… and see a ton of flexibility there.  Not that this is a big deal, but I see it as a ‘gateway’ for WPF developers to also be able to use those same skills to write to something that outputs html5.

It’s ironic, and I’m going to take note of this – the webforms model was an attempt to abstract away the web.  And it’s abstraction in many ways became a hinderance.  Doing simple formating requires knowing all these custom controls – how to bind and postback on a GridView for instance.  And what I’m proposing is even more of an abstraction. 

I truthfully would rather just see better tooling from Microsoft on HTML5/CSS and javascript – and to stop treating javascript like the redheaded stepchild. 

That all said, I see potential in Microsoft leveraging the development model of Silverlight to produce what Google has accomplished with the GWT.  So I would take that toolset and provide those capabilities.  Seemlessly to the point of being able to do things such as ‘creating a silverlight webpart that produces compliant html5’, etc…

I see value in several different directions for Silverlight – the embedded – with wp7, etc…, the out of browser ‘app’ model – where I think it makes the most sense for a future Microsoft AppStore – because these apps are well sandboxed, and then this final option of an HTML5/CSS3/Javascript output.

What do you think?

Html5 & Silverlight– an opinionated post–‘what if’

Yes, it wouldn’t be in my character to hold off on yet another opinionated post!  Smile

Let me reference Davy Brion’s post on ‘why were going with html5 instead of silverlight’.  To break this down, what I see and continue to see is are the pros – the development environment, use of a single language (although minor I do see two here, we have XAML and C# – in same manner as Html + Javascript).  And yet the usability is down, it’s not as accessible, it’s a plug-in, etc…

And while I’m on this topic, I’d venture to say I believe the same solution I’m going to propose would be good for Adobe’s Flash/Flex applications as well.

I think the biggest concern I have isn’t whether ‘Linux’ can run Silverlight (we have Moonlight), it’s more along the lines of ‘any device anywhere’.  Let’s take the iPad or Xoom – these new devices, that I predict will continue to infiltrate businesses as they have consumers – will lead us to requests such as ‘why can’t I view this Silverlight webpart in my internal Sharepoint site that was done in Silverlight’.

There have been two tools that I know of, that in my opinion solve a big chunk of the plugin issue:  Google Web Toolkit (GWT) – and Script#.  Now, Script# was supposedly used on Microsoft’s Office on the web, but it’s currently done by one person and it’s not really supported, and it’s usage has some issues imo because of this.  So, for now I’ll just look at the model Google has provided with GWT.

GWT provides a common environment – a plugin in Eclipse – where you write java code.  There is an API to handle common dom tasks.  Similar to Silverlight, you typically would have asynchronous calls back to the server code through the GWT API.   Any client side behaviors are output as  javascript – in a best practice format.  The javascript is compressed.  The output uses compression and is minified.  In addition it created compiled javascript through Google javascript’s compiler.  That all said, I know there are issues with GWT, and my concern would be the flexibility of it, but I consider it the best conceptual solution to creating html/javascript using a single language.

So – that is my scenario – we have Silverlight that is producing a plugin that can’t run anywhere.  It can’t run on iPhone, iPad, Xoom, it can’t run on different systems.  It’s a ‘foreign entity’ in that it doesn’t comply with html standards and usability – that all said – the development environment of Silverlight is great – top of the line really – as your writing C# code and using a very flexible XAML.

My solution would be for Microsoft to shift how Silverlight is outputted.  I think the environment is good – the Blend, Silverlight, etc… dev experience is good.   My proposal would be to provide an option that the underlying Silverlight code OUTPUT generates compliant HTML5 source, compiled, compressed and minified javascript and CSS3.  So you would select your output – ‘XAP’, ‘HTML5’, ‘Mobile HTML5’, etc… and then thethe tooling would handle conversion of the events, elements, etc… in the XAML/code behind ie.  A XAML ‘storyboard/animation’ would be equated to a series of javascript animations – ie. jQuery animations.  XAML controls would output the corresponding html5 controls.  Binding would implement the html4 data binding, etc… I know this is no small task – but the benefit is huge.  Move forward a few steps, and we would have targeting capability – ‘create a HTML5 mobile equivalent’ for example. 

I think Script# was starting to take this path, it has the core fundamentals.  But just not the support it needed.  I’m not sure why Nikhil didn’t open source is at the very least.  Perhaps because Microsoft will eventually take it and use it – not sure.  It did provide what I would considering a R&D into the capabilities of taking C# to Javascript.

I want to say I’m not someone that thinks we need to hide away javascript.  I’m not necessarily looking at it that way.  I’m looking at the developers who are attached to and have been sold on all the benefits of Silverlight.  I’ve worked with Silverlight as well.  I like the client side architecture of it.  I liked working with XAML, etc… and see a ton of flexibility there.  Not that this is a big deal, but I see it as a ‘gateway’ for WPF developers to also be able to use those same skills to write to something that outputs html5.

It’s ironic, and I’m going to take note of this – the webforms model was an attempt to abstract away the web.  And it’s abstraction in many ways became a hinderance.  Doing simple formating requires knowing all these custom controls – how to bind and postback on a GridView for instance.  And what I’m proposing is even more of an abstraction. 

I truthfully would rather just see better tooling from Microsoft on HTML5/CSS and javascript – and to stop treating javascript like the redheaded stepchild. 

That all said, I see potential in Microsoft leveraging the development model of Silverlight to produce what Google has accomplished with the GWT.  So I would take that toolset and provide those capabilities.  Seemlessly to the point of being able to do things such as ‘creating a silverlight webpart that produces compliant html5’, etc…

I see value in several different directions for Silverlight – the embedded – with wp7, etc…, the out of browser ‘app’ model – where I think it makes the most sense for a future Microsoft AppStore – because these apps are well sandboxed, and then this final option of an HTML5/CSS3/Javascript output.

What do you think?

WCF RESTFul Service with Entity Framework CodeFirst

I’m going to try to kill two birds with one stone in my post today.  My first goal was to setup a WCF RESTful service – but spice it up a bit to show off some Entity Framework CodeFirst goodness at the same time.

This isn’t some sort of ‘best practices’ post – more of a quick (hopefully) and dirty sample walkthrough for anyone interested in doing this as well.

This sample will be done with Visual Studio 2010, .NET framework 4.0.

The first step is to setup a WCF REST Service Application.  I used, what I think, is an out of the box C# template, under ‘Web’:

image

I used the default name it provided (‘WcfRestService1’).

The default template will create some boilerplate code for us.  I recommend as well to goto the project settings for the service and set the port to be 2023. 

The WCF RESTFul service provides an operations help page to view the available endpoints:

http://localhost:2023/Service1/help

image

Clicking on the method ‘GET’ and/or ‘POST’ will highlight the services available.  You might see more than these two items at this time.  But first I’m going to make some changes and introduce Entity Framework Code-First.

Let’s go ahead and get our Code-First setup before we refactor the service.  Assuming you have Nuget installed (if not, go get it!), inside the Package Manager Console you can easily install Code-First.  Type into the console the following:  Install-Package EFCodeFirst.

As of this writing I’m using version 0.8.  You should see something similar to the following:

 

PM> Install-Package EFCodeFirst
Successfully installed 'EFCodeFirst 0.8'.
Successfully added 'EFCodeFirst 0.8' to WcfRestService1.

Great – we now have EFCodeFirst, it will add some assemblies to the mix. 

The default WCF RESTful template included a class ‘SampleItem’, so we will use that – it takes advantage of the Code-First convention over configuration by providing an ‘Id’ field – so it makes like easy for us.  If you don’t’ it, the class looks like the following:

public class SampleItem
    {
        public int Id { get; set; }
        public string StringValue { get; set; }
    }

[ServiceContract]
    public interface IService1
    {
        [WebGet(UriTemplate = "")]
        List<SampleItem> GetCollection();

        [WebGet(UriTemplate = "{id}")]
        SampleItem Get(string id);

        [WebInvoke(UriTemplate = "", Method = "POST")]
        SampleItem Create(SampleItem instance);

        [WebInvoke(UriTemplate = "{id}", Method = "PUT")]
        SampleItem Update(string id, SampleItem instance);

        [WebInvoke(UriTemplate = "{id}", Method = "DELETE")]
        void Delete(string id);
    }

[ServiceContract]
    public interface IService1
    {
        [WebGet(UriTemplate = "")]
        List<SampleItem> GetCollection();

        [WebGet(UriTemplate = "{id}")]
        SampleItem Get(string id);

        [WebInvoke(UriTemplate = "", Method = "POST")]
        SampleItem Create(SampleItem instance);

        [WebInvoke(UriTemplate = "{id}", Method = "PUT")]
        SampleItem Update(string id, SampleItem instance);

        [WebInvoke(UriTemplate = "{id}", Method = "DELETE")]
        void Delete(string id);
    }

[ServiceContract]
    public interface IService1
    {
        [WebGet(UriTemplate = "")]
        List<SampleItem> GetCollection();

        [WebInvoke(UriTemplate = "", Method = "POST")]
        SampleItem Create(SampleItem instance);
    }

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class Service1 : IService1
    {

        public List<SampleItem> GetCollection()
        {
            using (ItemContext context = new ItemContext())
            {
                return context.SampleItems.ToList();
            }
        }

        public SampleItem Create(SampleItem instance)
        {
            using (ItemContext context = new ItemContext())
            {
                context.SampleItems.Add(instance);
                context.SaveChanges();
            }
            return instance;
        }

        public SampleItem Get(string id)
        {
            using (ItemContext context = new ItemContext())
            {
                var item =
               (from c in context.SampleItems
                where c.Id == Int32.Parse(id)
                select c).FirstOrDefault();

                if (item == null)
                {
                    throw new WebFaultException(HttpStatusCode.NotFound);
                }

                return item;
            }
        }

        public SampleItem Update(string id, SampleItem instance)
        {
            using (ItemContext context = new ItemContext())
            {
                 SampleItem sampleItem =(from c in context.SampleItems
                 where c.Id == Int32.Parse(id)
                 select c).FirstOrDefault();
                sampleItem = instance;
                context.SaveChanges();
                return sampleItem;
            }
        }

        public void Delete(string id)
        {
            using (ItemContext context = new ItemContext())
            {
                SampleItem sampleItem = (from c in context.SampleItems
                                         where c.Id == Int32.Parse(id)
                                         select c).FirstOrDefault();
                context.SampleItems.Remove(sampleItem);
                context.SaveChanges();
            }
        }
    }

Just a quick overview here – we can use Linq style queries to handle all our query needs.  You can see from the GetCollection call above that the context exposes the SampleItems DbSet that is queryable. 

I added one piece to the above that is a nicety of working with REST.  I made a decision to throw a ‘404’ not found exception on the Get call.  If a value is passed in that is not valid, it should show a 404 response back.

ie.

throw new WebFaultException(HttpStatusCode.NotFound);

I hope this provides some insight into use the WCF RESTful services along with EF Code First.

KISS : WCF ServiceHost and ClientBase

This is meant to be a very simple overview of the servicehost creation in code and a clientbase creation in code.  And to help clarify how both use the configuration (it could be programmatic) ties into them.

Let’s take for instance that we have a very simple service.

[ServiceContract]
public interface IService
{
    [OperationContract(AsyncPattern=true, Action=*”)]
    IAsyncResult BeingResponse(Message message, AsyncCallback callback, object state);

    Message EndResponse(IAsyncResult result);
}

and an implementation of the service:

public class MyService : IService
{
    public IAsyncResult BeginResponse(Message message, AsyncCallback callback, object state)
    {
         return new CompletedAsyncResult(message);
    }

    public Message EndResponse(IAsyncResult r)
    {
        CompletedAsyncResult<Message> result = r
            as CompletedAsyncResult<Message>;
        return result.Data
    }
}

 

// Simple async result implementation.
  class CompletedAsyncResult<T> : IAsyncResult
  {
    T data;

    public CompletedAsyncResult(T data)
    { this.data = data; }

    public T Data
    { get { return data; } }

    #region IAsyncResult Members
    public object AsyncState
    { get { return (object)data; } }

    public WaitHandle AsyncWaitHandle
    { get { throw new Exception("The method or operation is not implemented."); } }

    public bool CompletedSynchronously
    { get { return true; } }

    public bool IsCompleted
    { get { return true; } }
    #endregion
  }

This is the service side.  Now, we want to go update our app.config (in this case, I’m running this in my test, so create or use existing config in your test project).  The endpoint is the key here, and commonly referred to as the ABC’s of WCF  (Address, Binding, Contract).

<system.serviceModel>
    <services>
        <service name="MyService">
            <endpoint
                name="MyService"
                address="net.tcp://localhost:4400/MyService"
                binding="netTcpBinding"
                contract="IService"
            />
        </service>
    </services>
    <bindings>
        <netTcpBinding>
            <binding name="netTcpBinding"
        </netTcpBinding>
    </bindings>
</system.serviceModel>

The service host will look to the service configuration file to find the setup for our IService contract and see that MyService is an implementation and use those settings.

 

So now let’s create a client to call into our service.  This can be done with a ChannelFactory, or a ClientBase.  For this example we’ll just use a ClientBase:

public class MyServiceClient : ClientBase<IService>, IService
{
    public IAsyncResult BeginResponse(Message message, AsyncCallback callback, object state)
    {
        IAsyncResult result = Channel.BeginResponse(message, callback, state);
        return result;
    }

    public Message EndResponse(IAsyncResult result)
    {
        return Channel.EndResponse(result);
    }
}

Pretty simple really, we implement the interface of our service contract and use the ClientBase.  The ClientBase handles the Channel.

Now let’s look at the configuration – since our example we will be hosting the service and client in same project, we can add the client configuration parts:

...
    <client>
        <endpoint
            name="MyService"
            address="net.tcp://localhost:4400/MyService"
            binding="netTcpBinding"
            contract="MyService"
        />
    </client>
</system.serviceModel>

ok, so returning to finish our test:

[TestMethod]
public void TestServiceWithClient()
{
    ServiceHost host = new ServiceHost(typeof(MyService));
    host.Open();

    Message message = Message.CreateMessage(MessageVersion.Default, "*", "Test Message");

    MyServiceClient proxy = new MyServiceClient();

    //just use inline callback...
    AsyncCallback completion = (result) =>
    {
        Message msg = proxy.EndResponse(result);
        Assert.AreEqual("Test Message", msg.GetBody<string>());
        proxy.Close();
    }

    proxy.Open();
    proxy.BeginResponse(message, completion, null);
    host.Close();
}

So there is an end to end self-hosted wcf service example.

Kata–Greed Kata

While at Codemash this year, I was introduced to ‘katas’.  It’s a great idea really – where you are given a problem to solve and you work through it using whatever language and technique you want.   Take a look at Ryan Cromwell’s post ‘The Purpose of Katas’ to learn more.

So, actually I went with Ryan to Codemash and instead of just going to a session the entire day, there were opportunities to try some new stuff.  Ryan and I took a session off, desiring to do some coding, and went to the Codemash ‘Coding Dojo’ where you could pair up or even solve the kata alone. 

I will admit, I was a bit bewildered, as I really didn’t quite get it at first, as I really didn’t know what a kata was!  I ended up closing my lid of my laptop and leaned over to watch the process Ryan was doing.   For experienced kata developers in the dojo, they were off and running and pounding out the code in the allotted 30 minute timeframe.  Honestly, I spent my whole time trying to figure out what the kata meant!

When I got home from Codemash, one of my goals was to work through some kata’s to gain some experience and not be such a newbie.  My first week home I went through the bowling kata, following along with Uncle Bob (Bob Martin) – I highly suggest following along his powerpoint presentation : http://butunclebob.com/ArticleS.UncleBob.TheBowlingGameKata (check out this as well – adapted for C# 4 : http://www.slideshare.net/stewshack/bowling-game-kata-c ).  I went through this kata several times, attempting to grasp the flow and technique.  I don’t think kata’s are just meant to blindly work through and instead, start to develop an eye for when to refactor, how to use TDD, spotting patterns (ie. http://cleancoder.posterous.com/the-transformation-priority-premise) etc…  You don’t ‘have’ to use TDD to do a kata, but honestly, I am going to say that it would really defeat the purpose not too!

Ok, so all that aside, today I decided to re-try the Greed kata.   This time around, I didn’t want to follow along with any guide, just to try to solve it myself.  What I’m going to show is my ‘final product’ – although I think I need to figure out a way to do as Bob Martin did and go through my thought process – as this final product was not how I started.  I went through many iterations and steps (and although I can barely follow that link about transformation priority- I will say I think I saw that action – lol!).  I learned a few things going through this such as the TestCase concept – which I saw used at Codemash and thought was a clever way to test sets of data.   I am open to any feedback on my solution, as I don’t really like my ‘switch…case’ solution – so I will be looking to refine this the next time I run through the kata.   Kata’s are meant to be repeated over and over again.

Greed Kata

Greed is a simple dice game in which players roll a number of dice and determine their score based on combinations of dice rolled.  In an actual game, players would be allowed to re-roll unused dice until they arrived at their final score for one of their turns, and a game might be played up to a certain point total.  The game can be played with different numbers of dice.
For the purposes of this kata, the game will use 5 dice and will not allow any re-rolls.  A Game class with a Score method will return the player’s score for a given roll of the dice.  The following scoring rules will be used:

•    A set of 3 1’s [1,1,1] is worth 1000 points
•    A set of 3 of any other number is worth 100 * that number (e.g. [2,2,2] is worth 200 points)
•    A single 1 is worth 100 points
•    A single 5 is worth 50 points
•    Any other die or combination is worth 0 points

Requirements

•    Write a class named “Game” that has a public Score() method accepting a collection of dice values.
•    Implement the rules above however you like, so that the correct score is returned for a given roll of 5 dice

My solution:

First the test using NUnit – (if using Visual Studio with Nuget – you can do ‘Install-Package NUnit’) :

[TestFixture]
    public class GreedScoreTester
    {
        [TestCase(1, 1, 1, 2, 3, 1000)]
        [TestCase(1, 1, 1, 1, 5, 1150)]
        [TestCase(1, 1, 1, 1, 1, 1200)]
        [TestCase(2, 3, 4, 6, 2, 0)]
        [TestCase(3, 4, 5, 3, 3, 350)]
        [TestCase(1, 5, 1, 2, 4, 250)]
        public void GameScore(int die1, int die2,int die3, int die4, int die5, int expectedScore)
        {
            var values = new int[]{die1, die2, die3, die4, die5};
            var greed = new Greed();
            int score = greed.Score(values);
            Assert.That(score == expectedScore);
        }
    }

Basically, the TestCase allows me to pass different sets of data to my GameScore test.  Since there are 5 dice being rolled, I can control the values being passed in.  Additionally, I pass the expected value with the set to assert on.

Next is the Greed class:

public class Greed
    {
        public int Score(int[] ints)
        {
            IEnumerable<IGrouping<int, int>> groupedDieRolls = ints.GroupBy(c => c);
            return groupedDieRolls.Sum(g => ScoreSet(g.Key, g.ToList()));
        }

        private static int ScoreSet(int key, IList<int> values)
        {
            int score = 0;
            var count = values.Count;
            switch(key)
            {
                case 1:
                    if (count >= 3)
                    {
                        score += 1000;
                        int extraOnes = count - 3;
                        score += (extraOnes*100);
                    }
                    else
                    {
                        score += (count*100);
                    }
                    break;
                case 5:
                    if (count >= 3)
                    {
                        score += (key * 100);
                        int extraFives = count - 3;
                        score += (extraFives * 50);
                    }
                    else
                    {
                        score += (count * 50);
                    }
                    break;
                default:
                    if (count >= 3)
                        score += (key * 100);
                    break;
            }
            return score;
        }
    }

As I mentioned above, the only real issue I have with my solution is the switch…case – I would like to have a more robust solution.  Then again, this was my first attempt at the kata.

In my initial code experience I started with an array of ints.  Then I moved to a dictionary of ints – as I wanted to group my values.  My last refactor was to use the Linq ‘GroupBy’.

Well, it was fun, I plan now on going out and seeing other examples.  One thing I didn’t mention above is that some people like to use the kata’s to learn new skills, ie. do it with Vim, do it with Ruby, etc… since I’m very new, I stuck to C# but hope to expand!

Kata–Greed Kata

While at Codemash this year, I was introduced to ‘katas’.  It’s a great idea really – where you are given a problem to solve and you work through it using whatever language and technique you want.   Take a look at Ryan Cromwell’s post ‘The Purpose of Katas’ to learn more.

So, actually I went with Ryan to Codemash and instead of just going to a session the entire day, there were opportunities to try some new stuff.  Ryan and I took a session off, desiring to do some coding, and went to the Codemash ‘Coding Dojo’ where you could pair up or even solve the kata alone. 

I will admit, I was a bit bewildered, as I really didn’t quite get it at first, as I really didn’t know what a kata was!  I ended up closing my lid of my laptop and leaned over to watch the process Ryan was doing.   For experienced kata developers in the dojo, they were off and running and pounding out the code in the allotted 30 minute timeframe.  Honestly, I spent my whole time trying to figure out what the kata meant!

When I got home from Codemash, one of my goals was to work through some kata’s to gain some experience and not be such a newbie.  My first week home I went through the bowling kata, following along with Uncle Bob (Bob Martin) – I highly suggest following along his powerpoint presentation : http://butunclebob.com/ArticleS.UncleBob.TheBowlingGameKata (check out this as well – adapted for C# 4 : http://www.slideshare.net/stewshack/bowling-game-kata-c ).  I went through this kata several times, attempting to grasp the flow and technique.  I don’t think kata’s are just meant to blindly work through and instead, start to develop an eye for when to refactor, how to use TDD, spotting patterns (ie. http://cleancoder.posterous.com/the-transformation-priority-premise) etc…  You don’t ‘have’ to use TDD to do a kata, but honestly, I am going to say that it would really defeat the purpose not too!

Ok, so all that aside, today I decided to re-try the Greed kata.   This time around, I didn’t want to follow along with any guide, just to try to solve it myself.  What I’m going to show is my ‘final product’ – although I think I need to figure out a way to do as Bob Martin did and go through my thought process – as this final product was not how I started.  I went through many iterations and steps (and although I can barely follow that link about transformation priority- I will say I think I saw that action – lol!).  I learned a few things going through this such as the TestCase concept – which I saw used at Codemash and thought was a clever way to test sets of data.   I am open to any feedback on my solution, as I don’t really like my ‘switch…case’ solution – so I will be looking to refine this the next time I run through the kata.   Kata’s are meant to be repeated over and over again.

Greed Kata

Greed is a simple dice game in which players roll a number of dice and determine their score based on combinations of dice rolled.  In an actual game, players would be allowed to re-roll unused dice until they arrived at their final score for one of their turns, and a game might be played up to a certain point total.  The game can be played with different numbers of dice.
For the purposes of this kata, the game will use 5 dice and will not allow any re-rolls.  A Game class with a Score method will return the player’s score for a given roll of the dice.  The following scoring rules will be used:

•    A set of 3 1’s [1,1,1] is worth 1000 points
•    A set of 3 of any other number is worth 100 * that number (e.g. [2,2,2] is worth 200 points)
•    A single 1 is worth 100 points
•    A single 5 is worth 50 points
•    Any other die or combination is worth 0 points

Requirements

•    Write a class named “Game” that has a public Score() method accepting a collection of dice values.
•    Implement the rules above however you like, so that the correct score is returned for a given roll of 5 dice

My solution:

First the test using NUnit – (if using Visual Studio with Nuget – you can do ‘Install-Package NUnit’) :

[TestFixture]
    public class GreedScoreTester
    {
        [TestCase(1, 1, 1, 2, 3, 1000)]
        [TestCase(1, 1, 1, 1, 5, 1150)]
        [TestCase(1, 1, 1, 1, 1, 1200)]
        [TestCase(2, 3, 4, 6, 2, 0)]
        [TestCase(3, 4, 5, 3, 3, 350)]
        [TestCase(1, 5, 1, 2, 4, 250)]
        public void GameScore(int die1, int die2,int die3, int die4, int die5, int expectedScore)
        {
            var values = new int[]{die1, die2, die3, die4, die5};
            var greed = new Greed();
            int score = greed.Score(values);
            Assert.That(score == expectedScore);
        }
    }

Basically, the TestCase allows me to pass different sets of data to my GameScore test.  Since there are 5 dice being rolled, I can control the values being passed in.  Additionally, I pass the expected value with the set to assert on.

Next is the Greed class:

public class Greed
    {
        public int Score(int[] ints)
        {
            IEnumerable<IGrouping<int, int>> groupedDieRolls = ints.GroupBy(c => c);
            return groupedDieRolls.Sum(g => ScoreSet(g.Key, g.ToList()));
        }

        private static int ScoreSet(int key, IList<int> values)
        {
            int score = 0;
            var count = values.Count;
            switch(key)
            {
                case 1:
                    if (count >= 3)
                    {
                        score += 1000;
                        int extraOnes = count - 3;
                        score += (extraOnes*100);
                    }
                    else
                    {
                        score += (count*100);
                    }
                    break;
                case 5:
                    if (count >= 3)
                    {
                        score += (key * 100);
                        int extraFives = count - 3;
                        score += (extraFives * 50);
                    }
                    else
                    {
                        score += (count * 50);
                    }
                    break;
                default:
                    if (count >= 3)
                        score += (key * 100);
                    break;
            }
            return score;
        }
    }

As I mentioned above, the only real issue I have with my solution is the switch…case – I would like to have a more robust solution.  Then again, this was my first attempt at the kata.

In my initial code experience I started with an array of ints.  Then I moved to a dictionary of ints – as I wanted to group my values.  My last refactor was to use the Linq ‘GroupBy’.

Well, it was fun, I plan now on going out and seeing other examples.  One thing I didn’t mention above is that some people like to use the kata’s to learn new skills, ie. do it with Vim, do it with Ruby, etc… since I’m very new, I stuck to C# but hope to expand!

Post Navigation

Follow

Get every new post delivered to your Inbox.