Translate

Friday, July 25, 2014

Microsoft shims for faking methods

If you want to inject some fake code for testing, there are two ways to do it. Stubs and Shims.



Stubs can be achieved using dependency injection. Microsoft provides the unity framework to facilitate dependency injection. I personally prefer autofac for dependency injection.

If your code was not written keeping testability in mind, then you may not be able to use stubs. That's where shims come in. A shim modifies the compiled code of your application at run time so that instead of making a specified method call, it runs the shim code that your test provides. Shims are also useful when you want to fake something in a third party assembly.

Note: Fakes are available only in VS Ultimate.

In the example below, I will be testing a method that returns current year +1.

 class MyClassToBeTested
    {
        public static int ReturnCurrentYearPlusOne()
        {
            return System.DateTime.Now.Year+1;
        }
    }

As you can see, if I want System.DateTime.Now to return 1/1/2000, its not possible. Unless I fake it.

This is how you do it

1>Add references to 
  • c:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\PublicAssemblies\Microsoft.QualityTools.Testing.Fakes.dll
  • c:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\PublicAssemblies\Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll
2>Right click on the reference System and click "Add Fakes Assembly"





































3>Paste the code below into a class file

using System;
using System.Fakes;
using Microsoft.QualityTools.Testing.Fakes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
 
namespace ShimPlay
{
    [TestClass]
    public class ShimPlayClass
    {
        [TestMethod]
        public void TestMethod()
        {
            int nextYear = MyClassToBeTested.ReturnCurrentYearPlusOne(); //returns 2015 (current year is 2014)
 
            using (ShimsContext.Create())
            {
               //The faking happens only inside this using block
               ShimDateTime.NowGet = () => new DateTime(2000, 1, 1);
               int nextYearFake = MyClassToBeTested.ReturnCurrentYearPlusOne();//returns 2001
            }
        }
    }
 
    internal class MyClassToBeTested
    {
        public static int ReturnCurrentYearPlusOne()
        {
            return DateTime.Now.Year + 1;
        }
    }
}


Thursday, July 24, 2014

Entity Framework 5 tutorial (Introduction to Entity framework 5 for beginners)

For this example, I will be accessing a SQL table called person which looks like this













  Id int  
FirstName varchar(MAX)  
LastName varchar(MAX)  
Address varchar(MAX)  
Age int  

I have set the primary key on the id column.

In this example I will first perform a select,update, insert and delete in the old fashioned way using ado.net. Then I will perform the same actions using Entity Framework 5. I will be doing all this in a console application.


CRUD operations using ADO.net

Add this to your console application's app.config inside the configuration element. (Replace appropriate values

  <connectionStrings>
    <add
      name = "ConnString"
      connectionString = "Data Source=myServerName; Initial Catalog=myDatabaseName;Integrated Security=False;User ID=myUserName;Password=myPassword"
      providerName = "System.Data.SqlClient" />
  </connectionStrings>

Add to your project a reference to the System.Configuration.dll

This is how my console application solution looks like














Given below is the code

Program.cs

namespace EntityPlay
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var dataAccess = new DataAccess();
 
            //select
            Person person = dataAccess.GetPerson(1);
 
            //update (change his age to 60)
            person.Age = 60;
            dataAccess.UpdatePerson(person);
 
            //Insert John Doe 
            var newPerson = new Person {FirstName = "John", LastName = "Doe", Address = "CT", Age = 28};
            dataAccess.InsertPerson(newPerson);
 
            //Delete person with id 5
            dataAccess.DeletePerson(5);
        }
    }
}



Person.cs


namespace EntityPlay
{
    public class Person
    {
        public int Id { getset; }
        public string FirstName { getset; }
        public string LastName { getset; }
        public string Address { getset; }
        public int Age { getset; }
    }
}

DataAccess.cs


using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
 
namespace EntityPlay
{
    public class DataAccess
    {
        private readonly string _connectionString = ConfigurationManager.ConnectionStrings["ConnString"].ToString();
 
        //SELECT
        public Person GetPerson(int id)
        {
            var person = new Person();
            using (var conn = new SqlConnection(_connectionString))
            {
                string commandText = @"SELECT * FROM Person WHERE Id=" + id;
 
                using (var cmd = new SqlCommand(commandText, conn))
                {
                    cmd.CommandType = CommandType.Text;
                    conn.Open();
                    SqlDataReader reader = cmd.ExecuteReader();
 
                    if (reader.Read())
                    {
                        person.Id = id;
                        person.FirstName = reader["FirstName"].ToString();
                        person.LastName = reader["LastName"].ToString();
                        person.Address = reader["Address"].ToString();
                        person.Age = Int32.Parse(reader["Age"].ToString());
                    }
                }
            }
 
            return person;
        }
 
        //UPDATE
        public void UpdatePerson(Person person)
        {
            using (var conn = new SqlConnection(_connectionString))
            {
                string commandText =
                    String.Format(
                        @"UPDATE Person SET FirstName='{0}', LastName='{1}', Address='{2}', Age={3} WHERE Id={4}",
                        person.FirstName, person.LastName, person.Address, person.Age, person.Id);
 
                using (var cmd = new SqlCommand(commandText, conn))
                {
                    cmd.CommandType = CommandType.Text;
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
            }
        }
 
        // INSERT
        public void InsertPerson(Person person)
        {
            using (var conn = new SqlConnection(_connectionString))
            {
                string commandText =
                    String.Format(
                        @"INSERT INTO Person (FirstName, LastName, Address, Age) VALUES ('{0}','{1}','{2}',{3})",
                        person.FirstName, person.LastName, person.Address, person.Age);
 
                using (var cmd = new SqlCommand(commandText, conn))
                {
                    cmd.CommandType = CommandType.Text;
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
            }
        }
 
        //DELETE
        public void DeletePerson(int Id)
        {
            using (var conn = new SqlConnection(_connectionString))
            {
                string commandText = String.Format(@"DELETE FROM PERSON WHERE Id=" + Id);
 
                using (var cmd = new SqlCommand(commandText, conn))
                {
                    cmd.CommandType = CommandType.Text;
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
            }
        }
    }
}

Now lets see how we can do the same operations doing entity framework

CRUD operations using Entity Framework

Follow these steps

1>Add entity framework 5 to your project using the nuget command

Install-Package EntityFramework -Version 5.0.0

2>Add an entity DataModel (this can be thought of as the code representation of your database)



Select  generate from database in the next screen and click next and follow the instructions. Accept all the default settings. On the screen where we select tables, I just selected the Person table. I set my model namespace as PlayEntities.


This is how my code in the Program.cs looks like now

using System.Linq;
 
namespace EntityPlay
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Person person;
            using (var context = new PlayEntities())
            {
                //select
                person = context.People.First(p => p.Id == 1);
 
                //Update
                person.Age = 60;
                context.SaveChanges();
            }
 
 
            //Insert John Doe 
            var newPerson = new Person {FirstName = "John", LastName = "Doe", Address = "CT", Age = 28};
            using (var context = new PlayEntities())
            {
                context.People.Add(newPerson);
                context.SaveChanges();
            }
 
 
            //Delete
            using (var context = new PlayEntities())
            {
                Person deletePerson = context.People.First(p => p.Id == newPerson.Id);
                context.People.Remove(deletePerson);
                context.SaveChanges();
            }
        }
    }
}

As you can see, once you set up the DataModel, you just need to work with the model. You don't need to worry about writing the lower level code that actually persists data it into the database.

Friday, July 11, 2014

Private ip addresses

The following range of ip addresses are reserved for use within your LAN (local area network). Nothing on the internet can have these ip addresses.

10.0.0.0        -   10.255.255.255
172.16.0.0    -   172.31.255.255
192.168.0.0  -  192.168.255.255
169.254.0.0  -  169.254.255.255 (Reserved for automatic private ip addressing)

When you send a message to one of these ip addresses, if that  address doesn't exist within your network, then that host is considered unreachable. Your NAT server will not attempt send out a request to this ip, out into the internet.