Search This Blog

Friday, October 31, 2014

To I (interface) or not to I

Recently I had a very interesting debate about when to create interfaces for classes and when not to.  The debate was specific to DTOs (Data Transfer Objects) but the debate can be generalised a bit further. A web article was referenced which overwhelmingly said “no, you should not create interfaces for DTOs”.  When I say overwhelmingly I mean 17 people (the number of ticks the post got), so in reality, less than the average classroom size of a small New Zealand primary school. 

So in this post I’ll hopefully systematically set out a whole bunch of reasons on why I (this is my opinion) believe interfacing everything (nearly everything) is indeed plain old good practice.

Argument A: The interface serves no purpose

Rebuttal: The purpose of an interface is always what you think the purpose is, a little bit cyclic but its like saying beauty lies in the eyes of the beholder.  I am a unit test aficionado and even if I don’t always write unit tests for everything I go out of my way to make code unit testable.  In my experience interfaces allow this to happen with ease.  Interfaces also keep code scalable, it may not serve a big purpose now but can you guarantee it won’t serve a purpose a year down the track?

Argument B: I’ll add the interface when the need arises

Rebuttal: Why put off till tomorrow what you can do today.  Adding an interface to any class takes under 5 clicks at most with any modern IDE.  Doing this in the future may mean that you might have to touch several (already deployed) components.  Depending on how complicated your release strategy is this change may not even be allowed by your release manager.

Argument C: The code (without interfaces) meets business requirements

Rebuttal: Some one can potentially write a whole application with a single method which meets business requirements, really…, is this even a fair argument?  I’ll entertain it anyway.  You are writing code to meet business requirements, agreed but that is not the only concern.  Your code should be maintainable and scalable.  Maintainable not just by you but by future developers.  Adding an interface to a class just adds that extra layer of protection for you in the future to denote that all properties in the class are actually there for a reason.  Not to forget it follows the “interface segregation” and “open close principle” of OO.

Interfaces also build that extra flexibility into your code to allow for those pesky requirements to change and believe me they always do.  E.g. say if you have a class called Customer with three properties DOB, Name and Title.  You have used this class everywhere and I mean EVERYWHERE! A new business requirement has come in to prepend the Title to the Name of the customer in parts of the application where formal communication is required.  Easy, all those parts of the application will have Customer.Title + “ “ + Customer.Name. Woah! All of a sudden we have got business logic in parts of the application which only deal with the UI for example. Wouldn’t it be more elegant to use a different type of Customer, e.g. FormalCustomer in those parts of the application?  If you had a simple interface, this would be a walk in the park, where all you passed in was a ICustomer and in the parts where formal communication was required, you would pass a factory to create a FormalCustomer implementation.  Yes very easily done if your application is written with scalability and maintainability in mind (i.e. IOC).

Now with an interface if you ever decide to move the Customer class to a new namespace you know that you need to move the interface and the FormalCustomer too, this makes refactoring a thought process rather than simply doing it for the sake of it.

Argument D: Do you expect me to go change all classes (DTOs) and add interfaces to them?

Rebuttal: HELL NO!!! Only the ones you touch for your new code.  Most times we are dealing with legacy systems where there are hundreds of classes scattered all around the place, I would suggest only touching the ones you are interested in.  Sometimes this is also not possible as the classes/DTOs might be auto generated, e.g. EF entities.  In that case its an executive decision you need to make and decide whether adding interfaces is truly worth is or not at this juncture in time.

Argument E: Aren’t you saying create a canonical model of the business objects with interfaces?

Rebuttal: In a way yes, unfortunately with modern tools like Entity Framework there is a very grey area where the domain meets the persistence layer.  Unfortunately, if things are not designed well at the start to keep the domain (canonical models) away from the persistence layer there is very little advantage in adding an interface late in the application lifecycle.

Argument F: In the article mentioned at the start, they said “no, you should not create interfaces for DTOs”

Rebuttal: Ever heard of the line “If it is on TV it must be true”? Articles online (this one too) are merely a reference point, it is up to you what you do from that point onwards.  Actually there are many articles which will strongly agree and some which may agree with me, well, this is my opinion.

Argument G: A DTO like Customer is similar to framework objects like Point and Color, you don’t see the framework interfacing those out

Rebuttal: Comparing a Customer DTO to a trivial property bag such as Point or Color is naive.  I agree that some DTOs do exhibit the same attributes as trivial property bags, e.g. if you had a EF entity called CustomerType.  Although I don’t think trivialising Customer in the same bucket as a Color object is prudent.  In reality it could be argued that say you have a Point and then a TransformedPoint (which given a point transforms it), now you want to store these in the same collection, simple, you can’t! So you could either extend Point or extract an interface, both options may have their pros and cons (beyond the scope of this article). Although you can see how interfaces can be so powerful.

Summary

  1. Use interfaces as much as possible, they help you become a good abstract programmer
    1. Once you have felt the power of interfaces and feel that you can successfully decide when best to use them and not, that’s when you can dial them down
  2. Adding an interface is trivial and takes less than 5 seconds, so why the hell not!
  3. Don’t write code to last, write code to change, interfaces cater for that change

Sunday, October 21, 2012

How are we raised?

There are a lot of things in life that intrigue me, out of which I have to say faith and spirituality are right up there on the list.  In the past recent few months we have been learning about God and the Holy Spirit and a lot of questions have come to mind.  Out of which, the question which I have long asked even before attending church was of immortality.

A question, which I am sure is on everyone’s mind, what happens after death?  And the slightly mundane version of that, how are we actually raised from the dead?

In the Christian faith (pardon me if I do get things wrong), Jesus’s resurrection is the corner stone.  Even more so, it is the cornerstone of time.  This gives extra meaning to what I learnt a few days ago at church by merely reading a few paragraphs of Corinthians I.

I always wondered how was Jesus raised from the dead?  How did he appear to the number of people in the days following?  Was he a figment of their imagination?  Maybe a hallucination?  To tell you the truth, I don’t really know what form or body Jesus took after death, maybe it has been stated in the Bible although I haven’t got to that passage yet.  So the verse which got my attention more than anything was Corinthians I 15:35-38 which goes:

“But someone will ask, “How are the dead raised? With what kind of body do they come?”  You foolish person! What you sow does not come to life unless it dies. And what you sow is not the body that is to be, but a bare kernel, perhaps of wheat or of some other grain. But God gives it a body as he has chosen, and to each kind of seed its own body.”

This is then followed on in Corinthians I 15:42-45:

“So is it with the resurrection of the dead. What is sown is perishable; what is raised is imperishable. It is sown in dishonor; it is raised in glory. It is sown in weakness; it is raised in power. It is sown a natural body; it is raised a spiritual body. If there is a natural body, there is also a spiritual body. Thus it is written, “The first man Adam became a living being”; the last Adam became a life-giving spirit.”

These particular words resonated with me dearly, as to when a man is born he is impure and when he is “raised” he is purified.  Put simply, the act of bringing life into existing can be seen as dishonor although the process of life after death is glorious.

This gives new meaning to the word death, who knows what lies beyond, as this particular chapter in the Bible puts it, it is something to dearly look forward to, if for nothing else, then to answer the questions which burden not the mind, but your soul.

In Corinthians I it also says how each form of life/body/presence is different from the rest.  Like the Sun and the Moon are different and how our flesh is different from that of any animal, fish or reptile.  Although I am afraid it doesn’t draw any conclusions to what a resurrected body might look like, that is up to us to find out but rest assured that it will have its own unique “body”.

I hope this blog article creates more questions in your mind than answers, after all the best answer is one which surfaces when there are no more questions to ask!

Monday, December 21, 2009

Using Microsoft Enterprise Library VAB with WCF services – Part 2

In Part 1 we looked at a simple solution on how to do service side validation for a simple WCF service and pass the resulting validation result back to the client.  In this article we’ll look at some other types of validators provided by the Enterprise Library and also touch the topic of rulesets and how they help.

So far we have looked at RangeValidator; let us look at some of its properties.

Bounds
The LowerBound and UpperBound of the validator are self-explanatory and denote the minimum and maximum value the validator can accept.

BoundType
The BoundType is synonymous to the bounds you have, it tells you whether the bounds are included, excluded or simply ignored.

Negated
If negated is set then we basically negate the rule, therefore in our example where we had the rangevalidator to accept only positive integers, setting negated=true would mean we only allow negative integers.  Kind of a redundant property in my opinion and simply complicates things.

Tag
Allows the developer to replace the name of the property which caused the validation fault to a custom string.  Useful when your property name is something like “accessDate” and you want to return “Access Date”.  Keep in mind that the custom Tag is only read when you have a custom message template.

MessageTemplate
Each validator provided by the Enterprise Library comes with its own message which gets returned on a validation fault, this can be customised by the developer.  For e.g. for the Range Validator we know (looking at the MSDN documentation) token {2} is the Tag, therefore our message template could be “{2} is invalid.” and we would get “Access Date is invalid.”

MessageTemplateResourceName/MessageTemplateResouceType
The following items come in handy when you have declared your messages in a resource file.

Ruleset
Allows the developer to target different validation rules depending on different criteria.  E.g. different clients may have different validation rules depending on different business logic.  This can be done by simply changing the config file to tell the validation block which ruleset to use as shown below:







To be continued…

Thursday, December 10, 2009

De/Se-rializing C# objects to XML

I have come across many projects over the years which need some sort of serializing and deserializing of C# objects to XML.  I usually remember the general syntax but more than often end up searching for the exact syntax.  There are tonnes of articles on this by the way and this blog is merely to give me a consistent way of doing this rather than anything else.

Say you have a couple of C# classes such that one class contains a collection of the other class and you want to serialize this into XML.

image

The way I usually do it is simply by adding some attributes to my C# classes which represent the structure of the resulting XML and run an XML serializer against it.  So my C# classes would potentially look like:

[XmlRoot(ElementName = "Customer", IsNullable = false)]
public class Customer
{
[XmlElement(ElementName = "Name")]
public string Name { get; set; }

[XmlElement(ElementName = "IsExpired")]
public bool IsExpired { get; set; }

[XmlElement(ElementName = "DOB")]
public DateTime DOB { get; set; }

[XmlArray("Orders")]
[XmlArrayItem("Order", Type = typeof(Order))]
public List<order> Orders { get; set; }
}

public class Order
{
[XmlAttribute(AttributeName = "OrderID")]
public int OrderID { get; set; }
}

With the above class we get an XML output as shown in the figure below:

image

And the code which actually does the serialization:

class Program
{
static void Main(string[] args)
{
Customer c = new Customer()
{
Name = "Ruskin Dantra",
DOB = DateTime.Today,
IsExpired = false,
Orders = new List<order>()
{
new Order() { OrderID = 1},
new Order() { OrderID = 2},
new Order() { OrderID = 3}
}
};

System.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(typeof(Customer));

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;

XmlWriter writer = XmlWriter.Create(@"Customer.xml", settings);
s.Serialize(writer, c);
writer.Close();
}
}

If you want to deserialize the above created XML back into the object all you have to do is:

System.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(typeof(Customer));
XmlReader reader = XmlReader.Create(@"Customer.xml");
Customer deserializedCustomer = s.Deserialize(reader) as Customer;
reader.Close();

Its as easy as that :)

Wednesday, December 9, 2009

Using Microsoft Enterprise Library VAB with WCF services – Part 1

I am starting to write a series of blog articles, each varying in complexity, highlighting how we use can the Validation Application Blocks within the Microsoft Enterprise Library to do really neat validation.  Extremely flexible and configurable at runtime.  Although we will slowly build towards that.

In this first part let me just give a brief introduction to what the VAB actually is some simple ways of using it within a WCF service.

While writing WCF services we often cannot guarantee the data we get passed in, let it be simple data like integers or complex business objects such as Customers or even worse, process definitions.  Although, as developers we have to design some sort of clever program which can intelligently sorting out good data from bad data.  Good data is often derived from pages of use cases and business rules.  These rules tend to change often so it’s only advisable that we allow for this by allowing our program (in this case a WCF service) to read this rules at runtime.  This is our end goal.

In the early days I used to do simple checks on data to determine its validity.  Although strenuous and naive, it worked.  For e.g. if you have a service which finds the square root of a number then we know for a fact that it cannot accept a negative number.  So a developer has the following options:

  1. Don’t care about the erroneous input
  2. Cater for error scenarios (number being less than 0) and return a exception
  3. Cater for error scenarios (number being less than 0) and return a message
  4. Return an exception which has the message

Yes, the last option does look the most tempting but a bit harder to implement.  Let us try and work through the other options first, for all our scenarios we will have the same interface and client definition:

Interface:

namespace VABService
{
[ServiceContract]
public interface IMyService
{
[OperationContract]
double SquareRoot(double number);
}
}

Client:

namespace VABServiceClient
{
class Program
{
static void Main(string[] args)
{
service.MyServiceClient client = null;
try
{
client = new VABServiceClient.service.MyServiceClient();
double result = client.SquareRoot(4);
}
catch (Exception e)
{
}
finally
{
if (client != null && client.State != System.ServiceModel.CommunicationState.Faulted)
{
try
{
client.Close();
}
catch (Exception e)
{
// don't care
}
}
}
}
}
}


Don’t care about the erroneous input With this approach our implementation looks simple and we end up with:



namespace VABService
{
public class MyService : IMyService
{
#region IMyService Members
public double SquareRoot(double number)
{
return Math.Sqrt(number);
}
#endregion
}
}


This service implementation will allow for the correct square root to be returned but say instead of passing in a positive integer we pass in a negative integer: –4; can the service guarantee a deterministic result?  I don’t think so, the most the developer can say is that it will do whatever the .Net environment is set up to do.  Left as is the result coming back will be NaN.



image



If the client was a high risk financial application and the service returned this value, the result would be quite catastrophic unless both the client and the service came to some sort of prior agreement about this returned value.  Although wouldn’t it be nice if we raised an exception or an error of some kind sighting the problem?



Cater for error scenarios (with an Exception) To allow for an exception to be raised we have to slightly change the service implementation as shown below:



namespace VABService
{
public class MyService : IMyService
{
#region IMyService Members
public double SquareRoot(double number)
{
if (number < 0)
throw new ArgumentOutOfRangeException(string.Format("Square root of negative numbers cannot be determined:{0}.", number));
return Math.Sqrt(number);
}
#endregion
}
}


Now with the same client as before if we pass in a negative number we get a  exception although the client is nonetheless wiser than it was before:



image



You see the above exception because of an attempt to hide the implementation details of the service from the clients calling it.  Just as the exception states, if we set the flag IncludeExceptionDetailsInFaults to be true, we will actually see why the exception occurred:



image



Although this is opening up our service unnecessarily and clients can get a clear view of our implementation when things go wrong and lets face it, things always can go wrong!  So we want to avoid setting IncludeExceptionDetailsInFaults to true in a production environment.



Cater for error scenarios (with a message) To allow for this we have to add even more code to the implementation and also add another parameter to our interface which we can use to pass back the error message, which in this case is the exception text.  We all know how this is going to look, yes UGLY!  We don’t want to do that!!! This brings us to our last option and the most elegant solution.



Return an exception which has the message This is where Geers Blog comes in handy.  WCF exposes really neat things which can be used to do all sorts of validation but why do this when we can go one step further and use an already well thought and designed framework wrapper.  Yes, the VAB is exactly that.



The Meat

Yes so far all you have seen is bones and why, what…and blah blah, boring stuff.  The meat of the post is now here…let us use the VAB to do simple validation while finding the square root of a number.



First step would be to install the enterprise library and add a reference to (within your service project):





  • Microsoft.Practices.EnterpriseLibrary.Validation.integration.WCF




  • Microsoft.Practices.EnterpriseLibrary.Validation.dll




  • Microsoft.Practices.EnterpriseLibrary.Common.dll




After doing so we’ll need to make 3 changes…




  1. Service interface change

    Our service interface will now contain the following code.

    using System;
    using System.ServiceModel;
    using Microsoft.Practices.EnterpriseLibrary.Validation.Integration.WCF;
    using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;

    namespace VABService
    {
    [ServiceContract]
    public interface IMyService
    {
    [OperationContract]
    [FaultContract(typeof(ValidationFault))]
    double SquareRoot(
    [RangeValidator(0, RangeBoundaryType.Inclusive, Double.MaxValue, RangeBoundaryType.Inclusive)]
    double number);
    }
    }

    Note that we now have a rangevalidator for the parameter “number” and also declare that this particular interface method has a fault contract of type ValidationFault associated to it


  2. Config file
































    Note that we have only added new a endpoint behaviour, a behaviour extension and mapped our already existing endpoint to the newly added endpoint behaviour.


  3. Client change
    static void Main(string[] args)
    {
    service.MyServiceClient client = null;
    try
    {
    client = new VABServiceClient.service.MyServiceClient();
    double result = client.SquareRoot(-4);
    }
    catch (FaultException fe)
    {
    }
    catch (Exception e)
    {
    }
    finally
    {
    if (client != null && client.State != System.ServiceModel.CommunicationState.Faulted)
    {
    try
    {
    client.Close();
    }
    catch (Exception e)
    {
    // don't care
    }
    }
    }
    }

    With this change in the client, now instead of getting simply exceptions without any message we get a particular type of exception which we can catch and investigate as shown in the image below: 
    image



We’ll look at other validators in Part 2.

Debugging VB6 COM DLLs via .Net

I am sure there are other ways of doing this but this post is just a simple step by step guide on one of them.

More often than not we have to use legacy COM components while writing new applications, let it be for database access, business logic or to simply avoid duplicating code.  Every time I end up using a COM object in my .Net application I lose the ability to debug inside that COM object and mostly have to assume that whatever happens within that call is logically correct.  Sometimes I am not convinced so I need to see proof of it first hand, so what do I do, I debug the COM call.

Adding a COM object to .Net cannot be easier, simply add a reference to the COM object which is registered on your computer and .Net automatically creates what we call a CCW (COM Callable Wrapper).  This is widely documented here.

In order to demonstrate how to debug a COM call let us first create a very simple VB6 DLL called Project1.dll.  In this COM DLL I have a single class called Class1.cls which contains a very simple Add method as shown below:

Option Explicit

Public Sub Add(ByVal a As Integer, ByVal b As Integer, ByRef result As Integer)
result = a + b
Exit Sub
End Sub

After creating this method, I built the DLL to a location using the default build options within the VB6 IDE by going to File>Make Project1.dll.


After this was done I created a new ConsoleApplication solution in C# to reference this COM DLL.  Added a reference to Project1 which allowed me to do this:


Project1.Class1Class class1 = new Project1.Class1Class();
short res = 0;
class1.Add(1, 2, ref res);

Great, I can now use the add method which I wrote in the COM object, say if the COM method returns the wrong value and I want to step into that code, I simply go Debug>Step Into (F11).  But what happens is that the debugger simply steps over that code and gets the result.  What has happened is that none of the symbols for that Project1.dll were loaded into my IDE:

image


This can be achieved simply by building the VB6 DLL using symbolic information.  You can do this by right clicking on the VB6 project in your IDE and going to Properties>Compile and check the boxes which say “Create Symbolic Debug Info” and also select “No Optimization”.


image

After the above is done, rebuild the Project1.dll.  You’  Simply doing the above step will not allow you to step into the “Add” function because the .Net IDE still hasn’t loaded the symbols.  To allow for this we have to enabled “Unmanaged Debugging” for our project, this can be done by going into the Project Properties>Debug and checking the box “Enable unmanaged code debugging” as shown below.

image


Doing the above process will now load the symbols:

image


Doing the above steps will still not allow us to step into the VB6 code, for this we have to do a manual step.  Open up the code file which has the “Add” function defined and put a breakpoint at the desired line of code.  Now when you step into the “Add” method call you will hit the breakpoint on the VB6 side as shown below:


image


Voila! :)

Saturday, October 24, 2009

Using VB to show IIS sites within Installshield 2010

Quite often I have worked on projects where an installer is needed.  So far I am quite familiar with Installshield and its inner workings so this blog describes a simple piece of code which solves a generic issue I had.

More often than not we program in a web based world, a web based installer is needed and the obvious incline is to use IIS, well at least for me considering I am mainly of a .Net developer.  In Installshield everything is easy when it comes to installing something on the local IIS but it gets complicated when you want to customise this process and allow users to choose the website within which the application will be installed or even the name of the application.

Customising the name of the application is easy and can be done simply by using what Installshield refers to as “properties”.  Expose a simple edit box and then in your “Internet Information Services” node simply change the “Name” to point to the property mapped to the edit box (e.g. “[MY_VIRTUAL_DIRECTORY]”).

Things get complicated when you want to show the user a list of websites to which your application can be added to, by default it goes to the “Default Web Site” or at least that’s what I assume but not always as stated by this table here.

Saying that, there is no easy way of showing the user a list of already existing websites on the local computer so after a bit of hunting around I found several solutions on the Installshield forums which advised me of a particular VB script which does what we need.

Dim objViewDim objDB
Dim objInstaller
Dim objRecord
Dim objW3SVC, objIisWebSite
Dim lngOrder
Set objDB = Session.DatabaseSet
objInstaller = Session.Installer

'Delete any records that may exist
Set viewList = Database.OpenView("SELECT * FROM ComboBox")
viewList.ExecuteSet recList = viewList.Fetch

'delete any existing records
While Not (recList Is Nothing)
viewList.Modify 6, recList ' 6 = deleteSet
recList = viewList.Fetch
Wend
viewList.CloseSet

objView = objDB.OpenView("select * from ComboBox")

' enumerate webservers on localhost and populate ComboBox tableSet
objW3SVC = GetObject("IIS://localhost/W3SVC")
lngOrder = 1


For Each objIisWebSite In objW3SVC
If objIisWebSite.Class = "IIsWebServer" Then
If LCase(objIisWebSite.ServerComment) <> "administration web site" Then
' add site name to ComboBox table (which is used by our dialog ComboBox)
Set objRecord = objInstaller.CreateRecord(4)
objRecord.StringData(1) = "WEBSITE_DROPDOWN" ' property name
objRecord.IntegerData(2) = lngOrder ' order
objRecord.StringData(3) = objIisWebSite.Name ' value
objRecord.StringData(4) = objIisWebSite.ServerComment ' text
Call objView.Execute(objRecord) ' now add the record to the table
Call objView.Modify(7, objRecord) ' (7 = msiViewModifyInsertTemporary)

lngOrder = lngOrder + 1
End If
End If
Next
Call objView.Close

Note that the value of the combobox is “objIisWebSite.Name” and you might think this is the human readable string which appears as the website name, but its not.  The name of the website is a unique number (ID) assigned to it as shown in the figure below:

image

Therefore when you want to specify where your application will be added to, you have to modify the “Default Web Site” node (which you will add as the default behaviour and put all your applications under it).  A bit counter intuitive as earlier I simply thought that instead of naming it “Default Web Site” I have to map it to my property which corresponds to the drop down list, i.e. "WEBSITE_DROPDOWN”.  But the trick is to associate the “WEBSITE_DROPDOWN” property to the “Site Number” setting in the Default Web Site node.