Category Archives: C#

Are your classes created under App_Code folder not recognized in other classes?

It is a very simple issue and i always forgot to fix it before i add any class to App_Code folder.

Problem : 

Let’s say you have a class under App_Code folder


namespace Enhancements.App_Code
{
public static class Defaults
{
public static readonly string PAYROLL_JOB = "Payroll_Test";
}
}

Now  you are trying to reference this Defaults class in some other class say webpage UI code behind class.


namespace Enhancements
{
   public partial class SqlJobManager : System.Web.UI.Page
   {
      private static string payrollJobName;

      protected void Page_Load(object sender, EventArgs e)
      {
          payrollJobName =<strong> Defaults.PAYROLL_JOB</strong>; // Defaults class is not recognized here.
      }
}

It happens due to the default build action (which is ‘Content‘) of the class added to the app_code folder.

Solution: Right click on the Class and select properties –> Advanced –> Build Action –> Select ‘Compile

Explaination:  According to MSDN documentation we can set build action for every class type we add to the solution

The BuildAction property indicates what Visual Studio does with a file when a build is executed. BuildAction can have one of several values:

None – The file is not included in the project output group and is not compiled in the build process. An example is a text file that contains documentation, such as a Readme file.

Compile – The file is compiled into the build output. This setting is used for code files.

Content – The file is not compiled, but is included in the Content output group. For example, this setting is the default value for an .htm or other kind of Web file.

Embedded Resource – This file is embedded in the main project build output as a DLL or executable. It is typically used for resource files.

Now we are good to go!

I hope it was useful.

Advertisements

Unit testing using Visual Studio 2010 — WHY and HOW

As a developer, we have been asked about Unit testing during interviews. Typical answer is “yeah! i know how to write a unit test case but did not get a chance to implement it.”  what cliche! 🙂 .

Why Unit testing is important :  Apart from SDLC and following the best practices (from my experience nobody cares for unit test cases unless it is a established product). I still found one of the reasons why we may HAVE to perform unit testing for every application in future. Cloud Hosting is making news all around the world and looking at it’s cost benefits companies are trying their best to adopt it asap. With remote hosting comes lot of rules imposed by the vendor who is hosting your application and Unit testing is one of them. for example SFDC (sales force dot com) applications need at least 70% unit testing coverage of before they agree to host it on cloud.  So it’s about time we need to take unit testing seriously.

Good news for visual studio developers is that It’s really easy to implement unit testing in VS2010.  No plugins required for a test project.

Class Library : to unit test. I have a C# class library project. which has only one class  ProductRepository.cs. I am using entity framework to access database (makes life easy. right? :)).

</pre>
public class ProductRepository
 {
 public ProductRepository()
 {
 }
 private readonly static NorthwindEntities _db = new NorthwindEntities();

public static List<Product> GetAll()
 {
 return _db.Products.ToList();
 }

public static Product GetById(int productId)
 {
 return _db.Products.Where(p => p.ProductID == productId).SingleOrDefault();
 }
 }
<pre>

it has only two methods GetAll() and GetById(). You can change the implementation the way you need.

HOW to create a Unit Test using VS 2010: 

  1. Go to any class in library project. say ProductRepository class here.
  2. Go to any method name and Right Click and Select Create Unit Tests.

3.  It opens a wizard. It shows library with all types and its methods listed.  You can select types and methods you want to write unit test cases for.

4.  Select Output project. It can be an existing Test project or Select –> “Create a new C# Test project”

5.  It creates all the test methods for selected methods in library earlier in the wizard.

6.  Check out the Test method created for TestGetAll(). it prefixes “Test”  to all the method names.


[TestMethod()]
 public void GetAllTest()
 {
 List<Product> expected = null;

// change it here and make a db call to populate expected object with the same data source.

//something like below using entity framework.

// expected = _dbContext.Products.ToList();

 List<Product> actual;
 // call library method
 actual = ProductRepository.GetAll();
 Assert.AreEqual(expected, actual);
 Assert.Inconclusive("Verify the correctness of this test method.");
 }

7.  Note that Test project does not copy the .config  settings. Though it will reference the main project so database access layer classes are still available in test methods. Connection strings need to be added manually in test project .config.

8.   Look at a better implementation of TestGetAll () method below.


[TestMethod()]
 public void GetAllTest()
 {
 var _db = new NorthwindEntities(); // declared in class library
 List<Product> expected = null;
 expected = _db.Products.ToList();

 var actual = ProductRepository.GetAll();
 Assert.AreEqual(expected.Count , actual.Count );

// comparing each item in collection

IEnumerator<Product> p1 = expected.GetEnumerator();
 IEnumerator<Product> p2 = actual.GetEnumerator();

while (p1.MoveNext() && p2.MoveNext())
 {
 Assert.AreEqual(p1.Current.ProductID, p2.Current.ProductID);
 Assert.AreEqual(p1.Current.ProductName, p2.Current.ProductName);
 Assert.AreEqual(p1.Current.SupplierID, p2.Current.SupplierID);
 Assert.AreEqual(p1.Current.UnitPrice, p2.Current.UnitPrice);
 }
 }

Above code can be changed as per our needs. If you just want to validate the count of collection or each element.

How to Run Unit Test Cases: 

You will notice that under Solution Items there is a new file created YourClassLibraryProjectName.vsmdi . It will list out all the test methods. you can select the ones you want to run or Run all. Every time you make any changes in Test methods don’t forget to Refresh the .vsmdi file in Test editor.

Just Hit Run Test in Current context and check the results (Passed or Failed) in Test Results window. you should see something like the below.

It may look like coding twice for every method 🙂 but you got to do what you got to do. right?

I will go deeper in my next article “Unit Testing beyond Assert statements”. 

I hope it is useful!

Asp.Net MVC 3.0 with dependency injection using Ninject container.

I did not use the famous jargon “Inversion Of Control IOC” intentionally here so that developers who are taking a shot at implementing(or understanding the existing application) dependency injection in their MVC application are not puzzled by the debate over comparing/relating IOC  with DI.

For now, let’s settle on that   “IOC is an architecture principle and DI is configurable piece of code which follows IOC.”

I am going to cover the much needed  WHY,WHERE and HOW of DI

WHY to use DI: Even though MVC represents Separation of Concerns quite strongly, yet controllers are tightly coupled to Data access model/service.

// using Entity framework here.
private NorthwindEntities _Db = new NorthwindEntities();
public ActionResult CustomerList()
 {
 var model = _Db.Customers.ToList();
 return View(model);
 }

In the above code, we have NorthwindEntities entity framework context used for Data access. let’s say we need to change the data access methodology for some reason (trust me it happens more often than you assume), then we need to change controller codes all across the application.  So, why not creating a way where controller can become loosely coupled with data access methodology.

Hence here are few situations when to use IOC – DI

  1. When we need our components to be loosely coupled.
  2. When Unit testing is important and database may not be ready in the beginning. Test Driven Development TDD.
So, rather than instantiating the database context object we should pass an interface to the controller. This reduces extra work to create a test/mock data for testing. Even the database is not ready we can test our action methods easily as all  controller needs is an Interface.
WHERE to use DI:
  1. Initialization of controllers should be changed. controller’s constructor should accept interface to a repository (ICustomerRepository).
  2. In Global.asax and under Application_Start event setup the binding to interface.
 HOW to use:  piece of code to implement.
Interface and Repository classes
</pre>
</div>
<div>
public interface ICustomerRepository
 {
List<Customer> GetAll();
 }

// entity framework data access

public class CustomerEFRepository : ICustomerRepository
 {
 #region ICustomerRepository Members

public List<MVC_IOC_DI.EF.Customer> GetAll()
 {
 NorthwindEntities _db = new NorthwindEntities();
 return _db.Customers.ToList();
 }

#endregion
 }

// Sql to Linq data access

public class CustomerLinqRepository : ICustomerRepository
 {
 #region ICustomerRepository Members

public List<Customer> GetAll()
 {
 NorthwindLinqDataContext _db = new NorthwindLinqDataContext();
 return _db.Customers.ToList();
 }

#endregion
 }

// Home Controller

public class HomeController : Controller
 {
 private readonly ICustomerRepository irepository;

public HomeController(ICustomerRepository repository )
 {
 irepository = repository ;
 }

// right click on this method and Add View (as List template) strongly typed to Customer object.
public ActionResult CustomerList()
 {
 var model = irepository.GetAll() ;
 return View(model);
 }

}</div>
<div>
Ninject IOC container related code:  You can download Ninject libraries for MVC3.0 from http://nuget.org/packages/Ninject.MVC3 . If you are using VS2010 just go to NuGet Package manager and search for Ninject and install it (Nuget really rocks :))
</div></div>
<div>
<pre><div>
using Ninject;
using Ninject.Syntax;</div>
<div></div>
<div>//You would need a dependency resolver class to instruct MVC about the binding/mapping you need to specify in //global.asax.</div>
<div>

public class NinjectDependencyResolver : IDependencyResolver
 {
 private readonly IResolutionRoot _resolutionRoot;

public NinjectDependencyResolver(IResolutionRoot kernel)
 {
 _resolutionRoot = kernel;
 }

public object GetService(Type serviceType)
 {
 return _resolutionRoot.TryGet(serviceType );
 }

public IEnumerable<object> GetServices(Type serviceType)
 {
 return _resolutionRoot.GetAll(serviceType);
 }

}

</div>
<pre>// call this method ins Application_Start event</pre>
private void SetupDependencyInjection()
 {
 // create Ninject DI kernel
 IKernel kernel = new StandardKernel();

// register repository with specific data access repository DI container
 kernel.Bind<ICustomerRepository>().To<CustomerLinqRepository>();
// Later you may change it to EF data access easily.
//kernel.Bind<ICustomerRepository>().To<CustomerEFRepository>();
// Tell mvc to use our DI Ninject container
 DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
 }
<pre>

Here is the summary of the whole implementation.

  1. Include Ninject libraries in your application.
  2. Write Interface for each entity repository. — ICustomerRepository
  3. Write repository classes which implements the interface. — CustomerEFRepository or CustomerLinqRepository
  4. Controller should have interface as a class variable.
  5. Write a constructor for the controller which accepts this interface as parameter.
  6. Write a dependency resolver class for Ninject container. Which will change the dafualt way of how the MVC  resolves the dependency.
  7. Map the bindings in Application_Start event of Global.asax.cs.
These steps are for a very basic implementation of DI in MVC 3. 

For a beginner, it is a good start. Once the skeleton is ready, it’s easy to put on some fat :).

I hope it is useful.


Converting a Json string to C# object using JavaScriptSerializer

Gradually web development is shifting it’s focus to Client side programming day by day. Json is simply a Fat Free alternative to XML. Earlier XML was our commonly accepted data format across all the platforms, but JSON seems to be even more promising because of it’s light weight and familiar syntax (reminds me of .Net  object initializer).   Jquery on the other hand has become a standard which has excellent support with JSON format.

Let’s say we have a C# class Product.


class Product {

int ProductID;

string ProductName;

int CategoryID;

int SupplierID;

decimal UnitPrice;

}

JSON string example : We need to make sure our json string syntax is correct.  Class property names should be same to map it by default.

Here is the syntax

“{Property1 : ‘stringvalue’ , Property2 : ‘stringValue2’, Property3 : 123 }”

var jsonProductString = "{ ProductID :" + pid + ", ProductName :'" + pName + "',CategoryID :" + categoryId + ", SupplierID :" + supplierId + ", UnitPrice :" + unitPrice + "}";

Conversion to C# object: this is code is tested in .Net4.0.


System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

 var p = serializer.Deserialize<Product>(args);
// p is Product object initialized with Json string values.

Interesting part is after deserialization all the data types are easily mapped to Product class data types

Update:  There is a new serialization technique which performs even better for Json serialization. It is Json.Net library developed by James Newton King. it is available on codeplex.

Read more about Json.Net library on my Post on Json.Net library.
I hope it will be useful!!