Creating HTML Treeview on website wth MVC and JQuery

There are many ways to create a tree view on the web, today I wanted to talk about a simple way.  What I did was declare an object called resource, in this case people, that report to one another.  So its an object that links to other objects of its own type.  Here is the resource class as I am using it. The DataBridge is just my data access class in this case.
public class ResourceModel
        public int Id { get; set; }
        public string Name { get; set; }
        public int ReportsTo { get; set; }
        public EResourceType Type { get; set; }
        public int PercentFullTime { get; set; }
        public IList<ResourceModel> GetChildren
                if(_children == null)
                    _children = DataBridge.GetModels(Id);
                return _children;
        private IList<ResourceModel> _children = null;
Next, I created a web page that renders a list of ResourceModels.  The list I respond to this page is the root level resources.  This is what that super simple page looks like.
@model IEnumerable<ResourceManager.Models.ResourceModel>

    ViewBag.Title = "ResourceEdit";
    Layout = "~/Views/Shared/_Layout.cshtml";

<h2>Resources Edit</h2>

<ol id="treeview">
<script type="text/javascript">
    $().ready(function () {
        //default, basic treeview
I should note that I am using the JQuery library called Bonsai to convert my ol li list to a tree view before I go any further.  There are a number of JQuery libraries that do the same thing, this is just the first that Google Returned that looked reasonable.  I had to modify the header to include links its css and js file as well as make sure JQuery was being included.
That's almost it, as you could see, I was using the Html.DisplayForModel(Model) in the treeview which renders a list of ResourceModels.  For this, I implemented a partial view for the ResourceModel type and put it in the Shared/DisplayTemplates folder.  Here is the content of that recursive view.  
@model ResourceManager.Models.ResourceModel
    @if(Model.GetChildren.Count() > 0){
It utilizes the GetChildren property I exposed on the class to get all child elements as it re curses the tree.  Its rather slick actually.  Because it had to do a count check before actual list, I cached the results on the object as you could see in the class storing the children as a private variable.

MVC 4 Install on IIS 7 First time 404.14 Error

Ok, I have run into this a few times installing MVC for the first time on IIS.  You copy the file out to the server, set up the application and nothing happens.  Here are the steps I go through to solve the problem.

1. Make sure .Net is installed to the version of your site.  In the MVC case make sure you have 4.0 or better most likely and compile your site to that version by right clicking your Project Properties and setting the .Net version.  If you need a later version, install it on the server.

2. After IIS is installed, register that version of IIS there.
cd \
cd Windows\Microsoft.NET\Framework\
aspnet_regiis -i

3. If it still doesn't work you may have to look in your config file.  One line I had to add to get things working was the following.
    <modules runAllManagedModulesForAllRequests="true"/>
4. If your still getting the 403, you need to start looking at the permissions used.  If the site is using windows authentication, do you have rights to use it on that server?  Perhaps you need to use impersonate like below.
    <identity impersonate="true" userName="domain\username" password="password"/>
Another common line of code that will cause issues is the deny users, remove this from the config if need be, but make sure to take care of that authentication then.  
      <deny users="?"/>
Good Luck!

Publisher Subscriber WCF Implementation C#

The publisher subscriber software pattern was described several decades ago as a way to decouple messaging between systems.  It allows the source of data to let an unknown number of subscribers know about the data and have it without knowing who they are.  This is useful in modern day business software as many times you will have an object, say a new product that comes into the system, and several other systems want to know about that new product.  The challenge arises when we want to send that product to all sub systems.  Traditionally, we may have put the product in a table, and each other system would have a routine to look at the table for new products.  This is clunky and depends on schedules which is limiting in its own right. 
The next method to implement this traditionally was to have the process that loads the new product to go ahead and push its changes to all other systems as well.  This is much more real time, but does come with the catch that adding any new sub system will require a complete release and regression of all the other systems which is costly.
The publisher subscriber pattern tried to alleviate this by having a central broker take care of the communication from publisher to subscriber.  This 3rd party was historically very simple and really should be.  An interesting way to implement it is with WCF using web services to have more of a distributed setup.  Here is how I did it.
The first thing I did was create a new WCF project I called PubSub.  I had a product object defined to use as my message to pass in transport.  It ends up being passed as an event argument which I placed in a class.
public class ProductChangeEventArgs : EventArgs
        public IProduct product;
Next, I defined the interfaces for my WCF app.  I have a product contract as well as a the product Client Contract.  
[ServiceContract(Namespace = "http://ProductContract.Service", SessionMode = SessionMode.Required, CallbackContract = typeof(IProductClientContract))]
    public interface IProductContract
        [OperationContract(IsOneWay = false, IsInitiating = true)]
        void Subscribe();
        [OperationContract(IsOneWay = false, IsTerminating = true)]
        void Unsubscribe();
        [OperationContract(IsOneWay = true)]
        void PublishProductChange(IProduct input);

    public interface IProductClientContract
        [OperationContract(IsOneWay = true)]
        void ProductChange(IProduct input);
As you can see, the IProductContract has 3 methods.  Subscribe, Unsubscribe and PublishProductChange.  The publishing agent(s) call this routine with the product.  The subscribers call the subscribe method, which is not one way, so it is a connection held open until unsubscribe is called.  The concrete implementation of the IProductContract (ProductService) shows how subscribers are pooled and managed though the subscribe and unsubscribe method and have IProductClientContract called back to them with the product information when it is published by the publisher.  In effect, this WCF app is the broker.
// The Service implementation implements your service contract.
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
    public class ProductService : IProductContract
        public static event ProductChangeEventHandler ProductChangeEvent;
        public delegate void ProductChangeEventHandler(object sender, ProductChangeEventArgs e);

        IProductClientContract callback = null;

        ProductChangeEventHandler productChangeHandler = null;

        //Clients call this service operation to subscribe.
        //A price change event handler is registered for this client instance.

        public void Subscribe()
            callback = OperationContext.Current.GetCallbackChannel<IProductClientContract>();
            productChangeHandler = new ProductChangeEventHandler(ProductChangeHandler);
            ProductChangeEvent += productChangeHandler;

        //Clients call this service operation to unsubscribe.
        //The previous price change event handler is deregistered.

        public void Unsubscribe()
            ProductChangeEvent -= productChangeHandler;

        //Information source clients call this service operation to report a price change.
        //A price change event is raised. The price change event handlers for each subscriber will execute.

        public void PublishProductChange(IProduct product)
            var e = new ProductChangeEventArgs();
            e.product = product;
            ProductChangeEvent(this, e);

        //This event handler runs when a PriceChange event is raised.
        //The client's PriceChange service operation is invoked to provide notification about the price change.

        public void ProductChangeHandler(object sender, ProductChangeEventArgs e)
            catch (Exception)
                //todo bad subscriber, remove from queue
It is worth noting that if the subscribers die and don't call unsubscribe, it will cause issues on the broker, some sort of child maintenance would be necessary to make this production ready.  If you need guaranteed delivery, you may consider having this insert into messaging queues vs. TCP/IP calls.

So here is a quick form that could be your Publisher to send messages.
namespace TestPublisher
    public partial class Form1 : Form
        InstanceContext context = null;
        ProductContractClient client = null;

        public Form1()

        public class ServiceCallback : IProductContractCallback
            public void ProductChange(IProduct input)

        private void button1_Click(object sender, EventArgs e)
                context = new InstanceContext(new ServiceCallback());
                client = new ProductContractClient(context);
                client.PublishProductChange(new IProduct() { Description = textBox1.Text });
            catch (Exception)

Here is an example of a command line app that acts as a subscriber.  You can spin as many of each up as you want and watch the fun as you publish.  
namespace PubSubClient
    class Program
        public delegate void MyEventCallbackHandler(IProduct input);
        public static event MyEventCallbackHandler MyEventCallbackEvent;

        static void Main(string[] args)
            new Program().go();
            while (true)

        void go()
            InstanceContext context = new InstanceContext(new ServiceCallback());
            ProductContractClient client = new ProductContractClient(context);

            MyEventCallbackHandler callbackHandler = new MyEventCallbackHandler(UpdateForm);
            MyEventCallbackEvent += callbackHandler;

        [CallbackBehaviorAttribute(UseSynchronizationContext = false)]
        public class ServiceCallback : IProductContractCallback
            public void ProductChange(IProduct input)

        static void UpdateForm(IProduct input)

Restricting MVC site to an IP Range

At times it may become necessary to restrict a website to a particular set of IP addresses sometimes know as IP filtering.  I recently deployed an internal application for a company on the Azure platform hosted my Microsoft.  Deploying the app is content for a different article, but being that it is a internal site for the company in question, I wanted to restrict its access.  After some research, a simple config change can accomplish this in MVC, and Azure supports it.
      <!-- this line blocks everybody, except those listed below -->
      <ipSecurity allowUnlisted="false" denyAction="NotFound">
        <!-- removes all upstream restrictions -->
        <!-- allow requests from the local machine -->
        <add ipAddress="" allowed="true"/>
        <!--allow network to>
        <add ipAddress="" subnetMask="" allowed="true"/>
        <!-- allow the specific IP of  -->
        <add ipAddress="" allowed="true"/>
This can be used to either restrict ip ranges or grant depending on the ipsecurity tag's denyAccess flag is set.  In the example I allow access only to localhost, our network's IP range, and the public facing IP for the business.  Luckily we only have 1, so it was simple, if you have a range, one would just put the 0 in to cover all sets.

Add Tracing To WCF Messages

It sometimes becomes useful to trace messages coming into and out of a WCF service for debugging.  I find when I am doing soap integration's it is especially useful to be able to trace the soap messages for debugging.  The message isn't obviously stored, however there is a trace that you can attach to to get it though the system.diagnostics library.
      <source name="System.ServiceModel.MessageLogging">
                 <add name="messages"
                 initializeData="c:\logs\messages.svclog" />

Simple enough and now you will have a log file with your requests.