Unit Testing / Mocking Techniques

Introduction to Unit Testing Unit Testing The primary goal of unit testing is to take the smallest piece of testable software in the application, isolate it from the remainder of the code, and determine whether it behaves exactly as you expect under various conditions. Benefits Unit testing has proven its value in that a large percentage of defects are identified during its use. If you detect and solve bugs closer to the time they are introduced, it’s a lot faster than having to locate, debug, and resolve a bug in the future. You know that your code works as you expect it to work. With unit tests in place, you know that your foundation code is dependable. It’s a good way to test first hand how your API is going to be used. Unit Testing verses Integration Testing The difference between unit testing and integration testing is important to recognize. What is a unit test? A unit test is code that tests one single method or function and checks … [Read more...]

How to automate trimming strings in Entity Framework

When working with legacy data where the data being loaded into SQL server tables contains trailing spaces, the trailing spaces will remain in the fields regardless of whether the fields are varchar  This poses problems when doing compares or extracting data to files as you may not get the results you are looking for. One solution would be to add a trim to each field where this occurs.  This will result in having trims scattered all over your code base. Another and better solution would be to add an interception for Entity Framework that will trim all fields of certain data types. String Interceptor class As you can see, this will trim fields of types nvarchar, varchar, char, and nchar.  In the SQL generated, it will add a LTRIM and RTRIM to each field. To implement this interceptor, you just need to register it in a separate class within the same assembly. I found this solution based on Rowan Miller's EF6.1–Workaround Trailing Blanks Issue In String Joins … [Read more...]

NHibernate/DAO Unit testing

Unit Testing with using NHibernate and Data Access Objects [TestClass] public class AccountTest { private DATestHelper<CustomerDAO, CustomerDE> dh = new DATestHelper<CustomerDAO, CustomerDE>(); private DATestHelper<ProductDAO, ProductDE> dhProduct = new DATestHelper<ProductDAO, ProductDE>(); [TestInitialize()] public void TestInitialize() { dh.Init(); dhProduct.InitJoinSession(dh.session); } [TestCleanup()] public void TestCleanup() { dh.Cleanup(); dhProduct.CleanupJoinedSession(); } [TestMethod] public void GetAccountById() { CustomerDE c = dh.dao.FindById(1231); Assert.IsNotNull(c); } [TestMethod] public void GetProductByCode() { … [Read more...]

Getting started with Ionic Framework

Ionic is a framework for developing hybrid mobile apps using modern web technologies.  One of the benefits for creating mobile apps using ionic framework is you have one common code base. Ionic Command Line Reference start - starts a new Ionic project server - starts a local development server.  It has a live reload feature - file system watcher to where it refreshes the browser automatically. Platform - configure platform targets Build - locally build app for a platform Emulate - emulate app in simulator Run - runs app on device Installations Install node.js run from the command line (admin mode) npm install ionic -g npm install cordova -g -g is a switch for global Installations for Android and iOS. Depending on your preferences, you can install a text editor like Notepad++ or Sublime Text.  Or if you prefer to use Visual Studio, you can install the tools for Apache Cordova as follows: Visual Studio 2015 Install Tools for Apache Cordova … [Read more...]

Application Configuration Settings

One of the most common ways to store application setting is in the config file.  Below I will show examples of how to store configurations and their retrieval. AppSettings and ConnectionString Sections Include the appSettings and/or connectionStrings sections in  .config file for retrieval from your application. <?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <add key="MySampleKey" value="Sample value" /> </appSettings> <connectionStrings> <add name="DataSource" connectionString="Server=MyDevServer;Database=Northwind; Integrated Security=true;" providerName="System.Data.SqlClient"/> </connectionStrings> </configuration> C# code for getting the values var appsettingValue = ConfigurationManager.AppSettings.Get("MySampleKey"); var connectionStringValue = ConfigurationManager.ConnectionStrings["DataSource"] … [Read more...]

Personal Web Site hosting with Internet Information Services (IIS)

A lot of times working in development, you inherit code and never get the benefit of learning how things are configured and/or setup.  You just follow the patterns that are already presented within the code base.  But a while back, I worked with a developer who taught me the value of taking the time to learn to configure things on my own.  You learn so much more when you understand how things work from scratch. Even though there are many cheap hosting sites out there, I still have some test web site projects that I setup on my own personal web server.  To get started, you just need to register a new domain name with a registration service like namecheap and have a computer with IIS installed to use as your server. Configuring A record After registering your domain with your DNS provider, create an A record that resolves to your public IP address.  You can find out what your public IP address is whats my ip Example configuration with namecheap Port Forwarding Depending on … [Read more...]

Entity Framework cloning

On a recent project, I had come across the need to copy an existing EF Entity.  Upon my research, I found several ways to accomplish this task.  One way is to create a new object and manually assign the property values using the existing object values.  You can also use some kind of mapping utility if it supports deep copying.  However, I will demonstrate two alternative ways to clone an Entity object using EF techniques. Disable EF Tracking When you are retrieving an entity or entities from a dataset, you can tell Entity Framework not to track any of the changes that you are making to that object and then add that entity as a new entity to the dataset.  With using .AsNoTracking, the context doesn't know anything about the existing entity. var entity = context.MyDataSet .AsNoTracking() .FirstOrDefault(e => e.Id == 1); context.MyDataSet.Add(entity); context.SaveChanges(); You can also include child entities as well var entity = … [Read more...]

Global Data

Global data is accessible anywhere in a program.   Using global data is riskier than using local data. Here are some common problems with using Global Data: Problems with Global Data Unexpected changes to global data.  Since global data can be accessed anywhere, it can also be changed anywhere without the intent of doing so. Cannot concentrate on only one routine.  You have to concentrate on one routine and every other routine that uses the same global data. It's difficult to modularize your application. Usage of Global Data There are some situations when using global data is ok.  For example, configuration data is often used for an application using variables that you may want to change without recompiling and redeploying your code.  You can store application or user settings in a config file, database or windows registry. General Guidelines Create global variables only when you need to.  Always start with creating local variables first and expand scope as necessary. … [Read more...]

ASP.NET WebForms vs MVC

ASP.NET Web Forms and MVC both have their pros and cons.  Below I have them outlined. ASP.NET Web Forms Web Forms is a visual approach for web development using a drag-n-drop,  event-driven model. Advantages Rapid Application Development (RAD) Feature-rich server controls Data binding Higher level of abstraction over a stateless web.  Simulates statefulness with support for ViewState. Smaller learning curve for WinForm developers Disadvantages Undefined Application Architecture with lack of Separation of Concerns (SoC) Limited control over HTML Complicated page life cycle with performance issues Hard to keep up with fast evolving web platforms without expensive 3rd party control updates or waiting on Microsoft updates Not a good technology for designers who like working with HTML directly Limited support for testing ASP.NET MVC MVC is a framework for building web applications using the Model-View-Controller architectural pattern.  This … [Read more...]

Onion Architecture

Although there is no single silver bullet for every solution, most developers get locked into an architecture that doesn't scale and changes becomes difficult and slow as the system grows. Onion Architecture promotes a separation of concerns and a decoupled application.  Loose coupling makes it easier to upgrade or replace components without affecting other parts of the system. This architecture is best suited for complex behavior and long-lived business applications. It may not be feasible for small websites. Traditional Layered Architecture Each layer depends on the layers beneath it and every layer will depend on some common infrastructure and utility services.    Problems with Traditional Architecture Application is built on top of specific technologies that are sure to change Business logic is commonly added to the UI layer Transitive dependencies: makes it easy to take a dependency without putting much thought into it, and now it’s all over the code … [Read more...]