Tuesday, February 19, 2013

Preserve image aspect ratio

I've been meaning to put some code snippets in here. Nothing earth shattering just little handy coding bits.

A while back I spent some time in xaml trying to maintain image aspect ratio. The images that I'm binding to vary in size and ratio. I knew the area they would be displayed  would have a height around 200-220 pixels. This is what I ended up doing.



Only bind to the dimension you don't know, width
Create a multibinding value converter. You do that by implimenting IMultiValueConverter.
Because these converters take object parameters, and I don't know who may use them after I am off a project; I always check the types of each param.

The math for getting ratio is just width / height.

If you know what height you want, then take the height and multiply it by the ratio
If you know the width take it and divide it by the ratio.

Friday, November 2, 2012

Builder Pattern

*Disclaimer these writings are for my own learning purposes not as advice to others. If any part is incorrect please feel free to constructively discuss.

Previously I discussed
Strategy Pattern
Factory Pattern
Abstract Factory Pattern
Observer Pattern
Facade Pattern

Today I'll be discussing the Builder Pattern. I usually don't include UML because they are all over the web and haven't brought that much extra value to my write-ups. But this pattern has a few more parts then the previous patterns I have dicussed, and I feel it will help.

Straight from Wikipedia











The builder pattern is a creational pattern, and the point of it is to encapsulate the complexities of creating a
complicated object. The Builder pattern can also create variations of the complex object.

At first I thought this pattern sounded familiar. It sounded a little bit like the Factory or Factory Method Pattern or maybe Abstract Factory. Its pretty different though and a short definition of each should help illustrate.

Factory - Client calls factory and factory directly returns one of many different types based on the parameters given to it. The clinet doesn't know what it's getting back only that the object inherits from a given abstract class or interface.
Factory Method - Client has an instance of an abscract factory wich defines an abstract method for creating products, but the client instantiates the factory with a conrete instance of that factory. The concrete instance impliments the create method and can create one of many types of the product but only return the parent class or interface that represents the product.
Abstract Factory - There are some similarities to the Factory method pattern here but just remember the Factory method pattern only returns one parent type to the client. In Abstract Facotry the client has a reference to an abstract factory, and instanciates it with a concreate factory that implements the abstract factory. The concrete factory creates concrete products and returns multiple parent types to the client.

Builder Pattern - An abstract builder class defines abstract methods for creating various parts, and a method for returning a product. Concrete builders implement the abstract builder class and are responcible for building the parts, keeping track of their representations and providing a method to return the final product. A director class provides a construction method that calls the part building methods in the concrete builder classes. (In what ever order or with what ever parameters it decides on).

Below is my car demonstration of the Builder pattern. The source code along with all other pattern examples can be found here

















 

Tuesday, October 30, 2012

Part 2 Entity Framework 5 using the POCO pattern, a data first approach, for a Table Per Hierarchy model

*Disclaimer these writings are for my own learning purposes not as advice to others. If any part is incorrect please feel free to constructively discuss.

Part 2: MVC 4 with existing context class, and an abstract base type

Previously in Part 1 I discussed a data first approach to using Entity Framework, existing POCO's, and a table per hierarchy design.

With all that wired up I began to evaluate MVC 4.

Most MVC tutorials will have you start off with a table first approach or an object first approach. In the case of a table first approach you will end up with a datamodel (edmx file), and they will let EF code generate entity classes inheariting from EntityObject and a context class inheariting from ObjectContext. Some tutorials even advise that these entities might be a tad heavy for some uses. The alternative is to use DbContext by right clicking the model and choosing "Add code generation item", and selecting "ADO.NET DbContext Generator". This leaves you with a much more simplified context class inheriting from DbContext that just returns sets of each entity. You also get a much more stripped down simple entity class definitions.

I did not used EF code generation but instead defined my own entities and context class. (This will come into play later).

After adding an MVC app to my solution and choosing Razor as my view engine, I first needed to create a controller. In the "Add Controller" prompt you have the ability to choose a controller template that will wire up read/write actions and views for you. All you need is a model class and a context class.

If you choose this option you end up with a BookStore controller that already has the actions wired up for you.
You also get a class level instance of your context object instantiated in the controller.
Also notice the Get and Post verb comments added, (More about that later).



Also you get all your Razor cshtml views created for you.













This is enough to start the MVC application and view the default layout that comes with it.
Notice the RESTful URL style, and seperate views representing basic CRUD operations.



But there's a small problem. If I go to POST Or GET on one of my resources (create or an edit) I get this big ugly error.

Server Error in '/' Application.

Cannot create an abstract class.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.MissingMethodException: Cannot create an abstract class.




Why am I getting this? Pretty simple you cannot instantiate an abstract class. MVC has these ModelBinders, and I'm no expert but in simple terms they help bind the model information to the views. The default model binder may realize it needs a Book object but remember that discriminator thing we talked about in Part 1? The default model binder doesn't know how to make this discrimination. But we can define our own ModelBinder. To do that you need to derive from DefaultModelBinder. I'm only going to override the CreateModel method. Here is the result. 



But, we aren't done quite yet. I needed to tell the application to use this new binder before it worked correctly. You do this in global.aspx. 

Now that I have defined my custom modelbinder and added it to the global.aspx I can run the site. Its still just a very out of the box MVC 4 application. Notice the default edit and create views that got made for you. They don't reflect all the properties in our objects.





















My enums are missing. This may be because of how we had to map the entities, but fixing is pretty easy. I added the following lines to use the DropdownListFor control in the html helper



This control requires a SelectedList of values. You can add the C# required to accomplish this directly in your cshtml page using the open and close tags like @{ }

Instead I added a static method to the book class. that looks like so.


Technically putting this functionality in the Book class is all kinds of wrong, and I would not actually do this in  a production application. The reason not to do this is I would be breaking the "separation of concerns" principle by bringing a UI concern into a domain object. This whole demo app could be structured so that my UI layer doesn't even know about my domain objects. A service layer could pass the UI layer nice flat DTO's. I could then add this method to the Book DTO. 

In the end I end up with something that represents all the elements ofthe book object I need to do a create. 





















Obviously this is still not in a state I can really use. No one knows what ReturnPolicy value 3 means. To handle that I can decorate my Enum's with the Componentmodel.DescriptionAttribute and alter my EnumToSelectedList method so that the SelectedListItems text value pulls the description attribute. That's outside the scope of this blog but if I get around to writing it I will edit this blog and add it.

More to come in:

Part 3: MVC 4 view engine, Observer Pattern, and binding


Monday, October 29, 2012

Facade Pattern

*Disclaimer these writings are for my own learning purposes not as advice to others. If any part is incorrect please feel free to constructively discuss.

Previously I discussed
Strategy Pattern
Factory Pattern
Abstract Factory Pattern
Observer Pattern

The Facade pattern is widely used, and frameworks, and API's  are common implementers of this pattern. Often times a complex API or framework can have interfaces capable of large amounts of functionality and complexity. There may be too much complexity for the intended client to have to deal with. Stringing together a series of function calls for example. This is where the Facade pattern comes in to play. The Facade simply provides a layer of abstraction and or encapsulation by wrapping one or more complex interfaces to provide a unified interface showing only what is necessary to the intended client.

Considerations when implementing a facade layer:
Necessity: Is the facade really unifying complex interfaces for a client that doesn't need to use or understand all the functionality.
Forcing: Is the facade forced on the client? A facade should be bypass-able.
Adding functionality: Is the facade adding functionality? It shouldn't. Its primary focus is to unify a subsystem. It may collect some information to call several methods within the subsystem, therefore unifying functionality, but if functionality is added it might not really be the facade pattern, maybe Decorator instead.

Drawing from the automotive realm again Lets take the ignition process as an example. You the client want to turn the key and have the car start. You don't want to to think about the ignition switch allowing the electrical system to have power from the battery and in turn send electricity to the starter solenoid. The solenoid to send power from the battery to the starting motor. The gear on the starting motor to turn the larger gear on the flywheel. The flywheel to turn the crank driving the pistons. The vacuum from the pistons to pull atomized fuel and air mixture from the carburetor into the cylinders to be ignited by the spark plugs firing inside the cylinders... You just want your start method. You want to call it and let the rest of the stuff behind the scenes happen without your knowledge.

*Note it may be tempting to implement your facade as a singleton. Take a look at this interesting article discussing singleton, GoF patterns, their association with C++, and when is the best time to use a singleton. Its an interesting read. I'm not saying you shouldn't use it but just something of interest.

Here is that ignition example in code. (*Not how I would layout an object model for a serious project relating to an engines ignition process. But, its complex enough to get the point across for this demo).
The entire solution containing this project and the previously discussed projects can be found here.

//Ignition class


//Starter class and solenoid interface. Implements ISolenoidElectronic indicating it is a type of device that //requires a solenoid and should be expected to have a run method. (Not necessary for the Facade pattern //just makes this example make more sense to me.


//Flywheel Class


//Crank


//Carburetor


//Cylinder


//Sparkplug


//Facade class

Wednesday, October 17, 2012

Part 1 Entity Framework 5 using the POCO pattern, a data first approach, for a Table Per Hierarchy model

*Disclaimer these writings are for my own learning purposes not as advice to others. If any part is incorrect please feel free to constructively discuss.

Recently I wanted to become more familiar with Entity Framework, and MVC.
I'm going to discuss what I learned in a 3 part blog.

Part 1: TPH, Data First, with existing POCO's
Part 2: MVC 4 with existing context class, and an abstract base type
Part 3: MVC 4 view engine, Observer Pattern, and binding


Part 1: TPH, Data First, with existing POCO's

In the past I have worked with NHibernate, and Telirik Open Access ORM's. I have actually used Entity Framework a few times but in very simple scenarios. I follwed the wizards, and let EF create my entities.

I felt that this was pretty unrealistic experience, so I set out to make myself go through some pain so that I could learn the ORM better.

I decided that in many companies I would be asked to map to already existing data and object models.

I  already had an existing bookstore demo. This demo included an object model and a data schema. The two were not designed with this EF MVC demo in mind. So I thought I should have to jump through a few hoops to make it work. Well I did.

The model consists of one complex type (an abstract base class called book). And three POCO's (derived book types).

Here is the base class.


Here are the POCO's

Here is the very simple Book table.

I know its not a great idea to directly represent an Enum in a table by it's numeric value. But, I had read EF 5 has better Enum support so I wanted to put it to the test.

First I created an ADO.NET Entity Data Model. By default I ended up with something that looked like this:

First thing to do after generating the model was to set the "Code Generation Strategy" to "None". This stops EF from generating entities for you. *Remember I am plannig on using existing classes for my object model. Next I marked the Book entity type as Abstract.

The way the model is set now will work, but I don't like it yet. When I get a book out of my database I want it automatically casted to the derived type it really represents. I.E. I want many different types to map to the same table. This is called a "Table-per-hierarchy" design. There is also a Table-per-Type design but I'm not going to go into the differences. To accomplish the behavior I right clicked in the model's blank area, and chose "Add new Entity..." I'm guessing there is some string magic that goes on here so when typing the names of your derived types be sure to spell them the same way you did in your class declarations.
I created PaperBack, Magazine, and HardCover entities and set their base type to "Book"

The map looks like this now:



Almost done, but I need a way for EF to know how to map the derived types when fetching them from the DB. To do this I used a discriminator. In this case "BookTpye" is my discriminator. Right click on BookType in the Book entity, and choose "Delete from model". Now view the mapping details for the PaperBack entity. Click on "Add a condition", I chose BookType and the equals operator, and set the value to 3. This tells EF when the BookType value is three cast the object to PaperBack. I repeated this for Magazine and HardCover.

After that I mapped the Enum's. There is a new "Convert To Enum" option on the right click menu. It brings up a window that looks like this:





















And unlike earlier versions of EF this Enum mapping actually works.

Because I chose a code generation strategy of none I have no context class. I chose to implement a context class that inherits from ObjectContext. I could have also used dbContext, but I didn't.

The class itself is easy. The hard part came in troubleshooting various issues I had with my entity connection string's metadata. The problems I had there are a little outside the scope of this blog. I don't want to go too far off on a rabbit trail, but there are several great sites for troubleshooting issues of this type.

Here's the context class:

Here is a class that represents a service layer and exposes functionality of the context class.
Later on I could take this service layer and implement a more traditional SOA approach. I could set it up so that my DO's stay on one side of my service, and DTO's go out to my UI layer. I can set up some object validation in my service layer as well.




With these layers set up I can perform all the basic CRUD functions I need to make a sample MVC application.


As long as I was already in VS 2012 I went ahead and used MVC 4.

I will go over that portion in Part2.





Observer Pattern

*Disclaimer these writings are for my own learning purposes not as advice to others. If any part is incorrect please feel free to constructively discuss.

Previously I discussed
Strategy Pattern
Factory Pattern
Abstract Factory Pattern

Due to how events are handled one of the most widely used patterns in the .Net framework is the Observer Pattern.

The main point of the observer pattern is the allow objects to be notify of state change in other objects without being tightly coupled. At least thats how I would describe it to someone in my own words.

A more text book definition is:
"Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically" Got that from OODesigns.

If you ever written an application using the architectural pattern's MVC or MVVM you've used the observer pattern.

As usual I will not go into a lot of detail defining the pattern, there's plenty of sites that have already done that. Below is my example, and here is the source code.

*Note this is a very basic example. I point that out because you can get quite a bit more specific in exactly what flavor of the observer pattern you implement. I believe publish / subscribe is the most widely used. Another is using a feature called an event manager or change manager, or Event Emitter/Target/Dispatcher. My example is a simple publisher / subscriber flavor. Also within that flavor you can implement notifications in a "push" or "pull" manner. Push being the subject always informs the observers of change, and "pull" being the observers can reach out and check for changes in the subject when they want. This example uses the Push technique.

//Subject interface
public interface IEngine
{
      string Name { get; set; }
      List<ISubscriber> Subscribers { get; set; }
      void Notify();
      void Attach(ISubscriber subscriber);
      void Detach(ISubscriber subscriber);
      int EngineTemp { get; set; }
}

//Concrete Subject
public class SilveradoEngine : IEngine
{
        public List<ISubscriber> Subscribers { get; set; }

        public SilveradoEngine()
        {
            Subscribers = new List<ISubscriber>();
        }

        public void Notify()
        {
            foreach(ISubscriber subs in Subscribers)
            {
                subs.Update(this);
            }
        }

        public void Attach(ISubscriber subscriber)
        {
            Subscribers.Add(subscriber);
        }

        public void Detach(ISubscriber subscriber)
        {
            Subscribers.Remove(subscriber);
        }

        private int _EngineTemp;
        public int EngineTemp
        {
            get
            {
                return _EngineTemp;
            }
            set
            {
                _EngineTemp = value;
                Notify();
            }
        }

        public string Name { get; set; }
}

//Observer or subscriber interface
public interface ISubscriber
{
      void Update(SilveradoEngine engine);
}

//Concrete Observer 1
public class EngineTemperatureDashLight : ISubscriber
{
        IEngine engine;
        public EngineTemperatureDashLight()
        {
            this.engine = engine;
        }
        public void Update(SilveradoEngine engine)
        {
            this.engine = engine;
            EngineTempWarningLight = this.engine.EngineTemp > 500 ? true : false;
        }

        public bool EngineTempWarningLight {get; set; }

}

//Concrete Observer 2
public class OnStarAlert : ISubscriber
{
        IEngine engine;
        public OnStarAlert(IEngine engine)
        {
            this.engine = engine;
        }
       
        public void Update(SilveradoEngine engine)
        {
            this.engine = engine;
            OnstartHasAlerts = this.engine.EngineTemp > 500 ? true : false;
        }

        public bool OnstartHasAlerts { get; set; }
}

Wednesday, October 10, 2012

Abstract Factory Pattern

*Disclaimer these writings are for my own learning purposes not as advice to others. If any part is incorrect please feel free to constructively discuss. 

Previously I discussed the Strategy Pattern and the Factory Pattern. Most recently I've been looking at the Abstract Factory Pattern.

Here's the general definition used throughout the internet:
The abstract factory pattern is considered a creational pattern. In general this pattern is most useful when a client needs to create a family of related or dependent objects without specifying the concrete class.

A common example is a drawing or UI framework. An abstract Factory Pattern might be used to create a family of brushes or a palette of colors.

The client knows about the abstract product, but it doesn't know or care about the the concrete classes created by the methods exposed by the abstract factory.

Abstract factory pattern can be a way to encapsulate concrete factories with commonalities. If the system needs to create multiple families or a library of products without being concerned with implementation details, then this patten can be used.

Here's my example using the vehicle theme again.

//The abstract factory
abstract class AbstractFactory
    {
        public abstract Car CreateCar();
        public abstract Truck CreateTruck();
    }

//The concrete factories implementing the interface defined by the abstract factory
class BaseModelFactory : AbstractFactory
    {
        public override Car CreateCar()
        {
            return new BaseModelCar();
        }
        public override Truck CreateTruck()
        {
            return new BaseModelTruck();
        }
    }

class FullyLoadedFactory : AbstractFactory
    {
        public override Car CreateCar()
        {
            return new FullyLoadedCar();
        }
        public override Truck CreateTruck()
        {
            return new FullyLoadedTruck();
        }
    }

class SportModelFactory : AbstractFactory
    {
        public override Car CreateCar()
        {
            return new SportModelCar();
        }
        public override Truck CreateTruck()
        {
            return new SportTruck();
        }
    }

//Abstract Product 1
abstract class Car
    {
        public abstract Seats Seat { get; }
        public abstract Trims Trim { get; }
        public abstract AccessoriesPackages AccessoriesPackage { get; }
        public abstract Engines Engine { get; }
        public abstract int GetTrunkSpace();
        public abstract string GetTitle();
    }

//Abstract product 2
abstract class Truck
    {
        public abstract Seats Seat { get; }
        public abstract Trims Trim { get; }
        public abstract AccessoriesPackages AccessoriesPackage { get; }
        public abstract Engines Engine { get; }
        public abstract int GetBedSpace();
        public abstract string GetTitle();
    }

//Concrete Products
class BaseModelCar : Car
    {
        public override Seats Seat
        {
            get { return Seats.Cloth; }
        }

        public override Trims Trim
        {
            get { return Trims.Base; }
        }

        public override AccessoriesPackages AccessoriesPackage
        {
            get { return AccessoriesPackages.Base; }
        }

        public override Engines Engine
        {
            get { return Engines.Economy; }
        }

        public override int GetTrunkSpace()
        {
            return 3 * 2;
        }

        public override string GetTitle()
        {
            return "a reliable dependable no frills base model sedan.";
        }
    }

class BaseModelTruck : Truck
    {
        public override Seats Seat
        {
            get { return Seats.Cloth; }
        }

        public override Trims Trim
        {
            get { return Trims.Base; }
        }

        public override AccessoriesPackages AccessoriesPackage
        {
            get { return AccessoriesPackages.Base; }
        }

        public override Engines Engine
        {
            get { return Engines.Economy; }
        }

        public override int GetBedSpace()
        {
            return 8 * 4 * 2;
        }

        public override string GetTitle()
        {
            return "a reliable dependable no frills base model truck.";
        }
    }

class FullyLoadedCar : Car
    {
        public override Seats Seat
        {
            get { return Seats.Leather; }
        }

        public override Trims Trim
        {
            get { return Trims.ChromePackage; }
        }

        public override AccessoriesPackages AccessoriesPackage
        {
            get { return AccessoriesPackages.FullyLoaded; }
        }

        public override Engines Engine
        {
            get { return Engines.Touring; }
        }

        public override int GetTrunkSpace()
        {
            return 4 * 3;
        }

        public override string GetTitle()
        {
            return "a top of the line state of the art fully loaded car.";
        }
    }

class FullyLoadedTruck : Truck
    {
        public override Seats Seat
        {
            get { return Seats.Leather; }
        }

        public override Trims Trim
        {
            get { return Trims.ChromePackage; }
        }

        public override AccessoriesPackages AccessoriesPackage
        {
            get { return AccessoriesPackages.FullyLoaded; }
        }

        public override Engines Engine
        {
            get { return Engines.Touring; }
        }

        public override int GetBedSpace()
        {
            return 6 * 4 * 2;
        }

        public override string GetTitle()
        {
            return "a top of the line state of the art fully loaded truck.";
        }
    }



And it goes on the same for sport car/truck.
*I could have flipped this example and made the abstract product be the package type (Fully loaded, Base Sport). Then I could have let the different vehicle types be the concrete products. In the end my client could have then said show my all the types of trucks, and I could have used the abstract factory to create a truck of type fully loaded, Base, and Sport.

*Note my code implies the use of some enums. I did not show the definition of the enums in the code snippets in this blog, but they are in the source code
.
Here is the source code complete with an example of a client calling the methods exposed by the abstract factory, and listing out the vehicles features.
DesignPatternExamples