csDoc.IsAutoGeneratedCode()) return;
element.Name, element.LineNumber);
asIVisitor;
rules on your projects. Style cop will automatically look for assemblies in the directory and pick up the new rules for your team.
It could happen that you may have authentication and also authorization in your web application.
The authorization could be at page level and you need to enforce that in every page of your web application.
In these kind of scenarios httpmodule could turn out to be very handy. Httpmodule could be made
to behave like an gate keeper who on every request would check with the page being requested if the
request is from valid user or not. Below C# example would make it clear what I am talking about,
//Define interface which every page is required to implement
public interface IAuthorization
{
bool IsPageAccessible();
}
public partial class RequestedPage : Page, IAuthorization
{
public bool IsPageAccessible()
{
//Your authorization check logic goes here
}
}
public class AuthorizerHttpModule : IHttpModule
{
void httpModule_AuthorizeRequest(object sender, EventArgs e)
{
IAuthorization pageToAuthorize = HttpContext.Current.Handler as IAuthorization;
//Enforce authorization to be implemented.
if(pageToAuthorize == null) { //throw exception}
if(!pageToAuthorize.IsPageAccessible()){ //Redirect to unauthorized page}
}
}
CQRS is an object oriented architectural pattern built on the principle that every method should either be a command that performs an action, or a query that returns data to the client, but not both.
A typical CQRS scenario involves 2 DB’s, a write DB which is used to store transitional data for long running processes. For a process where a service expects multiple messages, it needs a way to temporary store data before the all the messages arrives. For e.g. to make a customer a preferred customer needs an approval from the management, which takes some time to process the request. The service will need a temporary storage for the preferred customer state change request till the approval comes. The write DB is used to store these kinds of data. The Read DB is not updated till the approval comes.
When the approval finally comes, the service will take the customer information from the write DB, complete the registration process and write it to the read DB. At this time, the temporary customer information in the write DB has done its job and can be removed from the write DB. For simpler process such as change customer first name, the change can be written to the read DB right away. Writing to the write DB is not required because there is no temporary data in this case.
This simple approach brings following benefits (from Rinat Abdullin’s blog)
This blog is an attempt to implement the principles of CQRS in a very simple way, for demonstrating the concepts of CQRS like:
Dependency Inversion Principle (DIP)
Basic idea is instead of low level modules are defining the way that high level modules interact with them, we can invert the dependency. So no longer are the high level modules going to be defined on low level ones, but the high level modules will define some kind of interface that low level modules must obey and then the low level modules depends on the interface or abstraction in order to function.
Ex: Portable chargeable devices like mobiles, cameras, laptops
They all have their own ports to get them charged. Like Mobile phones may have micro or mini usb; Cameras will have under connection in; laptops will have their own port.
So you cannot use the same plug to connect these. What’s wrong here is that the surge protector should be defining what these devices should confirm to recharge. As a result the power step should have all the different plugs that the portable devices use to recharge them.
This is an example of not using Dependency Inversion principle.
If we use the Dependency inversion to solve this problem, we will have the common port that will be used for charging and that will be defined by some high-level module (the power step). So the same plug can be used to connect to different type of devices.
The programming example here is:
We have a high level class depending on interface that is specified by low level class. Now in this case the low level class is not creating an interface. It is just a way the publicly exposed members that low level class defines an interface that high level class uses.
The problem is
If we have more low level classes, we should have a switch or if statement to be able to handle different low level classes. So the higher level classes should know about all these things and the High Level class is not reusable.
If we invert the dependencies
We have taken that interface above that line. That line represents Layering. If you think about your architecture, the high level class belongs to different layer from the low level. So we have the high level class defining the interface. This might exists as a abstract base class or Interface or some other contract. But the concept is the high level class has said, you must confirm this interface if I am going to use you to do this job. Now the low level class has to confirm the interface specified by the high level class and in fact the high level class also depends on that interface.
If we add multiple low level classes we can provide different implementations.
They all depend on the interface. But nothing happened to high level class. It becomes reusable.
Background:
This is one of my favorite, old and yet powerful feature which is available in C# 3.0 and above version…
Let’s think of a scenario where in, we need to add a new method to already existing class. There are many options available like
If the source code is available, either I can directly go to that class and add the method or
I can inherit that class in my derived class and add new method in my derived class
For ex: To a third party API class “Calculator” which provides methods like Add, Sub, Multiply and Divide of 2 numbers. Let say I need to add new method “HCF” to calculate Highest common factor of 2 numbers
But what if the source code for the class where we need to add new method is not available????
What if I need to use this newly added method at various places??
Here comes the use of Extension methods to make our life simpler and to write code easier…
What are Extension methods?
Extension methods are a special kind of static method. These methods are called as if they were instance methods on the extended type.
Extension methods allow us to extend new functionality for existing type without having to create a new derived type, recompile, and modify the original type.
How do we implement it?
Create a static “CalculatorExtension” class and new static method called “HCF”
For whichever class we have to extend the functionality, pass that class in the new method created along with “this” keyword.
public static class CalculatorExtension
{
public static int HCF(this Calculation calc, int x, int y)
{
var highestNumber = x > y ? x : y;
var lowestNumber = x > y ? y : x;
var remainder = 1;
while (remainder != 0)
{
remainder = highestNumber % lowestNumber;
highestNumber = lowestNumber;
lowestNumber = remainder;
}
return highestNumber;
}
}
That’s it. We are done. Wherever we need, we can use that new method as if it was a built in method for Calculator. All extension methods will have a down arrow symbol as you can see below.
Conclusion:
This extension method is widely used in LINQ. In my next blog, I will write a new extension method for LINQ and lets see the practical use of it .
Microsoft Fakes
The fakes framework can be used to test any .NET method. Microsoft fakes mocks objects with no preexisting interfaces.
The fakes framework actually provides two ways to create mock objects.
Getting started with Sims
Create a new class library in visual studio 2012. And add the class CartToShim
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace FakingExample
{
public class CartToShim
{
publicint CartId { get; set; }
publicint UserId { get; set; }
public ReadOnlyCollection<CartItem> CartItems { get; set; }
private List<CartItem> cartItems = newList<CartItem>();
public DateTime CreateDateTime { get; set; }
public CartToShim(int cartId, int userId)
{
CartId = cartId;
UserId = userId;
CreateDateTime = DateTime.Now;
CartItems = new ReadOnlyCollection<CartItem>(cartItems);
}
public void AddCartItem(int productId)
{
var cartItemId = DataAccessLayer.SaveCartItem(CartId, productId);
cartItems.Add(new CartItem(cartItemId, productId));
}
}
}
Add CartItem class
namespace FakingExample
{
public classCartItem
{
public int CartItemId { get; set; }
public int ProductId { get; set; }
public CartItem(int cartItemId, int productId)
{
CartItemId = cartItemId;
ProductId = productId;
}
}
}
Add the DataAccessLayer class
using System.Data;
using System.Data.SqlClient;
namespaceFakingExample
{
publicstaticclassDataAccessLayer
{
public static int SaveCartItem(int cartId, int productId)
{
using (var conn = newSqlConnection(“”))
{
var cmd = newSqlCommand(“InsCartItem”, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue(“@CartId”, cartId);
cmd.Parameters.AddWithValue(“@ProductId”, productId);
conn.Open();
return (int)cmd.ExecuteScalar();
}
}
}
}
Add unti test project to the solution
In the untitest project, add the FakingExample project
Now right click on the FakingExample reference in the unit test project and select “Add Fakes Assembly”
This will create the following references
Now we are ready to do faking.
Add CartToShimTests test class to the test project
using Microsoft.QualityTools.Testing.Fakes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace FakingExample.Tests
{
[TestClass]
public class CartToShimTests
{
[TestMethod]
public void AddCartItem_GivenCartAndProduct_ThenProductShouldBeAddedToCart()
{
using (ShimsContext.Create())
{
int cartItemId = 42, cartId = 1, userId = 33, productId = 777;
Fakes.ShimDataAccessLayer.SaveCartItemInt32Int32 = (c, p) => cartItemId;
var cart = new CartToShim(cartId, userId);
cart.AddCartItem(productId);
Assert.AreEqual(cartId, cart.CartItems.Count);
var cartItem = cart.CartItems[0];
Assert.AreEqual(cartItemId, cartItem.CartItemId);
Assert.AreEqual(productId, cartItem.ProductId);
}
}
}
}
Now run the unti test. Notice that our test completely skipped over the SaveCartItem in DataAccessLayer, otherwise we would have received exception saying invalid connection string.
In my next post I will show the Stubs example.
Thanks
Vinay
Misuse of exception handling has been a common problem in any software project that do not have a proper guidelines, strategy or framework on how to handle exceptions. It leads to lost of bugs coming over and over again. The purpose of this article is to establish some practices for proper exception handling code.
Practice #1: Never use “catch(Exception e)”
Catching exception like this, swallows the original exception and causes
Let me expain the problem with this kind of exception handling with a small C# example. Consider the following code:
try
{
CallSomeMethod();
}
catch (Exception e)
{
... do something here....
}
That will catch ALL exceptions that emit from CallSomeMethod(), including exceptions that should not be caught at this point. Some exceptions should be handled by higher level code. Some exceptions should cause the application to crash. The code should only catch the most specific exception type that needs to be handled and allow all other exceptions to pass up the call stack.
For example, next year another programmer may modify CallSomeMethod() to throw a new exception that needs to be handled by the UI. Since the code will catch that exception, the User Interface layer will never see the exception, and therefore will not function properly.
For example, a lower-level system call may throw an exception caused by some resource failure (unable to load a file or open a network port) that should stop the application. However, the catch() will stop the exception, the application will continue to run, and the end-user will complain that it is not functioning properly.
In both the examples, programmer/developer will have a hard time to debug any issue related to CallSomeMethod API.
Practice #2: Logging is not sufficient error handling.
Consider this code:
try
{
CallSomeMethod();
}
catch (SomeException e)
{
log.Error("Oops there was an error: {0}", e.ToString());
}
The users will never know that an error occurred, because they don’t read the log file unless they have a reason to. If the application appears to be functioning, and does not display an error message on the screen, then the user has no reason to read the log file. However, the application may not be functioning properly, and the users will not be aware of the problem.
The only case where logging is sufficient is when the exception is re-thrown.
catch (SomeException e)
{
log.Error("Oops there was an error: {0}", e.ToString());
throw;
}
OR
catch (SomeException e)
{
log.Error("Oops there was an error: {0}", e.ToString());
throw new SomeOtherException("error here", e);
}