Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

14 May 2013

Pub/Sub Implementation I -- Common Components

After explaining what I plan to build (last time) now it's time to build it out.  This will be very rough around the edges; it's more an exercise to see whether or not this idea has legs enough to be worth spending more time on.

So, if we're going to do this (even rough), let's do it more-or-less right.  That means starting with our common components.  We're going to define our two Interfaces IPublisher<T> and ISubscriber<T> and our base Message type.  Next, we'll define our MessageBox (I called mine "Broker" but "MessageBox" is more appropriate).  Finally, we'll define our final message types.

Here's IPublisher
public interface IPublisher<T> where T: Message
{
  T CreateMessage();
  bool Publish(T message);
  bool Publish(IEnumberable<T> messages);
  Task<bool> PublishAsync(T message);
  Task<bool> PublishAsync(IEnumerable<T> messages);
}

That's the easy one.  It can create a message of its appropriate type, and it can publish a single message or a group of messages.  The "Task<bool>" declarations are to take advantage of the new Async features in .NET 4.5, if we want.

Here's ISubscriber
public interface ISubscriber<T> where T: Message
{
  IList<T> PendingMessages {get; set;}
  IList<T> ProcessedMessages {get; set;}
 
  IList<T> GetMessages();
  IList<T> FilterMessages(Func<T, bool> predicate);
  Task<IList<T>> GetMessagesAsync();
}

This one defines two properties, in addition to its three methods.  It has to be able to get messages, Filter them, and (as the properties suggest) take them from "pending" to "processed."

I did not define a "Process" method, however, because each system will have different requirements for how it does that.  Maybe it just takes it's PendingMessages as is, or maybe it also accepts some parameters, or whatever.

Next, we'll take a look at some of our Message types.  Not all of them, just some.

First, the base Message class.
public abstract class Message
{
  public string Id {get; set;}
  public string Publisher {get; set;}
  public DateTime PublishedDate {get; set;}
 
  public override bool Equals(object obj)
  {
    if(obj == null) return false;
    if(obj is Message)
    {
      var msg = obj as Message;
      return (this.Id == msg.Id);
    }
  }
 
  public override int GetHashCode() 
  {
    return base.GetHashCode();
  }
}

Here, you see we're defining a string "Id" (that's because I'm using RavenDB as my database for this example- you could do it differently), a string "Publisher," and a DateTime "PublishedDate."  Those are things all of my messages will have in common- Which message am I, who created me, and when did they do that?  I've also overridden Equals.  It's possible I'll have the same message coming from two different requests to the DB- that would create two different instances that are identical- rather than leaving the base Equals, I have specified "Hey, no two of us can have the same Id."

That's enough for now.  Next time: The MessageBox (Broker).

22 April 2013

Pub/Sub Implementation III – OrderManagement 1

IPublisher<NewOrderMessage>

Last time, we outlined the common components all of our systems will use.  In Real Life, of course, these would each have more detail, and there would probably be more of them.  But, for our purposes, this will do.

Now we're going to start Implementing some functionality.  We'll start with our Order Management system, because that's the domain we're focusing on.  As such, it is also the most complex of these pseudo-systems we're going to implement.  It implements our two interfaces a total of 5 times.  Two of those are IPublisher<T> and three are ISubscriber<T>.  This post will focus on IPublisher<NewOrderMessage>.

The first IPublisher type we'll be implementing is NewOrderMessage.  This simulates the idea that the Order Management System would have a front-end (which we will not be implementing) to create an order.  That order will then be stored, and a NewOrderMessage published for anyone who wishes to know.

That means we can't just define the Order Management System, we also have to define what an Order looks like.  Again, this will be a highly simplified example.

    public class Order
    {
        public string Id { get; set; }
        public string Customer { get; set; }
        public List<OrderLine> Details { get; set; }
        public decimal Total 
            { get { return Details.Sum(d => d.LineTotal); } }
        public DateTime OrderDate { get; set; }
 
        public Order()
        {
            OrderDate = DateTime.Now;
            Details = new List<OrderLine>();
        }
 
        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            if (obj is Order)
            {
                Order ord = (Order)obj;
                return (ord.Id == this.Id);
            }
            return false;
        }
 
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
    }

Notice, once again, we've overridden Equals.  This is because (once again) it would be at least theoretically possible to get two different instances (and therefore two different memory locations) of the same order- and we only want to fulfill any given order once.

Next, we'll look at OrderLine.  Again, highly simplified.

public class OrderLine
    {
        public string ItemName { get; set; }
        public string ItemSKU { get; set; }
        public decimal ItemPrice { get; set; }
        public int Quantity { get; set; }
        public decimal LineTotal 
          { get { return ItemPrice * Quantity; } }
    }

Now that we have that done, we can look at the how we handle NewOrderMessages.  A lot of the code is either boring, or a (needed) variation on code we've already done.  So I'll just highlight things that are interesting or not immediately intuitive.

public NewOrderMessage CreateOrderMessage()
  {
    IPublisher<NewOrderMessage> temp = this as IPublisher<NewOrderMessage>;
    return temp.CreateMessage();
  }
 
public NewOrderMessage CreateOrderMessage(string orderId, string customerId, decimal total, Dictionary<string, int> lines)
  {
    NewOrderMessage om = new NewOrderMessage();
    om.Publisher = PUBLISHER;
    om.PublishedDate = DateTime.Now;
    om.OrderId = orderId;
    om.CustomerId = customerId;
    om.OrderTotal = total;
    om.OrderItems = lines;
    return om;
  }

These first two let me get a new OrderMessage without having to write

IPublisher<NewOrderMessage> publisher = SalesSystem as IPublisher<NewOrderMessage>;
var message = publisher.CreateMessage;

all the time.  Instead, I can simply call CreateOrderMessage with my values from the Order, and get an order message.

Here is the version we use when we're actually processing, though:

public NewOrderMessage CreateOrderMessage(Order order)
{
    string orderId = order.Id;
    string customerId = order.Customer;
    decimal total = order.Total;
    Dictionary<string, int> lines = 
        new Dictionary<string, int>();
    foreach (OrderLine line in order.Details)
    {
        lines.Add(line.ItemSKU, line.Quantity);
    }
 
    pendingOrders.Add(order, "new");
    return CreateOrderMessage(orderId, customerId, total, lines);
}

That pendingOrders.Add refers to a Dictionary where I keep my orders (simply for this example).  IRL, we'd probably have a DB with the orders and their status.

And, finally, we get to processing:

public void GetNewOrders()
{
    List<Order> orders = new List<Order>();
    int count = 0;
    do
    {
        int cursor = orders.Count;
        var temp = broker.GetPagedMessages<Order>(ORDERS, cursor, PAGE_SIZE);
        count = temp.Count();
        if (count == 0) break;
        orders.AddRange(temp);
    }
    while (count > 0);
    ProcessOrders(orders);                      
}
 
public void ProcessOrders(List<Order> orders)
{
    var query = new List<NewOrderMessage>(); 
    int count = 0;
    do
    {
       int cursor = query.Count;
       var temp = broker.GetPagedMessages<NewOrderMessage>(MESSAGING, cursor, PAGE_SIZE);
       count = temp.Count();
       if (count == 0) break;
       query.AddRange(temp);
    }
    while (count > 0);
 
   foreach (var ord in orders)
   {
       if (!pendingOrders.ContainsKey(ord) 
           && !completedOrders.Contains(ord)
           && !query.Any(q => q.OrderId == ord.Id))
       {
           IPublisher<NewOrderMessage> pub = 
            this as IPublisher<NewOrderMessage>;
             pub.Publish(this.CreateOrderMessage(ord));
       }
   }
}

GetNewOrders goes and grabs any orders we've got.  Note the "Do/While" syntax- I want to fetch records at least once, and this way I keep going back until I've got them all.

Next, I process the orders.  To do that, the first thing I do is get all the OrderMessages I've already sent.  This is really an artifact of this being an example instead of Real Life.  In Real Life, my order would be updated to some status when I had published a new order message.  For the moment, this is easier than building out a "real" order message and ALSO building in the necessary checks.

So I get all NewOrderMessage documents from the Database.  Next, I take a look at my orders, and validate that they're not already in my pending bucket, that they're not already completed, and that I have otherwise already published a message for them.  Assuming that is true, I publish the Order via NewOrderMessage.

Next, we'll look at ISubscriber<BilledOrderMessage> and ISubscriber<AllocatedOrderMessage>.

19 April 2013

Pub/Sub Implementation II – The Message Box

Okay, I call mine "Broker" but MessageBox is more correct- therefore it will be "MessageBox" from here on out.

The MessageBox is just defining the connection to the Database.  Others would call it a DAL, but I'm not actually accessing Object Data, I'm accessing messages.  Thus, "MessageBox."  In my case, I chose RavenDB for this implementation.  I really like RavenDB- it's lightweight, it's intuitive, and it's fast to get up-and-running.

Here's my implementation:

  private MessageBox()
  {
    store = new DocumentStore() {Url = http://localhost:8080};
  }
 
  private static Lazy<MessageBox> instance = 
      new Lazy<MessageBox>(() => new MessageBox());
  public static MessageBox Instance 
      {get{return instance.Value;}}
 
  public bool Insert<T>(T item, string db)
  {
    using(var session = Store.OpenSession(db))
    {
      session.Store(item);
      session.SaveChanges();
    }
    return true;
  }  
 
  public bool BulkInsert<T>(IEnumerable<T> items, string db)
  {
    using (var bulk = Store.BulkInsert(db))
    {
      for(int i = 0; i < items.count(); i++)
      {
        bulk.Store(items.ElementAt(i));
      }
    }
    return true;
  }
 
  public T GetItemById<T>(string db, string id)
  {
    using(var session = Store.OpenSession(db))
    {
      return session.Load<T>(id);
    }
  }
 
  pulic IEnumerable<T> GetItemsByIds<T>(string db, string[] ids)
  {
    using(var session = Store.OpenSession(db))
    {
      return session.Load<T>(ids);
    } 
  }
 
  public IEnumerable GetPagedMessages<T>(string db, int start, int pageSize)
  {
    using(var session = Store.OpenSession(db))
    {
      var result = session.Query<T>()
           .Skip(start)
           .Take(pageSize);
      return result.ToList();
    }
  }
}

Okay, that was a beating, so let's look at what the code actually does.  First off, we set up our DocumentStore (that's the connection to the actual RavenDB database. 

Next, we set up the MessageBox as a singleton.  We'll probably be calling it a lot, and it's better if we don't call multiple copies per app-domain.

Finally, we establish the actual operations the MessageBox will do for us.  Note that this is the MessageBox code.  If we were using RavenDb as our backing store for our business objects, we'd probably have a different class (or just have every application use the RavenDB client, and write their own code).

There are two kind of tricky methods here.  The first is BulkInsert- I'm not sure why RavenDB doesn't support a Save method (even under it's "BulkInsert" functionality) that allows me to pass an array or enumerable of objects, but it doesn't.  So we use BulkInsert (which still only takes one at a time??).  The reason we're using a For loop, instead of ForEach, is that using BulkInsert to save each document automatically provides that object with an Id- thus modifying our collection- thus making ForEach unavailable.

The second one is the GetPagedMessages.  RavenDB, by default, will only provide you with 128 messages at a time.  So, if you expect more than that, you have to page through the results.  This is just a basic paging system, there are actually better ways to do it with RavenDb, but a) this is fast, b) this is functional, and c) it isn't actually wrong.  I use ToList() there, because the session.Query() method returns a IRavenQueryable collection, and sometimes that doesn't play nice with IEnumerable.  Using .ToList() fixes that.

Okay, that was a slog.  But I promised the MessageTypes, so here they are:

    public class NewOrderMessage : Message
    {
        public string OrderId { get; set; }
        public string CustomerId { get; set; }
        public decimal OrderTotal { get; set; }
        public Dictionary<string, int> OrderItems { get; set; } //TKey = SKU, TVal = quantity
    }
 
    public class BilledOrderMessage : Message
    {
        public string OriginId { get; set; }
        public string OrderId { get; set; }
        public string CustomerId { get; set; }
        public bool Approved { get; set; }
    }
 
    public class AllocatedOrderMessage : Message
    {
        public string OriginId { get; set; }
        public string OrderId { get; set; }
        public Dictionary<string, int> OrderItems { get; set; }
        public string WarehouseId { get; set; }
        public bool Allocated { get; set; }
    }
 
    public class FulfillmentRequestOrderMessage : Message
    {
        public string OriginId { get; set; }
        public string OrderId {get; set;}
        public string BillingId { get; set; }
        public string AllocId { get; set; }
        public string WarehouseId { get; set; }
    }
 
    public class FulfilledOrderMessage : Message
    {
        public string OriginId { get; set; }
        public string OrderId { get; set; }
        public string RequestId { get; set; }
        public bool Fulfilled { get; set; }
    }

 

Next Up- The Order Management System.

15 April 2013

Pub/Sub Revisited

How many enterprises say they want a "Publisher/Subscriber" architecture?  "We want," they say, "For the Ordering system just to send one message, and for everyone who needs it to get it.  Ordering shouldn't know anything about the down-stream systems."  Okay, that's fine as far as it goes.  But what about the other way around.  The current paradigm says that *someone* has to know about both up-stream and down-stream systems.

Either every "down-stream" system knows about every up-stream system that it cares about (and you'd be amazed at how many that is.  You'd also be amazed at how fast Ordering finds that it is down-stream of Inventory in the right circumstances), or some central system (or "Broker") knows about everybody and keeps them all straight.

Now, the first option is terrible.  Suddenly this "Publisher/Subscriber" methodology becomes Code-thulu.

The second option is fine, but it's not actually Publisher/Subscriber.  It's Hub-and-Spoke with a Broker.  Nothing wrong with that, but it has certain ramifications which will be different if you were expecting publisher/subscriber.

"But how," I hear you asking, "Can we get 'real' Publisher/Subscriber?"  And you have a point.  At some point, someone has to know about both up-stream and down-stream systems, don't they?

Well... no.  Not really, if you're willing to do a little work.

Now, let me be clear here- what I'm suggesting does not reduce complexity in any significant way.  We're talking about complex interactions between complex systems.  We can abstract that complexity away all we want, but that complexity will still exist somewhere.  What I'm suggesting allows the complexity to exist where it can most readily be changed/fixed- within the individual business domains inside your company.

How does this methodology work?  Enter the Dragon, err... Database.  Publisher/Subscriber does exist in the wild- it's called RSS, or Email, or any number of other things.  In those systems, the Publisher simply publishes a message (a blog post, an email, whatever), and the subscriber goes to look for new messages on a schedule.  Ours will work the same way.

Let us say we have a business that sells widgets online.  We'll have a system that takes the orders and owns them- it's job is to say "I've got a new order."  Also to say, "Okay, warehouse, the order is confirmed; go ahead and ship it."  We'll have a billing system.  The billing system's job is to listen for a new order, and then verify the customer paid (or has sufficient credit to pay).  We'll have an inventory system whose job is to listen for a new order and make sure we have the available inventory.  We could go on.

So how do all these systems communicate?

A common messagebox, and defined message types.

Our system will have a base "Message" from which will be derived a "NewOrderMessage," a "BilledOrderMessage," an "AllocatedOrderMessage," and a "FulfillmentRequestOrderMessage."  (There would be more as well IRL).

Then, we'll define (on top of those Messages) a MessageBox (I call it Broker on my system, but don't get confused- I merely mean that it "brokers" the DB functions), and two interfaces: IPublisher<Message> and ISubscriber<Message>.

Because these are Typed interfaces, I can actually implement several of the same one (and, in some cases I'll have to) without much difficulty.  For instance, our OrderSystem will be IPublisher<NewOrderMessage> and IPublisher<FulfillmentRequestMessage>, and it will be ISubscriber<BilledOrderMessage> and ISubscriber<AllocatedOrderMessage>.  This is why Explicitly Implemented Interfaces exist, after all.

Then, in general, an Order will come in, and the OrderSystem will publish the requisite NewOrderMessage.  Billing and Inventory will be listening for that message, and will each do their job based on the information therein.  When done, Billing (IPublisher<BilledOrderMessage>) will publish it's message saying "yay" or "nay," and Inventory will publish (IPublisher<AllocatedOrderMessage>) it's message saying "yep, we've got enough" or "nope, we'll have to back-order."  The OrderSystem will then wait until it has both an AllocatedOrderMessage and a BilledOrderMessage for the order, before requesting Fulfillment ("Hey, billing and inventory say this is a go- somebody call FedEx!").

12 April 2013

The Lowly Do/While

So, semi-officially, I'm exploring some options regarding a Pub/Sub Architecture at work.

One of the requirements (for this to be worth continuing exploring instead of just grabbing something off-the-shelf) is that we want to remove the man-in-the-middle that so many other frameworks use.

Before I go on, let me explain that:
Most pub/sub architectures, buses, or solutions are actually broker solutions.  Whether we're talking BizTalk (which does, indeed, use pub/sub internally), MassTransit (which looks like an awesome product, though I've never used it), or whatever, there is something in the middle that is maintaining the subscriptions.  A subscriber does not request messages, messages are pushed to the subscriber.

We want to explore the possibility of getting away from that paradigm.  We want the publisher simply to be able to lay their message wherever, and the subscribers to say "Hey, I wonder if I have mail?" and go check.

With that out of the way, what I'm currently exploring is the ability to lay messages on a DB (I'm using RavenDB for development because a) it's easy and b) It's what I'd like to use), and then have the subscribers be responsible for picking up those messages.

That's an interesting problem right there.  This is especially true with Raven's limit of 128 documents per request, but even with SQL or Oracle, you run into issues of "how often do I poll, and how do I know when to stop?"  Pulling back "all" the messages is no big deal when you have, say, 1000 or less.  It becomes a much bigger deal once you start approaching the 100,000+ range.

I started with the standard "while" loop.  You know; you've used it more times than you can count.  And you're already thinking (many of you): "Sure.  You'll go fetch records, check to see if you need more, and then use a while loop to finish fetching your documents."

You're even thinking of something along these lines:

int count = 0;
int cursor = 0;
List<Document> documents = new List<Document>
using(var session = DocStore.OpenSession())
{
  var results = session.Query<Document>();
  if(results.Count() > 0) documents.AddRange(results);
  count = results.Count();
  while(count > 0)
  {
    cursor = documents.Count;
    results = session.Query<Document>()
              .Skip(cursor)
          .Take(128);
    count = results.Count();
    if(count == 0) break;
    documents.AddRange(results);
  }
}

Many of you are looking at that and (except for how the paging is being handled -hey, it's an example, not production code-) see nothing particularly wrong.

And that's were I started.  But it looked messy to me.  It was hard to say "Here's what I'm doing."  So, I considered, and then I remembered something from long ago.  It was a construct that I hadn't used since my computer classes.  In fact, if you look around the Net, you'll see some people calling it the worst of the loop constructs.

I'm referring to the lowly Do/While loop.

Where a For loop says "Hey, do this X times," and a While loop says "Hey, as long as this is true, keep doing this," Do/While says "Here, do this.  Then if this condition is true, keep doing it."  That is, the action inside the loop will always run at least once.

When fetching records from a database that may or may not exist, it is incredibly helpful.

Here's the cleaner (IMO) code:

int count = 0;
int cursor = 0;
int page_size = 100; //I like 100 docs at a time.  Use as many as you want up to 128
List<Document> documents = new List<Document>();
using(var session = DocStore.OpenSession())
{
  do
  {
    var results = session.Query<Document>()
          .Skip(cursor)
          .Take(page_size);
    count = results.Count();
    if(count == 0) break;
    documents.AddRange(results);
  }
  while(count > 0);
}

I added that "page_size" variable, just for clarity.  It's better to state explicitly "We'll be returning up to 100 records at a time" than just leave it up to the RavenDB configuration.  Easier for someone later to read and know what's happening.

See how much easier it flows?  The original, if read for understanding would say:
"First, we go ahead and initialize some variables, including a list to store our results and two ints... I guess I'll see what those do.  Okay, then we go fetch the records from the database (Oh, yeah, this is RavenDB, so it's probably 128).  Then we check to see how many results we got back.  If we have any, we'll add those to the list, and then go look for more.  Oh, that's what we're using those two ints for, one is how many records we got back this time, the other is how many records we have total, so we know how many to skip.  Got it.  We'll keep doing that until a fetch doesn't grab any."

The second, reads this way:
"Okay, we initialize some variables: a list to store our results, and three ints... I guess I'll see what those do.  Then, we go fetch results- oh, there's the first int: cursor must be the total records we have grabbed and page size means how many records I'm bringing back.  Then count is how many records were brought back.  If there weren't any, we stop.  Otherwise we add the current result set to our list, and keep going."

Both things do functionally the same operation, the only difference is in readability.

Over on StackOverflow, the question about the difference between Do/While and While has been asked a couple of times, and the consensus seems to be "I've never needed it" or "I've seldom needed it."  But how often do we do exactly this functionality- "Hey, do this until it's done." 

If you need to make sure it's done at least once, then Do/While is your man.

19 June 2011

C# In Depth 2nd. Ed.: A (partial) Review

I’m currently reading C# In Depth: 2nd Edition (Jon Skeet, Manning Publications), and I thought I’d share my thoughts about it so far.

I would say I’ll do this in three parts: the good, the bad, an my take, but really there’s only “the good.” 

I consider myself to be a mediocre-to-good developer.  I still have lots to learn and my code can always get better.  Hanging out on StackOverflow.com, I get to see Jon’s casual mastery of C# nearly every day.  I can only thank him for the help he’s been to me- even if he’s never actually answered one of my questions (or, at least, I don’t remember that he has, and I think that would stick with me…)

C# In Depth is the work of a master.  They say that you’ve truly mastered something- not when you understand it, but when you can communicate that understanding clearly.  By that standard, Mr. Skeet has truly mastered C#.

The book begins with a look, a retrospective if you will, of C# 1.  I, for one, noticed the fondness Mr. Skeet still holds for the old language (and, as he would point out, the BCL and CLR that went with it).  Even as he points out its flaws- which it must have, or why even bother with C#2, 3, & 4- he also takes care to explain things so clearly that one can see a huge proponent of the language.

From pointing out the flaws in C#1, the book proceeds through C#2 and its enhancements to C#3.5 (where I currently am) and will proceed to C#4.  At each level, the detail he provides about how the language actually works is quite comprehensive- or, as comprehensive as a book meant for actual consumption can be.  Moreover, his explanations and examples pointed out, quite clearly, places I could improve my own code, or explained to me the “why” of things I had taken for granted.

As a C# developer who considers myself in the “Coding 201” camp (Okay, I may have graduated to Coding 202), I cannot imagine a better technical book to have at one’s fingertips.  Where other books range (within the same book) from simple (and sometimes misguided) pedantry in text to oversimplification and hand-waving in examples, C# In Depths seems to have hit that perfect sweet-spot of the text being concise enough not to put me to sleep, and examples being robust enough to see what would actually happen.

I highly recommend you read the book, if you haven’t already.  I can virtually guarantee that it will improve your coding game as you begin to understand why some things work the way they do.

I also recommend you go (and subscribe) to his coding blog.  It’s on my must-read list.

14 June 2011

A New Project: DoctorConnect

Welcome back!

Today I’m introducing a new project- again, mostly to help me learn stuff.  This one is a little more complex and will actually involve at least 2 and probably 3 sub-projects.  I call it DoctorConnect.

The theory is this: Assume that a Doctor’s office wanted to enable its patients to do some basic tasks online without having to call and wait for a nurse to call them back.  We’ve all had to do that, right?  You’re puking your guts out, and you have to wait for the nurse to call you back before you know if they can see you today (saving you $$$) or if you have to go to some Doc-in-a-Box Urgent Care place.

So: DoctorConnect.

It will be a system in 3 parts: A database (SQL Server 2008 R2), an internal web application (haven’t decided on MVC or Web Forms, yet) and an external web page.  After all that’s done, I may also design a mobile-app for the project: so users could schedule an appointment on-the-go.

This is a big project for me, and I’m going to have to master some things that I haven’t mastered yet before I get it right.

First: The DB.  I’ll need to map my DB tables to Objects.  This is complex enough a data model (more on that in another post) that I don’t fully trust EF, and I don’t trust my own skills at Linq-2-SQL enough.  So I’ll be looking at various ORM options to determine the best way to go.

Second: Membership.  Unlike the Issue Tracker, this will require a custom membership provider: I’ll need to know not only if someone is an authenticated user, but exactly what things they should be able to see.  On the internal application, that may be role-based, but on the external application, it will have to be something else- some hierarchy model that allows for a Responsible Party to see all the accounts for which he (or she) is responsible, but let other patients see only their own accounts.

Third: Polymorphic Data.  What I mean is this:  A patient, when scheduling an appointment, doesn’t need to know all the information about a specific doctor, just their name, specialty (so they don’t go see an OB/GYN about their prostate), and availability.  On the other hand, the Office Staff need to know just about everything about a patient.  How should I handle that?

Fourth: Scheduling.  I’ll need a way to set an appointment for a doctor and validate it against other scheduled events: we don’t want patients to be able to schedule an appointment during lunch, for instance, or while that doctor is on vacation.  So I’ll need to figure that out.

All in all, this is shaping up to be a big project.  So let’s start eating this elephant: one bite at a time.  Next up: the data model.

06 June 2011

MVC Issue Tracker: Where We've Been

I should have the final code zipped and pushed to CodePlex as a download sometime today or tomorrow.  This post is sort of a retrospective on what we've already done.

If you missed the posts, here they are in order
Introduction
Part 1- Setting Up
Part 2- Controllers
Part 2.5- Ancillary Issues
Part 3- Cleaning Up the Views
Part 4- Finishing Up

So, some impressions to wrap up:

First off, while I would have liked to implement my own authorization system, MVC3's provided version met all my needs quite well, and so there was no reason to handle that.  So that got cut out at the end.  I do like the fact that, for almost all scenarios, the MVC3 provided authorization model works well enough.  Perhaps someone with exceptionally high security needs would be required to create their own model, but I doubt anyone with such needs would be using MVC (the product) anyway.

Which leads me to my second point.  ASP.NET MVC3 seems to me like something a small company (even big for a small company, but small nonetheless) would use to get a website up and running relatively quickly.  I can see that it has plenty of power for the mid-sized business as well, but once you get up to larger enterprises, I see things I believe would cause some problems.

First, I don't like the lack of separation of the code.  MVC3, by default at least, throws all your code into one project.  I believe that my Model code (let's face it, it's the Data Layer) should be in a separate project, at least, and possibly a separate solution.  The Controller code- being the Business Layer- should, to my mind, be likewise separated- either in a separate project or separate solution.

Now, I don't see any reason you couldn't use MVC like methodology and still have those layers of separation, but MVC3, in itself, is fairly dependent upon having all that code in the same project- at the very least for auto-generating views and controllers.  I may be wrong, but it seemed to me that MVC was built on the idea that all of this code would be in the same project.  That's fine for fairly small and/or encapsulated applications, but a larger enterprise with multiple web applications may very well have need to separate those layers better simply because they want people to interact very differently (beyond simple authorization issues) with the same data.

Take, for instance, the sample project the good folks at MS use of Contoso University.  Their MVC3 tutorial walks you through setting up a way to enroll students, or add classes, or whatnot.  In a real life situation, that enrollment, and most of the administrative functions, would be handled (if they used MS Technologies at all) on an internal only application- whether an intranet application or a windows application- and all anyone logging in would be able to do is some basic maintenance of their own student account and request enrollment (with the actual enrollment being handled by some other application to ensure class sizes were set properly, etc.).  This would lead to it making more sense to have that level of separation.

Now, my thought is that MS would be saying, "You're right- so you don't use MVC for that."  That's a completely reasonable expectation- but it is something to be aware of.

All in all, however, I was impressed by the power of MVC and the ease with which the application came together.  Certainly it would need a lot of cleaning and polishing before anyone used it as an actual production application, but I can see the seeds in there for just such a thing.  Add to that the lightweight nature of the newest version of SQL Compact for the database, and a small company could easily use such a thing- instead of some big and expensive tracking system- to track their trouble tickets.  And, as with anything that contacts the database, all that really needs to happen if the ticket database grows too big is to create the same db schema in some more robust database (say, full on SQL Server, or whatever) and change the web.config connection string.

I hope this exploration has been as beneficial for you as it was for me.

03 June 2011

MVC Issue Tracker Part 4

This is the penultimate entry in this series.  I’ve completed the code to the level I intend (for the moment) and I’ve verified things work as I expect (for the moment).

So, let’s look at what we had left to do:

  • Wire up WorkNote/Create so that it would redirect back to the underlying issue instead of to the index of WorkNote.
  • Provide Security.

The first was easy, instead of using “RedirectToAction(“Index”) I changed the code for "Create” to this:

   1: [HttpPost]
   2:         public ActionResult Create(WorkNote worknote)
   3:         {
   4:             if (ModelState.IsValid)
   5:             {
   6:                 var issueId = db.Issues.Where(i => i.IssueId == worknote.IssueId).SingleOrDefault();
   7:                 worknote.EnteredBy = this.HttpContext.User.Identity.Name;
   8:                 worknote.LoggedDate = DateTime.Now;
   9:                 db.WorkNotes.Add(worknote);
  10:                 db.SaveChanges();
  11:                 return RedirectToAction("Details", "Issue", new { id = issueId.IssueId });   
  12:             }
  13:  
  14:             ViewBag.IssueId = new SelectList(db.Issues, "IssueId", "Title", worknote.IssueId);
  15:             return View(worknote);
  16:         }

Ignore the “IssueId” and “EnteredBy” stuff for now.  The important part is at the end: “return RedirectToAction(“Details”, “Issue”, new {id = issueId.IssueId})';  This tells the controller that, on a successful insert, it should redirect to the “Details” view of the Issue with a specified issue id.

See?  Easy.

The next part required some extensive refactoring.  I was going to implement my own security model, but that’s really fairly silly.  MVC3 provides us with a perfectly acceptable method of Role based security, so we’ll just hook into that.

First, I removed the User class and Role enum, and all the references to same.  Then, using the configuration button, I used the built-in web-based configuration to set up roles, and add a couple of users.

From there, it was all markup.  Some samples follow:

   1: [Authorize(Roles="Administrators,Manager,Developer,User")]
   2:     public class WorkNoteController : Controller

This piece just says that only someone logged in as an Admin, Manager, Dev, or User can get to the WorkNoteController.  I have similar authorization on Issue.

More significantly, on Issue, I marked up some of the specific methods for the IssueController:

   1: [Authorize(Roles = "Administrators,Manager,Developer")]
   2:         [HttpPost]
   3:         public ActionResult Edit(Issue issue)
   4:         {
   5:             if (ModelState.IsValid)
   6:             {
   7:                 if (issue.ClosedDate != null) issue.ClosedBy = this.HttpContext.User.Identity.Name;
   8:                 db.Entry(issue).State = EntityState.Modified;
   9:                 db.SaveChanges();
  10:                 return RedirectToAction("Index");
  11:             }
  12:             return View(issue);
  13:         }
   1: [Authorize(Roles = "Administrators,Manager")]
   2: [HttpPost, ActionName("Delete")]
   3: public ActionResult DeleteConfirmed(int id)
   4: {            
   5:     Issue issue = db.Issues.Find(id);
   6:     db.Issues.Remove(issue);
   7:     db.SaveChanges();
   8:     return RedirectToAction("Index");
   9: }

These are specific authorizations required to access specific views: Edit and Delete, respectively.

So, now, an Administrator would have to create a new user (as one would expect in a business scenario) and provide that user with the correct credentials.  That user would then only be able to access the parts available to the assigned Role.  Basically, a basic user can add issues and can look at issue details/status.  A Developer can do that, but can also edit issues (specifically to close them, when necessary) and add work notes.  Managers and Administrators have the additional authority to delete issues.

Additionally, since I’m able to use the provided Role based security, I’m also able to avoid the necessity of a “User” object, and just grab the UserName from the Session.  This allows tagging that is just as accurate as building role-based security from scratch, and that is more intuitive, since I can just grab the username instead of the user’s Id, or going through some hoops to take that Id and turn it into their name.

The final code push is up on CodePlex now, and I’ll zip it all up and add it to the downloads folder soon as well.

Next Up (In a couple of days): A look back, and my impressions from working with MVC3.

02 June 2011

MVC Issue Tracker: Part 3

For this installment of the Issue tracker, I mostly just clean up our views a little bit.  I also added a little functionality for a snap-shot page and provided the ability to add new work notes to an issue.

Let’s dive in.

First off, I added a Snap-Shot report to the ‘About’ Page, like so:

image

This required very little code, actually, but adds a nice little bit of polish- along with helping me get my head around exactly where we’re going here…

 

   1: public ActionResult About()
   2:         {
   3:             var allIssues = ctx.Issues;
   4:             var closedIssues = ctx.Issues.Where(i => i.ClosedBy != null);
   5:             var openIssues = ctx.Issues.Where(i => i.ClosedBy == null);
   6:  
   7:             var oneWeek = GetClosedInOneWeek(closedIssues);
   8:             var twoWeeks = GetOpenGreaterThanOneWeek(openIssues);
   9:             double oneWeekCount = oneWeek.Count();
  10:             double closedCount = closedIssues.Count();
  11:             var pctOneWeek = oneWeekCount.PercentOf(closedCount);
  12:  
  13:             ViewBag.CountAllIssues = allIssues.Count();
  14:             ViewBag.CountClosedIssues = closedIssues.Count();
  15:             ViewBag.CountOpenIssues = openIssues.Count();
  16:             ViewBag.OneWeek = oneWeek.Count();
  17:             ViewBag.TwoWeeks = twoWeeks.Count();
  18:             ViewBag.PctOneWeek = pctOneWeek;
  19:  
  20:             return View();
  21:         }

First, I added this to the About action of the HomeController.  It just grabs the issues, then collates the ones that are closed vs. the ones that are open, and runs some quick analysis.

Heading over to the View, we added this:

   1: <h2>Issue Tracker Snap-Shot</h2>
   2: <p />
   3: <table>
   4:     <tr>
   5:         <td><b>Total Issues Logged</b></td>
   6:         <td>@ViewBag.CountAllIssues</td>
   7:     </tr>
   8:     <tr>
   9:         <td><b>Closed Issues</b></td>
  10:         <td>@ViewBag.CountClosedIssues</td>
  11:     </tr>
  12:     <tr>
  13:         <td><b>Open Issues</b></td>
  14:         <td>@ViewBag.CountOpenIssues</td>
  15:     </tr>
  16: </table>
  17:  
  18: <h3>Issue Closure Details</h3>
  19:  
  20: <table>
  21:     <tr>
  22:         <td><b>Issues Closed In One Week or Less</b></td>
  23:         <td>@ViewBag.OneWeek</td>
  24:     </tr>
  25:     <tr>
  26:         <td><b>Percent Issues Closed in One Week</b></td>
  27:         <td>@ViewBag.PctOneWeek</td>
  28:     </tr>
  29:     <tr>
  30:         <td><b>Issues Open More than Two Weeks</b></td>
  31:         <td>@ViewBag.TwoWeeks</td>
  32:     </tr>
  33: </table>

And that’s really all it took.

The Percentage part was kind of tricky, though: since there are no closed issues (as might actually happen in the first several days to couple of weeks if this were ever someone’s actual ticket tracking system) the Percentage wanted to return NaN.  So I created a little extension method off of Double:

   1: public static double PercentOf(this double numerator, double denominator)
   2:         {
   3:             var temp = numerator / denominator;
   4:             if (Double.NaN.CompareTo(temp) == 0) return 0;
   5:             return temp;
   6:         }

It just goes ahead and divides anyway, and if the result returns NaN, it passes back 0.  Not mathematically accurate, but business accurate.

Next, I turned to the WorkNote.  Specifically, I turned to making the edit a little more accurate, and linking it to the Issue.  I modified the controller and view to handle the LoggedDate automatically, and then I modified the Detail view of the Issue to provide a list of WorkNotes and the ability to add a new one.  Like So:

   1: </fieldset>
   2: <table>
   3:  <thead>
   4:    <tr>
   5:      <th>Work Detail</th>
   6:      <th>Entered By</th>
   7:      <th>Date</th>
   8:    </tr>
   9:  </thead>
  10:  <tbody>
  11:    @foreach (var item in Model.WorkNotes)
  12:    {
  13:        <tr>
  14:          <td>@item.Detail</td>
  15:          <td>@item.UserId</td>
  16:          <td>@item.LoggedDate.ToShortDateString()</td>
  17:        </tr> 
  18:    }
  19:  </tbody>
  20: </table>
  21: <p>
  22:     @Html.ActionLink("Add Notes", "Create", "WorkNote") |
  23:     @Html.ActionLink("Edit", "Edit", new { id=Model.IssueId }) |
  24:     @Html.ActionLink("Back to List", "Index")
  25: </p>

So, now, when we navigate to the detail of an issue, we get:

image

And clicking on the “Add Notes” link gives us:

image

Currently, when we add a new note, it takes us to the WorkNotes Index… we’ll work on that for the next post.