Unit Testing stack for C#/Visual Studio

After spending some time on digging through unit testing components, I ran into a setup I am finally happy with. This consists of:

https://github.com/AutoFixture – acts as DI container/object factory, significantly improving unit test maintainability

https://github.com/moq – awesome mocking framework, fully integrated with AutoFixture

https://www.nuget.org/packages/SemanticComparison – excellent utility for comparing instances

https://github.com/shouldly/shouldly – great for simplifying assertion statements

https://github.com/xunit/xunit – superb unit testing framework, supporting parameterized tests, multiple test executions and much more

Although each utility is great on it’s own, when combined together, this stack significantly reduces amount of testing code.

Below I include sample config file with latest versions of all packages.

<?xml version="1.0" encoding="utf-8"?>
<packages>
    <package id="AutoFixture" version="3.50.2" targetFramework="net461" />
    <package id="AutoFixture.AutoMoq" version="3.50.2" targetFramework="net461" />
    <package id="AutoFixture.Idioms" version="3.50.2" targetFramework="net461" />
    <package id="AutoFixture.Xunit2" version="3.50.2" targetFramework="net461" />
    <package id="Moq" version="4.1.1308.2120" targetFramework="net461" />
    <package id="SemanticComparison" version="3.50.2" targetFramework="net461" />
    <package id="Shouldly" version="2.8.2" targetFramework="net461" />
    <package id="xunit" version="2.1.0" targetFramework="net461" />
    <package id="xunit.abstractions" version="2.0.0" targetFramework="net461" />
    <package id="xunit.assert" version="2.1.0" targetFramework="net461" />
    <package id="xunit.core" version="2.1.0" targetFramework="net461" />
    <package id="xunit.extensibility.core" version="2.1.0" targetFramework="net461" />
    <package id="xunit.extensibility.execution" version="2.1.0" targetFramework="net461" />
    <package id="xunit.runner.visualstudio" version="2.1.0" targetFramework="net461" />
</packages>

 

 

 

Simplest way to restore MSSQL Server database

Here’s a simplest way I found (so far) to restore a database in MS SQL Server. First part lists “logicalnames” from the backup that you want to restore. Modify the path so it points to the actual path where your backup file is:

RESTORE FILELISTONLY FROM DISK = N'C:\[path]\[db_name_backup].bak'
 GO

This shows LogicalName and PhysicalName of the data and log backup files, which have to be used in the following script:

RESTORE DATABASE [db_name]
 FROM DISK = N'C:\[path]\[db_name_backup].bak'
 WITH FILE = 1,
 MOVE N'[data_file_logical_name]' TO N'C:\[restored_db_path]\[data_file_name].mdf',
 MOVE N'[log_file_logical_name]' TO N'C:\[restored_db_path]\[log_file_name].ldf',
 NOUNLOAD,
 STATS = 10
 GO

That’s it. Pretty simple, isn’t it?

How to delete all stored procedures from MSSQL database using cursor

Here is a code for deleting all stored procedures in SQL Server database using cursor.

DECLARE @name varchar(500)
DECLARE @sql varchar(max)
SET @sql = ''

DECLARE cur CURSOR
      FOR SELECT [name] FROM sys.procedures
      OPEN cur

      FETCH NEXT FROM cur INTO @name
      WHILE @@fetch_status = 0
      BEGIN
			SET @sql = 'DROP PROC ' + @name
			PRINT @sql
			EXEC (@sql)			
            FETCH NEXT FROM cur INTO @name
      END
      CLOSE cur
      DEALLOCATE cur

Animated iPhone-style ImageButton with Silverlight 4

In this article I am presenting a way to create animated iPhone-style ImageButton control in Silverlight 4. Button will have icon on it, rounded corners and will zoom-in/zoom-out on hover. It will be done programmatically, with very minimum amount of XAML.

I start with creating ImageButton class. I use ButtonBase as base class:

Class declaration

I want my button to contain rounded rectangle with shadow and image on it. I add these items in constructor:

Class constructor

Now my control contains rectangle and image laid out over a grid to ensure proper items positioning. Next step is to add animation to enable zoom-in/out on hovering. This can be achieved with storyboards and double animations:

Animations

To start animations I need to start animations when mouse cursor enters or leaves control:

Events

Very last step is making ImageSource property “bindable” so you can specify image from XAML. In order to do this I register new dependency property on my class:

Dependency property

The control then can be used in a following way:

Usage

And ready controls looks like this:

Final effect

 

WCF Custom tool error: Failed to generate code for the service reference.

Very recently, building multi-tier application involving Silverlight front-end inter-operating with WCF back-end, I encountered very odd, yet annoying behaviour of Visual Studio 2010. I was building new functionality using Telerik RadMap for Silverlight control that was to display some spartial data supplied by WCF service. To achieve this my Silverlight application had to reference few Telerik assemblies (Telerik.Windows.Controls.DataVisualization.dll). What is important is fact, that Service Reference for WCF service had been there already, project built and everything was working nicely, until I added extra method to WCF. After using “Update Service Reference” VS command, I started getting following error.

WCF error Screenshot no.1

Lack of further details with regards to this error and appropriate feedback from Visual Studio certainly does not help to get to the bottom of the problem, however after some investigation it turned out that one of Telerik assemblies caused this problem. When VS2010 creates service reference, default settings are that it should “reuse” all available types in reference. Excluding certain types from serialization allows service reference to be added successfully.

WCF error screen 2

I hope this helps anybody who got stuck with this problem.

SQL Data Types vs. C# Data Types

This article is just a reference of SQL Data Types to C# Data Types.

SQL Server data type CLR data type (SQL Server) CLR data type (.NET Framework)
varbinary SqlBytes, SqlBinary Byte[]
binary SqlBytes, SqlBinary Byte[]
varbinary(1), binary(1) SqlBytes, SqlBinary byte, Byte[]
image None None
varchar None None
char None None
nvarchar(1), nchar(1) SqlChars, SqlString Char, String, Char[]
nvarchar SqlChars, SqlString String, Char[]
nchar SqlChars, SqlString String, Char[]
text None None
ntext None None
uniqueidentifier SqlGuid Guid
rowversion None Byte[]
bit SqlBoolean Boolean
tinyint SqlByte Byte
smallint SqlInt16 Int16
int SqlInt32 Int32
bigint SqlInt64 Int64
smallmoney SqlMoney Decimal
money SqlMoney Decimal
numeric SqlDecimal Decimal
decimal SqlDecimal Decimal
real SqlSingle Single
float SqlDouble Double
smalldatetime SqlDateTime DateTime
datetime SqlDateTime DateTime
sql_variant None Object
User-defined type(UDT) user-defined type None
table None None
cursor None None
timestamp None None
xml SqlXml None

	

Interface vs. Abstract Class in .Net

In this article I will try to briefly explain main differences between interface and abstract class concepts in .Net. Although the differences can appear to be very subtle and little important, badly design inheritance can lead to massive problems and great mess in the code.

Abstract Class

Accordingly to MSDN abstract classes “are classes that cannot be instantiated (…), useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.”

Do declare abstract class following syntax is required:

abstract class Car()
{
    public Car() { };
    public string Make { get; set; }
    abstract public void Drive();
}

This class cannot be instantiated so following line will cause compiler throwing error:

Car a = new Car(); // this won’t compile

The only way to instantiate class Car is by creating child class that will inherit from it:

public class OffRoadCar : Car
{
    public OffRoadCar();
    public void Switch4WD(bool On)
    {
        // method code
    };
}

Because class OffRoadCar inherits from Car, following code will work:

OffRoadCar offroader = new OffRoadCar();
offroader.Switch4WD(true); // from OffRoadClass
offroader.Drive(); // from Car class

Interface

Interface, after MSDN, is a “definition that can never change after the interface definition has been released. This interface invariance is an important principle of component design, because it protects existing systems that have been written to use the interface.”

Interface cannot be instantiated, but serve as sort of pattern for derived classes, that share and implement specific features. Derived classes can also extend interface functionality, by defining extra members. Following code demonstrates sample interface:

public interface ICar
{
    string Make { get; set; }
    void Drive();
}

Because interface can serve as a “template” for series of classes, implementing it is a way of ensuring that all derived object will have set of common features. In example:

public class SportsCar : ICar
{
    public string Make { get; set; } // required from ICar
    public bool IsConvertible { get; set; } // adds extra feature
    public void Drive() // required by ICar
    { 

    };
}

public class Van : ICar
{
    public string Make { get; set; } // required from ICar
    public double LoadWeight { get; set; } // adds extra feature
    public void Drive() // required by ICar
    { 

    };
}

Because both SportsCar and Van classes inherit from ICar interface, they are forced to have common set of features (Make property and Drive() method). Thanks to that it is possible to write:

List<ICar> vehicles = new {
    new SportsCar() { Make = "Ferrari", IsConvertible = false },
    new Van() { Make = "Ford", LoadWeight = 3000 }
};

foreach(ICar car in vehicles)
{
    Console.WriteLine(car.Make);
}

Conclusion

In opposite to abstract class, interface cannot implement any default functionality in its methods. It also cannot implement default constructor. This is why we say we implement interface and inherit from abstract class.

Class may implement an unlimited number of interfaces, but may inherit from only one abstract class. A class that is derived from an abstract class may still implement interfaces.

Abstract classes and interfaces play extremely important role in programming concept called polymorphism, which in essence is “ability for classes to provide different implementations of methods that are called by the same name” (MSDN).

Resources