Translate

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

Monday, 9 April 2018

Explicit interface method - C#

Note: Putting the angular brackets < and > in a blogger post is more difficult than generics !

Continuing with generics, one of  my favorite language features, but this time in C#, the more dynamic of generic implementation in all programming languages, the premise, again from an example from Stackoverflow, is that there are two interfaces, IEquipment and 
IEquipmentDataProvider, with the latter providing for a generic method, GetEquipment, that returns a type of IEquipment.   

The question being on Stackoverflow ie., whether 
IEquipment
GetEquipment<E>(string Path) where E : IEquipment, new();

is correct or should there be an alternate way of working on the intent? 

An intent is what an interface is about and so when a constraint is declared on a generic method, or a normal method, the expansion of the constraint at implementation is what reveals the design of the intent. In this instance, it is a constraint that says all implementing classes must be of type 
IEquipment (
where E : IEquipment) and should have a parameterless constructor - , new().

So, what does it mean as a design when the interface IEquipmentDataProvider declares it like so,

public interface IEquipmentDataProvider
{
  IEquipment GetEquipment<E>(string Path) where E : IEquipment, new(); 
} 


public interface IEquipment{

}
public interface IEquipmentDataProvider:IEquipment
{
  IEquipment GetEquipment<E>(string Path) where E : IEquipment, new();
}
public class Equipment:IEquipment{
public Equipment(){

}
public IEquipment GetEquipment<E>(string Path){
Equipment eqp=new Equipment();
IEquipment ieq=(IEquipment) eqp;
return ieq;
} 
}

public class EquipmentDataProvider:IEquipmentDataProvider{
public EquipmentDataProvider(){

}
public IEquipment GetEquipment<E>(string Path){
EquipmentDataProvider eqp=new EquipmentDataProvider();
IEquipmentDataProvider iedp = (IEquipmentDataProvider) eqp;
return iedp;
}
public static void Main(){
IEquipmentDataProvider da=(IEquipmentDataProvider)new EquipmentDataProvider();
IEquipment eq = (IEquipment)da.GetEquipment<Equipment>("somepath");
System.Console.WriteLine(eq);
}
}

For the above code, the compiler rejects the interface implementation because E cannot be expanded into a type conforming to the constraints because a type of IEquipment does not exist with a parameterless constructor and a corresponding GetEquipment method. ie., had the IEquipment interface declared the GetEquipment method in it instead of the IEquipmentDataProvider, the error would have been for IEquipment because the implementing class, Equipment, too, has not implemented the method as an interface method!!


It can be quite vexing if one does not know C# well, which has a feature where a method can be explicitly defined so that the interface implementation conforms to what the compiler expects.

This means that you simply qualify the method with the interface name prefixed, like so:

public IEquipment IEquipmentDataProvider.GetEquipment(string Path){

}

But since it is an explicit method definition, the compiler throws an error that the public modifier cannot be applied on it!


Because it is typed specifically as an interface method! Cool, isn't it!?

Modify the signature of the method and the complete code is as below:

public interface IEquipment{

}

public interface IEquipmentDataProvider:IEquipment
{
  IEquipment GetEquipment<E>(string Path) where E : IEquipment, new();
}
public class Equipment:IEquipment{
public Equipment(){}
public IEquipment GetEquipment<E>(string Path){
Equipment eqp=new Equipment();
IEquipment ieq=(IEquipment) eqp;
return ieq;
} 
}
public class EquipmentDataProvider:IEquipmentDataProvider{
public EquipmentDataProvider(){}
IEquipment IEquipmentDataProvider.GetEquipment<E>(string Path){
EquipmentDataProvider eqp=new EquipmentDataProvider();
IEquipmentDataProvider iedp = (IEquipmentDataProvider) eqp;
return iedp;
}
public static void Main(){
IEquipmentDataProvider da=(IEquipmentDataProvider)new EquipmentDataProvider();
IEquipment eq = (IEquipment)da.GetEquipment<Equipment>("somepath");
System.Console.WriteLine(eq);
}
}

and, the output, even though the method returns an IEquipment type is actually an EquipmentDataProvider type!!



Happy C#-ing and generic interfacing, whatever may be the constraints!

Monday, 25 August 2014

What to Unit test?

Going by the book is not really encouraged in today's wildly advancing technology world. If you, do, it will most probably leave you staring at the behinds of many. :)

Best way to keep yourself ahead is to be really good in your skill set; if it is a programming language, be on top by participating in discussion forums and communities. This will help knowing about scenarios that may never appear in your own project or lifetime.

Close to what I am getting at is this definition of unit tests by Martin Fowler -
Like most software development terminology, however, it's very ill-defined, and I see confusion can often occur when people think that it's more tightly defined than it actually is. 
First and foremost,  what to unit test depends on your commitment to testing. If you are very committed then chances are that your code coverage will be good. But over and above this,  you also need the skill with the unit test tool. For instance, the most common statement possibly used by almost all programmers across the world is the if (!fileExists) or within a try...catch block.

Is this statement testable? Should it be tested? To answer the second question first, the reason the answer is 'Yes' is because the line of code is expected to throw many exceptions -  DirectoryNotFoundException, FileNotFoundException and (yes) etc...So, the first question becomes important - is it testable?

Again, the answer is 'Yes' (left out italicizing it to make it more interesting! :)) but if you really do not know any syntax of existing unit test tool, how to write the test?

This question has always seemed important to me (to make a programmer move from the "Code-first syndrome" to a "Test-first-and-let-the-test-tell-you-what-code-to-write avatar") and so, I decided to list (well, sharing just one technique now (how to get and test a list of files from the file system in a unit test)...will share more later) here some of these common scenarios.

Aside from helping the code achieve the necessary quality benchmarks, unit tests should also be efficient and lean so that it does not weigh down the overall build or CI framework.

So, to write a unit test in the 'file exists' scenario,

1. If not file exists

Scenarios - as many as there are files (wild possibilities! :)) in a specified directory.

So, the unit test will want a list of files against which to test for some criteria.

The code will be something like this -

using System.Collections.Generic;
using System.Linq;
using System.IO;
namespace NUnit_Tests
{
    public class ClassUnderTest
    {            
        public List getListOfFiles()
        {
            string[] filePaths=null;
            filePaths = Directory.GetFiles(@"c:\cambridge\");
            return filePaths.ToList();
        }
    }
}

In  NUnit, here is an example of how to test the method most efficiently and ALSO in such a way that maximum scenarios can be tested with this approach !!

using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
namespace NUnit_Tests
{
    [TestFixture]
    public class TestClass
    {
        ClassUnderTest objInstance;
        string[] filesToExist = { "abc.jpg", "a.htm" };
        [Category("LongRunning")]
        [Test]
        public void LongRunningTest([ValueSource("Files")] string filePath)
        {
            Assert.That(Files.ToList().LastOrDefault(),Is.EqualTo("zzz.jpg"));
        }

        private IEnumerable Files
        {          
            get
            {
                objInstance = new ClassUnderTest();
                return objInstance.getListOfFiles();
            }
        }
    }
}

The snapshot below (before refactoring class names) shows the number of scenarios (equivalent of unit tests / asserts in NUnit or unit testing tools) that are now possible with this approach.



For example, you could test if the path is returned correctly with Is.SamePath or can test the number of files existing or if a particular file has a required extension and the possibilities are endless.



Friday, 21 March 2014

Holi Hai ! :) List of Colors - C#

Working with colors is always fun but for that you must have the colors first.

It is like an old joke of mine -

To be or not to be a Macbeth is not the question; the real question is, Lady Macbeth has to be for Macbeth to be or not to be!

So, when I ventured to have a user select a color from a drop-down list for a software module, I was a little surprised (like the cat in the tree on seeing a dog climbing up to say hello to her) that it was not as simple as that.

Lady Macbeth may have known how to poison her husband but she had the poison and that is the crux of the matter - a resourceful woman, for her times!

Then I chanced upon the fact (Google search is almost a fact now) that Reflection (as in System.Reflection) had the solution but the real problems are faced only when you work towards the solution.

Lady Macbeth, too, must have thought it would be hunky-dory all the way until she found  that she really could not taste the poison herself to know what quantity to give to Macbeth ! :D

It is not as if she had to mix Coke or Pepsi with some other drink - she really could not know the taste of poison so, how could she ensure that her prey, her husband, would not find it distasteful and throw it away before drinking it?

The problem is that System.Drawing.Color is not really an enumeration that can be enumerated upon as it does not have a colors collection! So, how to compare the color values after the user inputs the color, when asked "Tippi, tippi, tap, what color do you want?" ?

The solution is to compare the name of the colors by storing the 'reflected' colors into an array of strings and then compare using a foreach loop to match the selected color.

Below is the code:

public class MyColorList{

private string[] colors = null;
private string colorSelected = null;

            private void listAllColors(){
                int colorIndex = 0;
                System.Type colorType = typeof(System.Drawing.Color);
                System.Reflection.PropertyInfo[] colorInfoList =                                                                                               colorType.GetProperties(System.Reflection.BindingFlags.Static |
                    System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Public);

                colors = new string[colorInfoList.Length];

                foreach (System.Reflection.PropertyInfo propertyColor in colorInfoList) {
                    colors[colorIndex] = propertyColor .Name ;
                    colorIndex++;
                }
            }
            private string getColor(string colorName)
            {
                foreach (string color in colors)
                {
                    if (colorName.ToLower() == color.ToLower())
                        colorSelected= color;
                }
                return colorSelected;
            }
}
// Method Calls
            listAllColors();
            currentColor = getColor(ColorAsString);

(c) Of course, needless to say, what happened between Lady Macbeth and Macbeth was their own private affair and none of the world's business but because Shakespeare disagreed with the view that I thought of highlighting it, safe with the knowledge that it was probably not as private as the English Royalty would have it, if it was discussed so vividly in public.

Friday, 21 June 2013

A UI notification technique - Exceptions or an event or as both (C#)

Just knowing MVC as defined in the books and arguing over it does not make any sense, does it?

It is when you know how to put the pattern to practise that will satisfy you that you know MVC or any design pattern/architecture and this is where most of the patterns example fail to do (believe me, most of the examples that abound 'are meant' to make sense to only similar, like-minded people (not necessarily to mean technically oriented)...;P here is a simple step-by-step example on how to simplify your UI notifications (not necessarily the heavyweight, 'technical' way).

Simply put, a front-end (since this is in C# - a Windows Form), a business layer (BusinessClass.cs) and a database class. (DataClass.cs)

Let us call it as an Orders utility with one of the specs, "Log as error and display on the user's error log so that the user can copy/paste it to a text editor, if no order is present in the results returned from the database query.

Now, let us implement this spec.

What are the mechanisms that you have? An exception? But this is no exception, in the true sense of the word. So? Return a resultset that if contains no rows satisfies our need.

Before we go further, let me tell you that you should have - knowledge of creating custom exceptions, how to use/create custom event handlers, the 3.5 way. To continue...

Exceptions

Exceptions, in programming, are any deviations, during the normal execution of a program, that need to be either taken care of or  dealt with in some way to enable graceful execution  of the software program.

An exception, in C#, is implemented as a base class called System.Exception and when it occurs is handled by the CLR (Common Language Runtime). This means that any object, let us  say the BusinessClass or DataClass, in our  example scenario, if does not handle the exception through the "try...catch..finally" mechanism, will throw the exception all the way up the  stack. So, if the DataClass was to throw an exception, it will be handled by the  preceding class and since the preceding objects cannot handle exceptions of other objects can only handle it through the base Exception class or not at all, in which case the program will terminate with a runtime exception!

But, if handled as a base System.Exception, our requirement of having to inform the user as to what kind of an exception it is cannot be satisfied because, as mentioned in the previous paragraph above, other objects cannot handle other objects exception. In simple terms, this means if "Object A" throws a "SQLConnection error", Object B can handle it as

SqlConnection conn=new SQLConnection(connectionString);
try{
conn.Open();
}
catch (SQLConnection sqlc){

}
finally{
conn.Close();
}

only if SQLConnection is a type of an Exception or, in programming terms, derives from System.Exception as shown below,

public class SQLConnection : Exception{
public SQLConnection(string exceptionMessage):base(exceptionMessage){
}
}

Hark back to the beginning of this post. Is "Log as error and display on the user's error log so ..." an exception ? No. It is a custom exception. So, we handle it by defining a custom exception class called "NoOrdersException" as below.

using System;
// The class
public class NoOrdersException: Exception{
// the data that he exception will return as a string
private string stringMessage="Default message";
// the constructor of the exception class that will pas the message to the base exception class
// and initialize this class' message
public NoOrdersException(string exceptionMessage):base(exceptionMessage){
stringMessage=exceptionMessage;
}
// the property of the class that will return this exception message that will override the base Message
//  property
public override readonly string Message{ get{return stringMessage;}}
}

Does this solve our requirement completely? No. because the program still has to notify the user. This can be done only through the UI (the Window on which the user awaits the result).

But, the front-end, the user input screen has nothing to do with the database class that interacts with the database. All it needs to know is how to pass the input from the user and receive the result.

Another problem that you will tackle is to understand what this custom exception is meant for; as you know, exceptions can be thrown and there is an inbuilt mechanism to handle exceptions but "NoOrders" is not really an exception in the execution process of the application rather, it is an exception in the data flow. You can understand it as, when you dip your hand inside a Popcorn bag but find the bag is empty or "NoPopcorns".

As of now, the above translates into a design like


with the BusinessObject class not doing anything. Do we really need the class in the design?

Yes, because if we define business rules in either the view or the data object, it is a deviation of OO principles - a View's purpose is just to enable correct user interaction and the data class to enable data related transactions or actions. Another reason why a separate Business Object class makes sense is because business rules may change as per market or client or customer or other needs and keeping it as separate logical unit makes sense.

All this is common knowledge so what does MVC or this post aim to provide as a value add-on?

As per the previous analysis on why we need the BusinessObject, let us modify the code to use this class to to establish the business rules with the design representing the code as below.


This design represents our requirement to notify the UI in the event of "NoOrders" correctly but is not a correct representation of the code.

It ia contrived because as per programmatic rules, a return value of a called method can only be returned to the calling object so the design representing the code should actually look like below, which it does.



This design represents the code (DataClass and the FormClass) correctly but is there a way to verify that  it is correct and not contrived? Yes, by verifying it through tests, requirements and performance but right now, let us re-look at the problem - throwing a custom exception that is not an exception. Why do we need to do it? Because it is the simplest mechanism to notify the UI from an object that is not known to it, as shown above. And to accomplish this in the OO way, we will use an event.

Event and Event Handlers

        private void OnNoOrdersErrorEvent(object sender,ErrorEvent ev)
        {
            txtErrorLog.Text=ev.errorMessage;
        }
        public event myEventHandler<ErrorEvent> ErrorLogEvent;
        delegate void myEventHandler<T>(object sender, ErrorEvent ev);

with the ErrorEvent defined as below:

 public class ErrorEvent : EventArgs
    {
        string eventMessage;
        public ErrorEvent(string evMsg)
        {
            eventMessage = evMsg;
        }
        public string errorMessage
        {
            get
            {
                return eventMessage;
            }
        }
    }

The parameter is the 3.5 version that is simpler than the previous way of handling events though you still need to wire up the event with the event handler as earlier:

        private void Form1_Load(object sender, EventArgs e)
        {
            ErrorLogEvent += new myEventHandler(OnNoOrdersErrorEvent);
        }

Now, let us look at how the data class notifies the "NoOrdersException."

    public class DatabaseActions
    {
        private static SqlConnection sqlConnection;
        private static SqlCommand sqlCommand;
        private static SqlTransaction sqlTransaction;
        private static DataSet dSet;
        private static int businessRule;
        private static DataView dView;
        public static void FetchOrderTransaction(string sqlQuery)
        {
            dSet = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter(sqlQuery, sqlConnection);
            da.SelectCommand.Transaction = sqlTransaction;
            da.Fill(dSet, "OrderDetails");
            EnumerableRowCollection<DataRow> ordersQuery = from row in dSet.Tables["OrderDetails"].AsEnumerable()
                                                           
                                                            orderby row.Field("OrderNumber")
                                                            select row;
            DataView orderDetailsView = ordersQuery.AsDataView();
            if (orderDetailsView.Count <= 0)
            {
                sqlConnection.Close();
                throw new NoOrdersException("No order exists!");
            }
            else
            {
                dView = orderDetailsView;
            }
        }
        private class NoOrdersException : Exception
        {
            private string msg;

            public override string Message
            {
           get 
           { 
            return msg;
           }
            }        
            internal NoOrdersException(string msgException)
                : base(msgException)
            {
                msg = msgException;
            }

        }

...
}

Much of the code above is meant for the example purpose and can be used with your own database as is

The question now is, why can we not raise the noOrdersEvent directly from here? 

The reason is - design. 

The exception or the event of no orders occurs in the data class and the result is subscribed by the UI class. If we raise the event from the data class, the design will look like


Not very elegant because there is another flow for the orders present, which will mean that the data class becomes attached to two objects. What is wrong in doing so? It will mean that testing the data class will be difficult.

So, either we declare the event in the UI class and raise the event from the data class but for which we need a handle to the UI in the data class (totally unnecessary) or just throw the exception from the data class, not handle it anywhere till it reaches up the stack to the UI class and then raise the event!

But why raise an event, when we already have the "catch..." mechanism? Because there could be another data flow exception, "MissingOrders" and because, the exception caught in the UI class will be of the base Exception type, the UI class will have no way of knowing which kind of exception occurred, plus because 
neither being exceptions may need to be handled in their own way.

But more importantly, other factors like thread safety, testability and simplicity in design are the real reasons!

An artist's impression of how it looks from the outside - only representative. :D


More to follow...and Webbased MVC and the challenges that MVC solves

Tuesday, 18 June 2013

A simple MSMQ example

You can consume this class from a main method or for a unit test.

using System;
using System.Messaging;

   public class QClass
    {
        private string qPath;
        MessageQueue mq;
        public QClass(string queue_Path)
        {
              qPath = queue_Path;
        }
        MessageQueue queue = null;
        private bool LoadQueue()
        {
            bool b=false;
            if (!MessageQueue.Exists(qPath))
            {
                try
                {
                    mq = MessageQueue.Create(qPath, true);
                    b = true;
                }
                catch (Exception ex)
                {
                    b = true;
                }
            }

            return b;
        }
        public bool SendMessageToQueue(string msg)
        {
            int msgCount = 0;
            MessageQueueTransaction mtx = new MessageQueueTransaction(); // Use for transactional q's
            string labelMessage = "Queue Loaded ";
            Message mesg = new Message();
            mesg.Body = "Hello world";
            mesg.Label = "Label 1";

            bool b = false;
            b = LoadQueue();
            if (b == false)
            {
                mq = new MessageQueue(qPath);
                try
                {                  
                    mq = new MessageQueue(qPath);
                    if (mq.CanWrite)
                    {
                       // mtx.Begin();
                        try
                        {
                            mq.Send(mesg, MessageQueueTransactionType.None);
                         //   mtx.Commit();
                            b = true;
                        }
                        catch (Exception ec)
                        {
                            //mtx.Abort();
                        }
                    }
                }
                catch (Exception ex)
                {
                    b = false;
                }
            }
                return b;
        }
        public Message readReceive()
        {
            Message m1=mq.Receive();
            return m1;
        }
    }