Archive for the ‘C#’ Category


One problem you may face is the need to check if an application is already running or not. You may not want a user to run multiple instances of an application for various reasons.

So, how does one go about doing this?

You can use the Mutex class. Yes, Mutex. While this if a funny name it does have its purpose.

To read more about Mutex, click ‘here

Basic summation of what Mutex is: A synchronization primitive that can also be used for interprocess synchronization.

So what does this mean? Basically, Mutex will provide the same functionality as the lock statement. This really means that Mutex is a bit redundant, however there is one advantage that Mutex has over lock:

Mutex provides a computer-wide lock versus just an application-wide lock.

So, this is really cool!

How will this work in our application? Let’s cut to the chase and look at code.

I have created a sample application called ThreadingConsole. My assembly and namespace are ThreadingConsole for consistency.

Now, I know you are really here to just see code that works and not read a bunch of mumbo jumbo about how it is supposed to work. Without further ado, the code:

using System;
using System.Threading;

namespace ThreadingConsole
{
    class Program
    {
        private static readonly Mutex AppMutex = new Mutex(false, "ThreadingConsole");

        static void Main(string[] args)
        {
            if(!AppMutex.WaitOne(TimeSpan.FromSeconds(5), false))
            {
                Console.WriteLine("Another instance of the app is currently running.");
                Console.WriteLine("Hit any key to exit");
                Console.ReadLine();
                return;
            }

            Console.WriteLine("Running - hit any key to exit");
            Console.ReadLine();
        }
    }
}

Now that  you have the code, you can copy and paste this into your application, build it. Navigate to your bin/debug directory. Launch the application and then launch it again. You will find that the 2nd instance will give you the proper error message and you can move on.

Exciting huh?

So, this post was not to explain the nitty gritty of what Mutex is (that is what the click ‘here’ link is for).

I hope you found this useful.

Happy programming.

So, I came across an issue today where I needed to test internal sealed classes in a separate testing project. Well, since you can’t instantiate internal sealed classes, I was in a tight spot.

So, I figured out a work around, and also discovered that there are resources out there on google that would have guided me towards this if I had just taken the time to search versus trying to figure it out on my own.

I remembered that in each project there is an AssemblyInfo.cs file. One of the assembly values is:
InternalsVisibleTo()

So, i set the following:
[assembly: InternalsVisibleTo("TestingProject.Tests")]

I compiled my project and went to my testing project. Behold, success!

I hope this helps others out there!

So, I came across the idea that I needed to come up with a way to dynamically set the where clause for a LINQ statement. There are many articles out there that give different examples of how to do this. Some show how you can pass in “string” values such as “id = 2” and then you can append your where clause this way.

Personally, I did not like any of these solutions. Granted my solution is not the first time it has been used, and I did not invent it, however I found that it works quite well and I would share with the world how to do this.

Not only am I going over how to do dynamic where clauses, I will be showing you a structure that I like to use when dealing with data and business in my applications. It provides an easy way to organize your code and when you need to make changes later, you only ever have to update a few spots.

Before we start coding and getting into the how’s, I want to make sure that you can follow along with me. To do that, we need to prepare some stuff.

If you don’t have the tools to follow along, then keep reading and you will get to the how it is done shortly.

Step 1:

We are going to create a database that we can shove a table into. I have SQL 2005 installed on my local machine.

I created a database called LINQTester, and added 1 table:

CREATE TABLE TestData

(

    NameKey INT IDENTITY NOT NULL PRIMARY KEY,

    FirstName VARCHAR(20),

    LastName VARCHAR(20)

)

We don’t need millions or records in this table, just a couple to prove a point. If you want to test performance, you can insert those records later, but performance is not the key point here (even though there is not a performance issue to really be discussed).

I am using the following insert statements to add the data:

INSERT INTO TestData VALUES ('Jason', 'Heine')

INSERT INTO TestData VALUES ('Bubba', 'Jones')

INSERT INTO TestData VALUES ('William', 'Tell')

INSERT INTO TestData VALUES ('Willie', 'Wonka')

 

So, now we have our data, we need to setup our project in Visual Studio. I am using Visual Studio 2008.

Here is the folder structure we are going to end up with (yes, yes, it may seem like a lot, but I am organizing it this way for a purpose).

If you want to go ahead and create this structure, with empty files, that will work. I will explain what each file is used for along the way.

image

We are going to start with our DBML file. Since we only have 1 table, that is all we need to add. Once you have added your table to the DBML file, make sure you build your project (this will enable the designer stuff to generate for the table).

We are going to start with the CoreConnection.cs

The CoreConnection.cs file is used for building the IDbConnection object, which will be used to physically connect to the database.

I am not going into the details of why all this works, if you need to ask questions, please do so in the comments.

Contents of the CoreConnection.cs file:

using System.Configuration;

using System.Data;

using System.Data.SqlClient;

 

namespace DynamicLinqTester.DataService.Core

{

    public class CoreConnection

    {

        public static IDbConnection GetConnection()

        {

            return GetConnection(ConfigurationManager.AppSettings["CoreDatabase"]);

        }

 

        public static IDbConnection GetConnection(string databaseName)

        {

            var builder = new SqlConnectionStringBuilder();

            builder["Data Source"] = ConfigurationManager.AppSettings["DatabaseServer"];

            builder["Integrated Security"] = true;

            builder["Initial Catalog"] = databaseName;

            builder["MultipleActiveResultSets"] = true;

            IDbConnection iConnection = new SqlConnection(builder.ConnectionString);

            return iConnection;

        }

    }

}

Once you have this, we are going to move onto the TestContextFactory.cs

The TestContextFactory.cs is just an initializer for your DataContext. This will be utilized in the BaseQuery.cs file.

Contents of TestContextFactory.cs

namespace DynamicLinqTester.DataService.Context

{

    public class TestContextFactory

    {

        public static TestDataContext CreateContext()

        {

            return new TestDataContext(CoreConnection.GetConnection());

        }

    }

}

The next thing we want to do is setup our object. Our object will be used to pass the information back to the program, and we will map the data from our table to this object.

Let’s take a look at our BaseQuery.cs file. This will be what each Query class uses to initialize the data context and dispose of it when it is done.

using DynamicLinqTester.DataService.Context;

 

namespace DynamicLinqTester.DataService.Queries

{

    public abstract class BaseQuery

    {

        public readonly TestDataContext CoreContext;

 

        protected BaseQuery()

        {

            CoreContext = TestContextFactory.CreateContext();

        }

 

        ~BaseQuery()

        {

            CoreContext.Dispose();

        }

    }

}

So, on to OTestTable.cs

Contents:

namespace DynamicLinqTester.Objects

{

    public class OTestTable

    {

        public int Id { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

    }

}

Now that we have our object, we need to create our “mapper”. The mapper is what we are going to use to say “Column 1” = “Property 1”. Doing it like this will mean you don’t need to use object initialization on your methods, and it will help reduce your code by a lot.

Open TestTableMap.cs (this is our mapper file)

Contents:

using System;

using DynamicLinqTester.DataService.Context;

using DynamicLinqTester.Objects;

 

namespace DynamicLinqTester.DataService.Mappers

{

    public class TestTableMap

    {

        public static readonly Func<TestData, OTestTable> DataToObject = mapper =>

           new OTestTable

           {

               FirstName = mapper.FirstName,

               LastName = mapper.LastName,

               Id = mapper.NameKey

 

           };

    }

}

Okay you may be wondering what all this means. If you do not understand the Func<> method, I would suggest reading up on it on MSDN. They will do a far better job then I could.

Again, the main purpose of this is to map the table to your local object.

Now, we want to move to the heart of this blog entry, the where clause.

Before we do that, look at the following LINQ query:

var query = from c in CoreContext.TestDatas

            where c.LastName == "Heine"

            select new OTestTable

                       {

                           FirstName = c.FirstName,

                           LastName = c.LastName,

                           Id = c.NameKey

                       };

This is how you would normally write your LINQ, you would have your where clause and then your object initialization. You can do it without the initialization, but you will end up with more code.

The mapper part get’s rid of the new OTestTable object. Doing so enables you to take multiple queries and use the same mapping without having to update lots of methods when you add/remove a column.

Now, what we want is something that looks like this:

return CoreContext.TestDatas.Where(whereClause)

                                .Select(TestTableMap.DataToObject)

                                .FirstOrDefault();

As you can see, we are replacing the object initialization with the TestTableMap.DataToObject. Now, what about the “whereClause”, what is that?

This is the apex of the blog entry.

Here is the full method with this LINQ statement (this goes in TestTableQueries.cs)

using System;

using System.Linq;

using System.Linq.Expressions;

using DynamicLinqTester.DataService.Context;

using DynamicLinqTester.DataService.Mappers;

using DynamicLinqTester.Objects;

 

namespace DynamicLinqTester.DataService.Queries.TestQueries

{

    public class TestTableQueries : BaseQuery

    {

        public OTestTable GetTestCode(Expression<Func<TestData, bool>> whereClause)

        {

            return CoreContext.TestDatas.Where(whereClause)

                                            .Select(TestTableMap.DataToObject)

                                            .FirstOrDefault();

        }

    }

}

Okay, again you can see we are using the Func<> again, but also we are using the Expression<>. If you do not use the Expression<> LINQ will not know how to evaluate the where clause into a SQL statement, and you will get a SELECT * FROM Table with no where clause.

So, how do we call something like this?

Open up testMethodsEngine.cs

Now add the following code:

using DynamicLinqTester.DataService.Queries.TestQueries;

using DynamicLinqTester.Objects;

 

namespace DynamicLinqTester.Business.TestMethods

{

    public class TestMethodsEngine

    {

        private readonly TestTableQueries QueryEngine;

 

        public TestMethodsEngine()

        {

            QueryEngine = new TestTableQueries();

        }

 

        public OTestTable GetTestCode(string lastName)

        {

            return QueryEngine.GetTestCode(id => id.LastName == lastName);

        }

    }

}

We are using a simple lambda expression to say Table.Column[Value] = ‘value’

If you want to add multiple statements to your where clause you can make it look like this:

public OTestTable GetTestCode(string lastName, string firstName)

{

    return QueryEngine.GetTestCode(id => id.LastName == lastName && id.FirstName == firstName);

}

Now, you control what data you bring back via your business layer. Your data layer no longer controls the business requirements. You give the business the ability to query how it needs to without dictating what the business needs to query.

Let’s open our program.cs and add some test methods:

Contents:

using System;

using DynamicLinqTester.Business.TestMethods;

using DynamicLinqTester.Objects;

 

namespace DynamicLinqTester

{

    class Program

    {

        static void Main(string[] args)

        {

            CodeSearchTest();

            Console.WriteLine(Environment.NewLine);

            Console.ReadLine();

        }

 

        private static void CodeSearchTest()

        {

            var engine = new TestMethodsEngine();

            DateTime startTime = DateTime.Now;

            OTestTable code = engine.GetTestCode("Heine");

            DateTime stopTime = DateTime.Now;

 

            TimeSpan span = stopTime - startTime;

            Console.WriteLine("Searching for Last Name 'Heine' in TestTable");

            Console.WriteLine("Time in MS:" + span.TotalMilliseconds);

            Console.WriteLine(code.FirstName);

        }

    }

}

Also, before we run this, we need to modify our app.config file to point to the proper database and server:

 

<configuration>

  <appSettings>

    <add key="DatabaseServer" value="SERVER"/>

    <add key="CoreDatabase" value="LINQTester"/>

  </appSettings>

</configuration>

When you execute your program you should see the following output:

image

Well, I hope you enjoyed this little bit of information. Feel free to ask me questions, or add comments.

Happy Coding!

The other day I had come across a problem. I needed to be able to sort one of my generic lists by several different properties.

Let us take the following code:

class Program
    {
        static void Main(string[] args)
        {
            var myList = new List<MyObject>
                                        {
                                           new MyObject{SortId = "D"},
                                           new MyObject{SortId = "B"},
                                           new MyObject{SortId = "C"},
                                           new MyObject{SortId = "A"}
                                        };

            foreach (MyObject o in myList)
            {
                Console.WriteLine(o.SortId);
            }

           Console.ReadLine();
        }
    }       

    class MyObject
    {
        public string SortId { get; set; }
    }

If you run this code you will see the following output:

image

So, we want to be able to sort this list.

The way this is normally done is like this:

myList.Sort((s1, s2) => s1.SortId.CompareTo(s2.SortId));

If you add this little bit of code right before your foreach statement you get the following output:

image

This works great. Now, we want to add a new property to our object. Let’s call is Value for simplicity.

Here is our new object:

class MyObject
    {
        public string SortId { get; set; }
        public string Value { get; set; }
    }

We are now going to update or object initialization with the new property:

var myList = new List<MyObject>
{
    new MyObject{SortId = "D", Value = "Value1"},
    new MyObject{SortId = "B", Value = "Value3"},
    new MyObject{SortId = "C", Value = "Value4"},
    new MyObject{SortId = "A", Value = "Value2"}
};

So, now we want to sort of the Value column or the SortId column.

Normally we would just add an if statement based on some parameters on which one we wanted to sort by.

Something like this (yes, this would be done a lot better if we were to pursue this avenue):

string sortBy = "Value";
            if (sortBy == "SortId")
            {
                myList.Sort((s1, s2) => s1.SortId.CompareTo(s2.SortId));
            }
            else
            {
                myList.Sort((s1, s2) => s1.Value.CompareTo(s2.Value));

            }

So, how are we going to write our sorting without all these giant If() statements in our code? I want to avoid as much code in my business logic as possible. Especially when it comes to doing if() statements.

Let’s look at the Func<,> method in c#

I am not going to go into detail on what Func really is, you can read up on it here: MSDN : Func

We are going to create an extension methos off of MyObject. This extension method will allow us to call the .Sort() directly from our object.

Let’s take a look at our method. This is the complete method which does the sort.

 

    public static class ObjectExtension
    {
        public static List<MyObject> Sort<T>(this List<MyObject> o
                                                , Func<MyObject, T> keySort)
                                             where T : IComparable
        {
            o.Sort((a, b) => keySort(a).CompareTo(keySort(b)));
            return o;
        }
    }

 

So what is happening here?

We are passing in an expression (func) which will extract the value which will be used to compare. You add the constraint where T: IComparable to allow the expression to be compared. If you do not have this you will get a compile error saying that CompareTo does not exist.

Okay, so how do I call something like this?

First, before we continue, make sure you make your MyObject class public, so your extension method will work.

    public class MyObject
    {
        public string SortId { get; set; }
        public string Value { get; set; }
    }

 

Now, we are going to update our program to call the extension method. We will have the same object initialization the only difference is we will be calling our extension method to do the sort.

static void Main(string[] args)
        {
          var myList = new List<MyObject>
                                 {
                                   new MyObject{SortId = "D", Value = "Value1"},
                                   new MyObject{SortId = "B", Value = "Value3"},
                                   new MyObject{SortId = "C", Value = "Value4"},
                                   new MyObject{SortId = "A", Value = "Value2"}
                                };

            myList.Sort(myObject => myObject.Value);

            foreach (MyObject o in myList)
            {
                Console.WriteLine(o.SortId + " - " + o.Value);
            }

           Console.ReadLine();
        }

As you can see we are calling myList.Sort() but this time we are using an expression to say, use this property to sort by.

If we run this we get the following result (which is what we want):

image

Great! We have accomplished the core of this article, which was to dynamically sort our objects based on the parameters.

Now, when you actually call your sort method, you will probably need to provide some if() statements in order to change which property you are going to pass in. The beauty in this is your client is now in control of which parameters to sort by and as the business layer, you don’t need to worry about the sorting, you just provide the functionality to sort based on whatever parameter is passed in (which falls into the Open Closed Principle, your business logic is open for extension but closed for modification).

 

One of the key problems with LINQ is you cannot do cross data context joins. Now, there is a good reason why you can’t do this using the standard LINQ framework. You can run into security issues and you can run into potentially strange data results.

Now, typically when you have multiple data contexts you are connecting to multiple databases for each context. There are some cases when you would want to have multiple data contexts for the same database.

In the example I am going to show you how you can have 2 databases, with 2 data contexts and join them together in the same query.

Before we begin, I am going to be setting up some test databases with some tables and test data. This is to show that you can actually have 2 different databases and have 2 different data contexts and join them together.

Step 1:

Creating the database:

Create database DatabaseA
GO
Create Database DatabaseB
GO

 

Now that we have our databases, we can create our tables and insert some dummy data.

Create Table DatabaseA.dbo.TableADatabaseA
(
    PrimaryKeyA INT IDENTITY(1, 1)
    , TableAValue CHAR(1)
)
GO
Create Table DatabaseB.dbo.TableBDatabaseB
(
    PrimaryKeyB INT IDENTITY(1, 1)
    , TableAJoinValue INT
    , TableBValue CHAR(1)
)
GO
INSERT INTO DatabaseA.dbo.TableADatabaseA VALUES ('A')
INSERT INTO DatabaseB.dbo.TableBDatabaseB VALUES (1, 'B')
GO

Okay great. We now have two databases, two tables and a single row in each table to work with.

If we were to run this query in management studio:

 

select
TB.TableBValue from DatabaseB.dbo.TableBDatabaseB TB
INNER JOIN DatabaseA.dbo.TableADatabaseA TA
on TA.PrimaryKeyA = TB.TableAJoinValue

We would get the result of “B” in our query results.

We want to get the same result using LINQ.

Step 2:

In Visual Studio I created a sample project which contains my 2 data contexts:

image

In my ContextA I have the following table from our DatabaseA:

image

In my ContextB i have the following table from our DatabaseB:

image

 

Step 3:

Now that we have our database and our data contexts setup, we need to write some code!

Before we get into the actual working code, let’s look at code that we think would work:

 

var contextA = new ContextADataContext();
var contextB = new ContextBDataContext();
var query = from a in contextA.TableADatabaseAs
                   join b in contextB.TableBDatabaseBs
                     on a.PrimaryKeyA equals b.TableAJoinValue
                        select b;
Console.WriteLine(query.First().TableBValue);

This code looks just fine. However, if you were to execute it, you will get the following error:

 

image

So, how are we going to fix this?

We are going to create two methods. Each method will be  returning IEnumerable<T>

Let’s create those methods so you can see what I am talking about.

Here is the code for those methods:

static IEnumerable<TableADatabaseA> GetTableA()
        {
            var context = new ContextADataContext();
            return (from t in
                        context.TableADatabaseAs
                    select t).AsQueryable();

        }

        static IEnumerable<TableBDatabaseB> GetTableB()
        {
            var context = new ContextBDataContext();
            return (from t in
                        context.TableBDatabaseBs
                    select t).AsQueryable();
        }

 

As you can see, I am returning an IEnumerable<T> but the query is being returned as AsQueryable(). This is the key, returning AsQueryable(). If you were to return as AsEnumerable() you would get the same error.

Now, for our main query:

            var query = from a in GetTableA()
                        join b in GetTableB()
                        on a.PrimaryKeyA equals b.TableAJoinValue
                        select b;
            Console.WriteLine(query.First().TableBValue);

As you can see, our tables turn into methods.

If you were to execute this you now see this, which is the result we want!

image

Congratulations! We now have a cross data context JOIN!!

Now, with this you do end up with a drawback. When it executes your queries it will execute them separately and then do the join after the queries execute. Which means you lose the lazy loading.

If you look at SQL profiler you can see this happening when you execute this query:

image

While this may not be the best practice for SQL, it does provide you with a solution to actually do a JOIN on multiple data contexts.

I hope that this helps you get a good start on how to do a cross data context join.

One of the major issues that I have come across in the past with writing tests for my application is when I get to the point where I need to test data.

There are a couple of things you can do with this.

1. You can create a data base with actual data that you can query by changing your connection string to this temporary database.

2. You can create fake data and use dependency injection to test your business logic.

First, let’s talk about creating a test database. While this is good you are relying on the fact that you actually have to be able to connect to this database. What happens when you are in a continuous integration environment and the server that does all the builds does not have access to the server with the database?

This brings us to the next topic. Fake Data!

So, some of you may be pondering what fake data really is.

What is not fake data?

Fake data is not a database in some SQL server, or Oracle if you prefer.

What fake data is.

Fake data is data that you create either in your objects or in some other static location, such as xml. I would not recommend xml, because you now have to work with opening new larger memory objects just to get your fake data.

So what does this all mean?

Okay, let’s begin with some code. It is always easier to explain a coding concept with code.

First of all, we need a base set of code to work from. I have here a really basic set of classes with methods as shown:

using System;

namespace FakeDataProject
{
    class Program
    {
        static void Main()
        {
            var myBusinessClass = new MyBusinessClass();
            MyObjectForTest result = myBusinessClass.MyMethodThatReturnsString();
            Console.WriteLine(result.Value1);
            Console.ReadLine();
        }
    }

    class MyObjectForTest
    {
        public string Value1 { get; set; }
        public string Value2 { get; set; }
    }

    class MyBusinessClass
    {
        public MyObjectForTest MyMethodThatReturnsString()
        {
            var dataLayerClass = new MyDataLayerClass();
            return dataLayerClass.MyDataLayerMethodThatReturnsString();
        }
    }

    class MyDataLayerClass
    {
        public MyObjectForTest MyDataLayerMethodThatReturnsString()
        {
            //this really calls the database 
            //(and no, this is not the fake data yet)
            //however this will give you an idea of where we are going for testing...
            return new MyObjectForTest
                       {
                           Value1 = "Some value 1",
                           Value2 = "Some value 2"
                       };
        }
    }
}

So, in this code we have the following:

MyObjectForTest – This is our generic object which we will be using to create fake data off of.

MyBusinessClass – This is our core logic.

MyDataLayerClass – Our DAL, where we are going to connect to the database.

 

If you were to copy and paste this code, it will run and you will see a result. Your result should be “Some value 1”

Okay now that all that works. We need to move into the part where we create fake data. If you noticed, we already have fake data in our MyDataLayerClass. While this is true, it is not the ultimate result we want. In reality we will have a database connection.

Now, because we want to use your favorite testing framework for this next step, your code may vary slightly from mine. I will be using NUnit and Resharper.

I have created a new class called Tester.cs

I have placed in my tester class one test with a very basic test.

using NUnit.Framework;

namespace FakeDataProject
{
    [TestFixture]
    public class Tester
    {
        private MyBusinessClass BusinessClass;
        [SetUp]
        public void Setup()
        {
            BusinessClass = new MyBusinessClass();
        }

        [Test]
        public void Length_Of_MyObjectForTest_Variable1_Should_Be_12()
        {
            Assert.That(BusinessClass.MyMethodThatReturnsString().Value1.Length == 12);
        }
    }
}

 

When you run the test, you will get a pass.

Now, we need to get down to the gritty detail on how we are going to produce fake data.

There are a few framework changes that need to happen for this.

First of all, when you write Unit Tests and when you do TDD, you should always be using Interfaces. The reason for this is because you can create fake services which inherit the same interfaces that your real service will inherit.

So, let’s change our main code to use an interface on the service.

interface iMyDataLayerClass
    {
        MyObjectForTest MyDataLayerMethodThatReturnsString();
    }

    class MyDataLayerClass : iMyDataLayerClass
    {
        public MyObjectForTest MyDataLayerMethodThatReturnsString()
        {
            //this really calls the database 
            //(and no, this is not the fake data yet)
            //however this will give you an idea of where we are going for testing...
            return new MyObjectForTest
                       {
                           Value1 = "Some value 1",
                           Value2 = "Some value 2"
                       };
        }
    }

 

As you can see, I took the code from above and just placed an interface on the data layer class.

In our business layer, we need to utilize the interface versus the class.

I went ahead and created a private interface variable and instantiated the class in the method (we will break this out later.)

    class MyBusinessClass
    {
        private iMyDataLayerClass DataLayerClass;
        public MyObjectForTest MyMethodThatReturnsString()
        {
            DataLayerClass = new MyDataLayerClass();
            return DataLayerClass.MyDataLayerMethodThatReturnsString();
        }
    }

 

At this point, if you run your test again, it will still pass. Which means we were able to refactor the core logic and our code still works.

Here is where it gets fun. We are going to use a little thing called Dependency Injection to pass in the data service into the business class. Why are we going to do this? The reason for this is so we can do several things. For one, the business layer no longer is coupled with the data layer. We can now use multiple data layers with the same interface which will help your application be a bit more portable. You can now test your business logic with a fake data service!

Here is the business layer modified to have the interface passed into the business constructor:

class MyBusinessClass
    {

        private readonly iMyDataLayerClass DataLayerClass;

        public MyBusinessClass(iMyDataLayerClass dataLayerClass)
        {
            DataLayerClass = dataLayerClass ?? new MyDataLayerClass();
        }

        public MyObjectForTest MyMethodThatReturnsString()
        {
            return DataLayerClass.MyDataLayerMethodThatReturnsString();
        }
    }

What is happening here?

We have a private variable which is the interface for the data layer.

Our constructor has a parameter to pass in the interface. Inside the constructor, we have a null check for the interface, if it is null we will instantiate a new instance of the class.

Our method now only has 1 line of code, return the result of the data layer.

Granted, our business logic will probably have more to it, but again, this is just a demo.

At this point, if you build, you are going to get an error. The reason for this is your constructor now requires a parameter.

Part of TDD and writing Unit Tests, is your tests will evolve.

Before we update our tests, we need to make our main program work. We need to update our Main() method with the new constructor:

static void Main()
        {
            iMyDataLayerClass dataLayerClass = new MyDataLayerClass();
            var myBusinessClass = new MyBusinessClass(dataLayerClass);
            MyObjectForTest result = myBusinessClass.MyMethodThatReturnsString();
            Console.WriteLine(result.Value1);
            Console.ReadLine();
        }

Now that we have done that, we can update our testing class.

Here is the code with the update:

private MyBusinessClass BusinessClass;
        private iMyDataLayerClass IMyDataLayerClass;

        [SetUp]
        public void Setup()
        {
            IMyDataLayerClass = new MyDataLayerClass();
            BusinessClass = new MyBusinessClass(IMyDataLayerClass);
        }

As you can see, we have a new interface for the data layer and in the setup we are instantiating the class for the data layer.

If you run your test, it should still pass.

Now, we finally get to the point where we can create the fake data.

Inside the tester.cs file I am going to create a new class called FakeDataService. This class will inherit the interface that we created for the real data service:

    class FakeDataService : iMyDataLayerClass
    {
        public MyObjectForTest MyDataLayerMethodThatReturnsString()
        {
            throw new NotImplementedException();
        }
    }

As you can see, we now have all the methods that our interface requires. What we want to do at this point is update our test fixture to use the new fake data service. We update the Setup() method as follows:

        [SetUp]
        public void Setup()
        {
            IMyDataLayerClass = new FakeDataService();
            BusinessClass = new MyBusinessClass(IMyDataLayerClass);
        }

Now, run your test. You will get a failure. If you get a System.NotImplementedException, then you are doing the right thing. You now know that you are  using the new fake data service instead of the real data service.

Now we need to make our test pass. Here is where the fake data comes into play.

You can do this one of a couple of ways.

The best practice is to create an ObjectMother class, which contains all your objects with “fake” data. You can create methods in your ObjectMother such as:

public static MyObject GetValidObject()

public static MyObject GetInvalidObject()

With these methods you can return an instance of that object with valid/invalid data. Each of which you can run tests against. This is important because sometimes your real data layer is going to return invalid data. Doing this will enable you to reuse that valid/invalid data for other tests.

So in this example, I will create a small ObjectMother class which we will use to get our fake data.

class ObjectMother
    {
        public static MyObjectForTest GetValidData()
        {
            return new MyObjectForTest
                       {
                           Value1 = "123456789012",
                           Value2 = "000"
                       };
        }
    }

 

In my fake data service, I will be calling the ObjectMother to get the valid data:

class FakeDataService : iMyDataLayerClass
    {
        public MyObjectForTest MyDataLayerMethodThatReturnsString()
        {
            return ObjectMother.GetValidData();
        }
    }

So, what we are doing here, is we are pretending we are connecting to a database. The object mother is the database, the fake service is the data layer and we are passing in that data layer, using Dependency Injection, into our business layer to handle our logic.

If we run our test after adding this code. It should pass.

One of the ways to know that this is working is to debug your test. When you debug you can see that when you get into your business layer, it is really using the fake data service and not the real one.

Also remember, that the main point of this is to test your business logic based on data that you would receive from the database. You don’t want to test the database to see if that works or not. Your goal should be to test the business layer and your business layer should handle if your data layer does not return valid data.

Oh boy, there have been a ton of discussions and articles about the usage of the var in c# development.

 

My perspective on this is that developers are being too dogmatic in their views when it comes to the usage of the var.

 

Okay, so what do I mean by this? Let’s play devils advocate on both sides. I am only going to give a few examples of the pro’s and con’s of the var usage. There are many articles out there if you would like to see an in depth usage of the pro’s and con’s. The point of this article is to help you be less dogmatic about the usage of var.

 

First, let’s take the “I do not support the var” approach.

 

Point 1: I think it makes the code much more difficult to read.

Point 2: The developer’s intent is not immediately obvious.

Point 3: It can be overused hence causing confusion in code.

 

Okay, now we have seen lots of points in regards to the do not support perspective, let us know look at the “I do support the var” approach.

 

Point 1: Var removes code noise.

Point 2: Var forces initializing to not null values.

Point 3: Var introduces flexibility inside the method scope.

 

 

If you really dig deep in these ideas, from both sides, you realize that both sides can be valid. Well, why don’t we take a less dogmatic approach and come up with the following points.

 

Point 1:

 

Use var when necessary. There are many scenarios where you may want to use var.

            Example:

            Don’t use var like this:

            var amount = engine.GetAmount();

            var amount = 10;

            var name = “Jason”

           

You get the picture. These examples show the un-necessity usage of var. For one, the first example shows that you have to clue what the type is unless you go into the method GetAmount(). The 2nd two are pointless because you know that name is going to be a string, you might as well just make it a string. The amount = 10, this could be an int, decimal, float or whatever. Hence, you need to have a type that indicates what that number really is.

 

            Example:

            Use var like this:

            var myList = new List<SomeObject>;

            foreach (var foo in barCollection)

           

Here you can see that you are declaring a list object, when you have a bunch of those (I think have had 10 or 12 in a row before) your code then does become unreadable. If you use var, you are giving an explicit definition to your variable, so you don’t care that you are using var. Also, why mess up your foreach with large variable names when you can declare the looping variable with a var making it much easier to read.

 

Some people will argue that putting a var in the looping variable in a foreach is not something you want to do. This is up to your personal discretion. Use it wisely.

 

 

So, back to the original point of this blog about being too dogmatic about the usage of var. We all need to sit back and look at the big picture. We need to use var when it is needed, and not use it when it does not make sense. If you can be less dogmatic about your approach to the usage of var, then you will for one, become a better programmer, for two, you will get to use a powerful feature of c#.