TopMenu

Microsoft Ending Support For .NET Framework 4, 4.5 And 4.5.1

Microsoft is to end the support for .NET framework version 4, 4.5. and 4.5.1 as per the source, Starting January 12, 2016 Microsoft will no longer provide security updates, technical support or hotfixes for .NET 4, 4.5, and 4.5.1 frameworks.

windows-update

What does it mean?

It means if you are running the above mentioned .Net versions in production then it might be a good time to update the production to 4.5.2 or greater to get full support and security updates. This is not necessary or mandatory to move to latest version in development because .NET 4.5.2 or greater version will be supporting the .NET 4, 4.5 and 4.5.1 version-ed application without any issue.

Read more details about the news here.  

Test post For OLW

Yeah this is just to test the new Open live writer.

Abstract class vs Interface in OO

Background

Object Oriented Programming conceptsRecently I answered a question asking about the difference in Abstract class and Interface. I gave him an explained answer but had this Idea to share it with everyone. This was not the very first question and asked many time on many forums then I looked at the answers. Those have the same articles blogs links and explanation about differences in both these terms from C# implementation view and not actually by Object oriented point of view. So this blog is the same content I provided in answer but had this thought to share it with more audience. 

The differences between Interfaces and Abstract classes can be categorized by concept and implementation.

From Object oriented view

As you might be knowing the basic principles of object oriented language.

- Abstraction/Encapsulation

- Inheritance

- Polymorphism

Interface

----------------

Interfaces provides high level of abstraction.

They also known as contracts in some design principles of software system.

Decoupled system uses Interfaces to expose dependencies because they represent declarations and not actual implementations. Because Interfaces abstracts implementation besides interface can have multiple definitions represented by multiple classes those implements those interfaces. So they are important part of a software system design which is(should be) less coupled and more cohesive.

Abstract class

----------------

Abstract classes represents a level of abstraction and high level of information sharing also known as Inheritance. Interfaces are not for data sharing at all.

Abstract classes are to define default behavior of any entity(class). It also allows to define abstract and virtual actions. Those actions represents derived/child class implementation. So polymorphism comes in picture. Which interfaces doesn't represent in any way.

When you being learning object oriented system or language its remains confusing in beginning but when you spent years practicing and learning the same, you realize that there's not much to compare for differences because these two things exists for their own purpose.

Difference from C# perspective

C# is a language which follows Object oriented principles. C# doesn't support multiple inheritance which make it close to pure object oriented language. Since C++ has this feature and we learn C++ as first class language during our college time so we compare features. Then question comes how the multiple inheritance works in C#. From many source you learn that there's interface that allows something like multiple inheritance but here the wrong information start crawling into mind and people starts comparing Abstract classes and Interfaces. Interface doesn't have Information sharing i.e. Inheritance feature. They're contracts which declares rules/actions which any class should implement in order to fulfill the contract rules(explained in simple words).

What are the difference in these two terms in C#?

There's plenty of blogs/articles and other source which have mentioned the differences in C# language. So just type it in google. Anyways If you have reached this blog means you might have already gone through those blogs and might be looking for some additional information than what’s out there.

The difference is by concept of OOP and not just in C#. So the above explanation applied to any language which follows OOP and not just C#.

Happy Learning!!!

(Used image source code.tutsplus.com)

Get free developer essentials tools-training material on MSDN

Microsoft is giving away a lots of tools and training materials in their recent Developer essentials membership program. This great takeaway for developers.

What are takeaways ?

1. 6 months free pluralsight subscription.

2. Azure app services free plan.

3.  $200 Azure credit

4. Parallels Desktop for Mac Pro 3-month subscription

... and lot more.

Join here:
https://www.visualstudio.com/products/visual-studio-dev-essentials-vs

Thanksgiving Day approaching soon.. May be it's a holidays gift from Microsoft. 

SOA best practices - Simplifying ServiceFaçade

A common practice observed during design or development of a service component; is heavy usage of ServiceFacade. According to Façade definition, A facade is an object that provides a simplified interface to a larger body of code, such as a class library. In this post I’ll be discussing about the challenge that are faced with ServiceFacade classes while working on SOA (Service Oriented Architecture).
Note: In this article we’ll be using WCF service contracts for sampling. The language is C# and code editing tool used is Visual studio 2013.

Let’s take a look at the high level design of Façade pattern.
image

Usually when the services are created we only concentrate on developing the server side functionality without thinking of fact that how service could grow in future because of the business. A simplest example, creating a service that manages products of an eCommerce site. Suppose the product service provides following operations:

- Create a product

- Delete a product

- Edit product

- GetProduct

- GetProductsList

- Search product

- Miscellaneous other operation

Now, Let’s take a look at the service contract. I’ll be taking the sample of WCF service contracts for demonstration:

public interface IProductService
{

[OperationContract]
IEnumerable<Product> GetProductsList(Guid categoryId, int pageIndex, int pageSize);

[OperationContract]
Product Edit(Model.Product product);

[OperationContract]
Product Get(Guid productId);

[OperationContract]
Product Create(Model.Product product);

[OperationContract]
IEnumerable<Product> SearchProduct(SearchCriteria criteria);

[OperationContract]
void Delete(Guid productId);
}
Let’s take a look at the usually seen implementation of above contract:
public class ProductService : IProductService
{
IRepository<Product> product;
ILogger logger;
InventoryService service;
//...
//...
// And any other dependencies required to fulfill
// operations requirement here.

public IEnumerable<Product> GetProductsList(Guid categoryId, int pageIndex, int pageSize)
{
// A try..catch{} for error/exception handling
// Check inventory step
// Get inventory availabilities step
// Prepare products lists step
// ... bunch of other stuff.
// Log, if required etc..
// return the response.
}

public Product Edit(Product product)
{
// Actual core logic of Editing a product.
}

public Product Get(Guid productId)
{
// Actual core logic of Fetching a product.
}

public Product Create(Product product)
{
// Actual core logic of Adding a product.
}

public IEnumerable<Product> SearchProduct(SearchCriteria criteria)
{
// Actual core logic of Seraching products.
}

public void Delete(Guid productId)
{
// Actual core logic of Deleting a product.
}
}
This is Façade pattern in real life scenario. I would call it service façade since we are talking in context of SOA. When we look the above service façade sample, it seems fine, right? Unless the business decided to add/replace/remove/re-locate an operation to another service. Now think about removing the Get() method from Product contract to some other service contract. The whole logic written under Get() will be demolished or might not work when moved to another service contract. Why? Because it’s tightly coupled with Façade here.
Figure below illustrating the coupling of CoreLogic and ServiceContracts:

clip_image002[5]


Let’s take a look at the downside of such Facades in SOA especially on services side:

Architect’s point of view:

The coupling of the core service logic to contracts and implementation resources can inhibit its evolution and negatively impact service consumers.

“When a service is subject to change either due to changes in the contract or in its underlying implementation, this core service logic can find itself extended and augmented to accommodate that change. As a result, the initial bundling of core service logic with contract-specific or implementation-specific processing logic can eventually result in design-time and runtime challenges.”
[Ref. SOA Design Patterns by Thomas Erl (Chapter 12)]

Developer’s point of view:

1. A huge bodied class carrying out all business logics (or core service logic).

2. Class became larger and larger as more methods will get added.

3. Hard to Unit test due to lengthy methods.

4. A centralize place where multiple developers will be working on it fix bugs/adding new operations. Now you can imagine how this central place can easily be polluted with stuff.

5. Bug prone!!! Fixing a bug could end up introducing multiple bugs also known as “Rebugging code”. See Fallacy of resue.

Considering both scenarios; ServiceFacades are problems and may become problem in future for maintenance so I decided to write this post as reference to developer seeking solution to this problem.

Solution approach –


The problem can be solved by separating core logic from service contracts(façade) to separate self-operating entities. Figure below illustrates the idea of separating the Contracts from CoreLogic:

clip_image002[8]


From implementation point of view let’s try to solve this problem using CommandPattern.
Why command pattern?

A command can represent individual operation of service contract. Then we can use a dispatcher to invoke a particular command. Also the Core logic of individual operation can reside in commands. This is “An approach” to solve above problem.
Note: The implementation of CommandPattern that I’ll use in this post might differ from the samples given on various sources. Design patterns are Notion to use the power of Object Oriented world. Implementation can vary but it shouldn’t violate principles.

Simplifying ServiceFacade

Figure below shows the Idea of using commands and redirecting each operation request to dedicated command via command dispatcher.
clip_image002[10]

Now let’s go back to the code and create a new project which will consists of Commands representing each operation from Service Contract. So let’s create a class library project and name the project “ServiceOperations”. Well I just named it because “Naming is one of the hardest thing in computer programming world”. :)

image

In this project we have 3 project folders which I have created for separating the classes by their respective responsibilities.

Base – Consists of Abstract classes and interfaces.
Commands – Consists of all commands and command result(we’ll be discussing these two).
Handlers – Consists of Handlers which will execute the commands.

Now we’ll start adding commands with respect to operations from service contract. For sampling we’ll create a command for Get(Guid ProductId) operation from service contract. To start with we need some foundation classes to implement command pattern under Base folder.

BaseCommand

/// <summary>
/// Each command would be dervied from Base command
/// </summary>
public abstract class BaseCommand
{
/// <summary>
/// Logical name to represent the command.
/// [optional] and can be used for other pusposes like logging/error reporting etc.
/// </summary>
public string Name { get; protected set; }
}
BaseCommandResult
/// <summary>
/// Each command must have a result to send back.
/// Any command restul must inherit from this class.
/// </summary>
public abstract class BaseCommandResult
{
/// <summary>
/// Contains error details, if occurred during execution.
/// </summary>
public ErrorDetails Error { get; set; }
}

/// <summary>
/// Represent error details happened during command execution.
/// </summary>
public class ErrorDetails
{
/// <summary>
/// Error code, For production level debugging purpose(representing technical issue type).
/// </summary>
public int Code { get; set; }

/// <summary>
/// Application friendly error message.
/// </summary>
public string Message { get; set; }
}
BaseCommandHandler – Design of this class is really important as each command handler should know the command and its return type. Also common error handling etc. will be done in base class only. As I mentioned above the implementation of command pattern might differ. But first it should fulfill the purpose of business while following SOLID principles.
/// <summary>
/// A marker interface for CommandHandlers.
/// </summary>
public interface ICommandHandler<TCommand, TResult>
{
TResult Execute(TCommand command);
}

/// <summary>
/// Each command handler must be dervied from this class.
/// </summary>
public abstract class BaseCommandHandler<TCommand, TResult> : ICommandHandler<TCommand, TResult>
{
/// <summary>
/// Executes the command logic in safe execution context.
/// </summary>
public TResult Execute(TCommand command)
{
try
{
return this.ExecuteCore(command);
}
catch(Exception exception)
{
this.HandleException(exception);

return this.GenerateFailureResponse();
}
}

/// <summary>
/// Consists of actual logic to process any command.
/// </summary>
protected abstract TResult ExecuteCore(TCommand command);

/// <summary>
/// Consists of dervied handler specific strategy to respond to
/// any error occurred during execution.
/// </summary>
protected abstract TResult GenerateFailureResponse();

/// <summary>
/// Method detailing the handling of exception.
/// Override this method to have CommandHandler specific error handling.
/// </summary>
protected virtual void HandleException(Exception exception)
{
// do logging
}
}
Add a new class under the folder Commands and name it GetProductCommand and GetProductCommandResult. Design the classes like below:
/// <summary>
/// Contains arguments and information required to process Get product request.
/// </summary>
public class GetProductCommand : BaseCommand
{
/// <summary>
/// Product Id
/// </summary>
public Guid ProductId { get; set; }

public GetProductCommand(Guid productId)
{
this.ProductId = productId;

this.DoSanityCheckOnArguments();
}

private void DoSanityCheckOnArguments()
{
if(this.ProductId == Guid.Empty)
{
throw new ArgumentException("productId", "Failed to initialize GetProductCommand. Invalid product Id received.");
}
}
}

/// <summary>
/// Contains results of GetProductCommand execution.
/// </summary>
public class GetProductCommandResult : BaseCommandResult
{
public Product ProductDetails { get; set; }
}
Now let’s add the GetProductCommandHandler. The GetProductCommandHandler will contains the execution logic, which will be executing in a really controlled environment. Inherit the class from BaseCommandHandler with generic argument of type GetProductCommand and GetProductCommandResult. Once you finish writing below syntax, press ctrl + . in visual studio and you’ll be prompted to implement the abstract class.
image
public class GetProductCommandHandler : BaseCommandHandler<GetProductCommand, GetProductCommandResult>
{
protected override GetProductCommandResult ExecuteCore(GetProductCommand command)
{
throw new NotImplementedException();
}

protected override GetProductCommandResult GenerateFailureResponse()
{
throw new NotImplementedException();
}
}
Add the Core Logic to fetch the product here. Build an error response if anything goes wrong. This is how the final class would look like after doing the patching work.
public class GetProductCommandHandler : BaseCommandHandler<GetProductCommand, GetProductCommandResult>
{
private IRepository repository;

public GetProductCommandHandler()
{
repository = new ProductRepository();
}

protected override GetProductCommandResult ExecuteCore(GetProductCommand command)
{
if (command == null)
{
throw new ArgumentNullException("command", "GetProductCommand object was received null.");
}

var product = repository.Fetch(command.ProductId);

var productDetails = new GetProductCommandResult
{
ProductDetails = product
};

return productDetails;
}

protected override GetProductCommandResult GenerateFailureResponse()
{
return new GetProductCommandResult
{
Error = new ErrorDetails
{
// Move it to shared constant file
Code = 200001,
// Load it from string resource file
Message = "There was an error while retreiving product details."
}
};
}
}

Now if you want you can also write some unit tests against the Command testing the individual logic of each operation. Instead of testing the whole big old mud ball service façade.

Core logic is now moved from Service contracts to a dedicated command. Now we need find a way to send those operation requests to respective commands. Let’s create a class CommandDispatcher. This class will have only Dispatch method which will actually take the command dispatch it to their respective command handler.

public static class CommandDispatcher
{
/// <summary>
/// Keep the cached instance of command handlers.
/// </summary>
internal static Dictionary<Type, Object> localCache = new Dictionary<Type, object>();

/// <summary>
/// Register all the command handler found
/// </summary>
static CommandDispatcher()
{
// A DI container can be used here.
// This is a composite root for registering all command handlers.
var coreAssembly = typeof(ICommandHandler<,>).Assembly;

var commandTypes =
from type in coreAssembly.GetExportedTypes()
where type.Name.EndsWith("CommandHandler")
select type;


// Register the handlers’ instances to local cache
commandTypes.ToList().ForEach(type => localCache[type] = GetInstance(type));
}

/// <summary>
/// Method to locate and execute the command on their respective command handler.
/// </summary>
public static TResult Dispatch<THandler, TResult>(BaseCommand command)
{
var handlerType = typeof(THandler);

var handlerInstance = Get<THandler>();

var methodInfo = handlerType.GetMethod("Execute");

return (TResult)methodInfo.Invoke(handlerInstance, new[] { command });
}

/// <summary>
/// Get the registered command handlers.
/// </summary>
internal static THandler Get<THandler>()
{
object cachedInstance = null;

if(!localCache.TryGetValue(typeof(THandler), out cachedInstance))
{
throw new InvalidOperationException("Command Handler for the respective command is not registered.");
}

return (THandler)cachedInstance;
}

/// <summary>
/// For testing purpose only.
/// </summary>
internal static void ResetCache()
{
localCache.Clear();
}

private static object GetInstance(Type type)
{
return Activator.CreateInstance(type);
}
}
This CommandDispatcher is doing following work:

1. Register instances of all the command handlers (this work can be replaced by using DI container).

2. Locate and execute the command on its handler via Dispatch method.

To test the Dispatcher I’ve created a few tests around ( ..and actually found couple of bugs to fix before using the code in this article). Refer to the sample solution here on github.

We have our Dispatcher in hand. Let’s patch it to the Service contract operations and finish the bonding of Dispatcher/New façade to Service contracts.

public class ProductService : IProductService
{
public Product Get(Guid productId)
{
var commandArgs = new GetProductCommand(productId);

GetProductCommandResult result =
CommandDispatcher.Dispatch<GetProductCommandHandler, GetProductCommandResult>(commandArgs);

// Raise the fault exception
if (result.Error != null)
{
throw new System.ServiceModel.FaultException<Exception>(new Exception(result.Error.Message));
}

return new Product
{
// map the GetProductCommandResult.Product properties to proerties of contracts.
};
}
}
That’s it. Pretty clean huh! Question yourself what impact would be move Get() method from this contract to another contract or completely removing the method from service contract. Yes, Remove it right away the Core Logic is safe and sound and can easily be used in another service. Also we have no dependencies of the system on contracts anymore. Core service logic unit is abstracted via CommandDispatcher and Commands. Such implementation promotes more cohesiveness and less coupling in the system.

I’m sure some readers might have observed that we have introduced a new design patterns as well while refactoring. Now Service contract is actually behaving as Adapter class for its consumer and the core service logic unit i.e. BusinessLogic. That’s how, IMO, the service contracts should behave in the system.

There are Pros and Cons (not much) of using this separation so before we wrap up let’s take a look at them.

Pros

1. Separated business unit from contracts.

2. Minimized the contract changes impact on core service logic.

3. More controlled execution of business logic via commands.

4. Each command is representing a service operation which is placed in a dedicated class means more scope to do with operations.

5. More opportunities to add unit tests at its core logic unit i.e. Commands.

6. Old service façade are now Adapters.

Cons

1. Boilerplate code. (This complain usually heard from developers. But this boiler plating is worth for long run, and of course it can also be optimized by techniques like Aspects Oriented Programming)

2. Additional mapping of Contacts and Business Entities. (This can be handled by using an awesome utility Automapper). Thanks to Jimi and community developers doing this great piece of work.

For further reading on best SOA practices and patterns I would suggest to read “SOA Design Patterns” by Thomas Erl.

Solution used in the blog post is hosted on Github here.

Managing Cross Cutting Concerns – Logging

Cross cutting concerns (a.k.a Aspects) are part of each every project built or being built and so called the Infrastructure. A quick definition of CCC (Cross cutting concerns), An essential part of software application that cuts across the layers of the application. CCC can including things like Logging, Exception/Error Handling, Caching, Monitoring, Security, Communication etc. and there’s a list of operation that are integral part of an application and needs to be performed across the layers. Take a look at a layered application architecture. It has DataLayer, BusinessLayer and UI or Presentation Layer. Those usually managed separately in individual projects but what kept me thinking is the way to manage the cross cutting. The challenge comes with the fact that CCC is shared across the layer. It can make maintenance of an application a nightmare if not implemented correctly.

image

In this post we’ll be looking at the pain areas and possible solution for better implementation of CCC but we’ll discuss a type of Aspect of an application architecture in Cross cutting concern, a set of sample problems and what can be best practices to avoid them etc. Unlike Java in C# Aspect oriented programming (AOP) is not fully supported. Using Aspects (Attributes in C#) is one way of introducing Cross cutting concerns in an application. But that’s a topic that we’ll discuss later in this post.

The problem

To depict the idea of the problem let’s start with simplest things known as Logging in CCC. Let’s talk about the logging aspect in an application from the various developer’s point of view. There could be possible cases during application development:

Case 1: Developer didn’t care about it unless….

This is the least and last thing that I’ve seen people care about unless the application is ready for Production or it’s already in production and bugs/problems are reported from the end users. Then the developer realized the importance of logs (Logging) and the whole picture gets clear dictating importance and necessity of logging in application. What happened during development could be:

1. Least or almost no logging.

2. Resulting in hot patch in production with minimum logging support. (Too much risk)

3. Consequence of #1 and #2 resulting in last moment code changes and endup with hard coded trace/log statement at random places.

Case 2: Developer cared about it too much

In this case developer knows the importance of logging in each layer and logs messages and any critical things that could happen in application. But usually end up in situations like:

  1. Methods are cluttered with logging statements. A case of violation of SRP(Single Responsibility Principle).
    try
    {
    // some operations here.
    }
    catch (Exception ex)
    {
    this.logger.Log(ex);
    throw;
    }

  2. Too much usage of Try..catch almost used in each function. A case of violation of DRY principle.(Don’t Repeat Yourself) .
  3. Too much logging.
Case 3: The optimistic developer

This is a case when developer have knowledge of not overflooding the code with log statement and she is also concerned about managing the Cross cutting across components. But she might get confused with the way to manage it having options available like:


  1. A static logger factory to provide logger instance access.
    public class MyController : BaseController
    {
    private static readonly ILog Logger = LogManager.GetCurrentClassLogger();

    public IList<Customers> Get()
    {
    Logger.Debug("Done! I can use it!");
    }
    }

  2. Adding logger property in every class via property or constructor injection and using DI container to inject the logger.
    public class MyController
    {
    private readonly ILog _logger;

    public MyController(ILog logger)
    {
    _logger = logger;
    }

    public IList<Customers> Get()
    {
    _logger.Debug("I am injected via constructor using some IoC!");
    }
    }

  3. Use AOP (Aspect oriented programming).

Now we all must have seen these cases or must felt somewhere by ourself somewhere in our career phase. Now let’s talk about the possible solutions to avoid such situations.

Solution approach[Case1]

This situation can be avoided by Design. Why the developer failed or didn’t care about the logging is because the design didn’t had enough support for Infrastructure in early stage of development. If they failed to incorporate cross cutting it wasn’t developer’s fault at all. It was the vague design of application.

To visualize it in real life scenario, let’s think of a building at construction site. If design doesn’t include the Hoses, Vent, Electricity wiring pipes, Windows etc. then later things might end-up breaking into walls and ceilings to get those small but necessary setups done. This is exactly what happens with software applications; end-up plumbing those cross cutting concerns later on. Situations like this are surely not a good sign.

Introduce a solid infrastructure in early designing phase before development starts. Cross cuttings concerns should be well defined. Infrastructure components which are required on an individual layer should be available by design.

E.g. On a business layer side a base class can have access to a logger factory or logger instance that can be accessed for logging purpose in all derived classes.

public abstract class BaseCommand
{
protected ILogger Logger { get; private set; }

public BaseCommand()
{
Logger = NullLogger.Instance;
}

public BaseCommand(ILogger logger)
{
Logger = logger;
}
}
Now let’s discuss few aspects of above design:

1. Logger in base class would be a good place why? because this piece of information can be shared to all derived classes.

2. Default instance can have a Null logger so it’s not a dependency any more. A system should work without an Aspect like logging. It’s shouldn’t be a defined as dependency in your application design.

3. Now Developer doesn’t have to worry about introducing logging by herself in first place.

This might not be a perfect example but this is “a way” of putting infrastructure/cross cutting concerns in right place at right time.

Solution Approach[Case 2]

Which in short says, Logging aspect viz. Infrastructure component is used but not correctly, sample shown above in problem Case 2. Defining “What and When to log” is very important. This is again should be defined in early stage of development. Areas that should be addressed on individual Layer are: What application should log on individual layer? E.g. Error, Exception (Handled/Unhandled), Trace info etc. along with which information must be shared across the layers.

The case of exception handling is very common that required logging to be done and exception would be wrapped and sent to another layer. In this case:

1. Design should manage a sample case like error handling at common places. So that logging can be performed without duplication and without avoiding SRP.

Let’s take an example of OrderProcessorCommand that processes an order this will be inherited from our above defined BaseCommand.

public class OrderProcessorCommand : BaseCommand
{
public void Execute(Order order)
{
try
{
// Business logic for processing order
}
catch(InvalidOperationException exception)
{
Logger.LogError(string.Format("Invalid operation.Order {0}", order.OrderId, exception));
}
}
}
Think of 10 more commands like this and may be in future you require to create more commands mean more try..catch and logging statements cluttered in your application. Now let’s redesign the above classes.

Let’s start with extending BaseCommandClass.

public abstract class BaseCommand<T>
{
protected ILogger Logger { get; private set; }

public BaseCommand()
{
Logger = NullLogger.Instance;
}

public BaseCommand(ILogger logger)
{
Logger = logger;
}

public void Execute(T parameter)
{
try
{
CheckForNull(parameter); // common place for command parameter null checking :)

ExecuteCore(parameter);
}
catch (InvalidOperationException exception) // gotcha! that's it handling all common commands errors here.
{
HandleError(exception.Message, exception);
}
}

protected abstract void ExecuteCore(T Parameter);

protected virtual void HandleError(string message, Exception exception)
{
// Do more with logging.
Logger.LogError(message, exception);
}

private void CheckForNull(T parameter)
{
if(parameter == null)
{
throw new ArgumentNullException("Command parameter should not be null.");
}
}
}
Now the base class is equipped with more infrastructure support i.e. Error/Exception handling. Now the OrderProcessorCommand will look like this:
public class OrderProcessorCommand : BaseCommand<Order>
{
protected override void ExecuteCore(Order Parameter)
{
// Business logic for processing order
}
}
Neat!! Isn’t it? More over if any particular command required to handle its exception in its own way then the new design is supporting it very well. E.g. the occurred exception has to be wrapped and should be sent to another layer.
public class UpdateOrderCommand : BaseCommand<Order>
{
protected override void ExecuteCore(Order Parameter)
{
// Business logic for processing order
}

protected override void HandleError(string message, Exception exception)
{
// Let the logging done in first place.
base.HandleError(message, exception);

// For demo purpose only. In real scenario error codes can be used here.
if (exception.GetType() == typeof(InvalidOperationException))
{
// Now pack it and tag it.
throw new InvalidOrderException("The order has invalid items.");
}
}
}
As you can see we have removed the clutter of logging and exception handling at one place. You can imagine how neat your all command classes would look like.

Conclusion, A better design in application can provide much better way to manage and clean the Cross cutting concerns clutter. This is why Design patterns are important during development.

Solution Approach[Case3]

Now this case is really interesting. In this case developer knows the problems and keeps the infrastructure (CCC) stuff usage straight and clean in the application by following best practices. But again during those practices another question comes in mind about managing the objects and classes for infrastructure components or aspects like Logging. This is really a topic where individuals have their own opinions and all are interesting you can’t deny one straightforward. After researching and with all experience I had so far with Cross cuttings (logging for example in this blog post) following can be best practices (IMO):

1. Infrastructure components like Logger shouldn’t be considered as Dependencies. Though one can use constructor injection but make sure it doesn’t become the “required” component. Application should work even without logger.

2. Singletons or Static logger factories are good to keep for shared instances. You should keep the infrastructure (CCC) stuff as thin as possible.

3. If you’re using Dependency injection. Logger object shouldn’t be registered with “Transient” life cycle.

4. Usage of AOP(Aspect oriented programming) for infrastructure (CCC) is really interesting one specially in C#. Found a definition of AOP which says,

"Aspect Oriented Programming is a methodology to separate cross cut code across different modules in a software system."

Means thinking of using AOP is not a false alarm at all. Unfortunately AOP is not fully supported in C#. C# supports Attributes but defining attributes isn’t enough a supporting actor class required to perform respective actions.

E.g. Logging can be done using AOP. Castle.Dynamic provides interceptors that can be used to intercept the method invocation for logging.

[EnableLogging]
protected override void ExecuteCore(Order Parameter)
{
// Business logic for processing order
}
Ayende has written a very informative article on logging via AOP. But using run time interceptors like Castle.DynamicProxy has their own runtime cost. As it works based on run time Proxy wrapper generation of each marked method/class. IMO this is too much cost for operations like Logging. You may not want to hamper the performance of your application just because of Logger operations. Look at the more types of approaches to achieve AOP in .Net.

But surely this can be a great way to incorporate cross cuttings in your application if done via Compile Time weaving or Link Time weaving. Let’s not go more deep about the AOP here. I’ll be writing another post details AOP possibilities in .Net C# separately.

Conclusion

Although Cross Cuttings Concerns are not sometimes not considered major part of an application. Often they appear in Application architecture design diagram nicely but in application code it remains less important (Observed many instances in couple of project I looked upon). Cross cuttings are the infrastructure on which great applications are built. And their importance is as equal as any of the concrete layer in application architecture. This blog post mostly talked about Logging. The problems I addressed here for a small aspect like loggin are real and often observed in development phase of application.
image

I’ll be writing more about other cross cutting concerns like Security/Error handling but let’s wrap things up here.

Hope you like this post. Kindly share/like if it really helped you by improvising your thoughts over CCC.

Setting up SSL encryption to WCF REST API Service

A complete guide to create secure WCF REST API with custom Basic Authentication

WCF REST API services are still being used by many developers for client server connectivity for data and messaging. This blog is a complete guide on creating a WCF Rest service from scratch and Adding security to the service using Basic Authentication. Then we’ll learn how to encrypt the basic authentication information which would be sent over the network using SSL. The main sections of this guide are:

Pre-requisite:

  • Basic knowledge of Visual studio/WCF basics.
  • Visual studio version > 2008
  • .Net framework > 3.5 installed
  • IIS server >7 or equal

Securing basic authentication credentials using SSL over Http i.e. (Https)

The Basic authentication information is usually sent in plain text (encrypted by Base64 string which can be easily decrypted) over the network. Most of the browsers issue a warning about this secure information being sent as plain text. If you try to launch the API call in IE browser you’ll see a warning something like below:

clip_image002

Here comes the Transport layer security into picture. All communication being done over the network can be secured using the Transport layer security by using SSL(Secure Sockets Layer) certificates.
To apply SSL security first you need a certificate. In order to get a real certificate one can go to certificates providers like Thawte, digicert, Godaddy etc. and purchase a certificate. These providers (not mentioning any specific provider but all in general) are trusted providers for issuing digital certificates to ensure that identity of certificate owner is verified.

But in development environment you don’t need to purchase a SSL certificate in real. You can generate a local self-signed certificate from your machine. But the certificate would be only valid for your local use only. If you use the certificate over the network this would be invalidated. I’m not going into details so let’s get started how to get a self-signed server certificate that you can use in development environment.

Creating a certificate and enabling the Https settings to use the certificate

You have two options either create a certificate using ‘makecert’ command. Here’s a nice detailed article with quite good explanation about certificates. Or you can use IIS 7.0 or greater to create your certificate.

1. Launch Internet Manager from control panel or goto Run -> type ‘Inetmgr’ -> press enter.

2. Select the ROOT node on left side panel. Look for `Server Certificates` under `IIS` on right panel.

clip_image002

3. Double click on ‘Server Certificates’ and select ‘Create self-signed certificate’.

image

4. Now enter the name of certificate. This will be the friendly name of your certificate.

clip_image006

5. Click Ok and certificate that you have created would appear in parent window.

6. Now select the website you want to configure for HTTPS in IIS.

clip_image008

7. In the Site Bindings window, click Add.

clip_image009

8. In the Add Site Binding window, enter the following information:

Type:

In the drop-down list, select https.

IP address:

In the drop-down list, select All Unassigned.

Port:

Enter 443. The port for SSL traffic is usually port 443.

SSL certificate:

In the drop-down list, select your recently imported SSL Certificate by its friendly name.

clip_image010

9. Click OK. Your SSL Certificate is now installed and the website is configured to accept secure connections.

Note: You may have to restart IIS or the server for it to recognize the new certificate (in some cases).

10. To test the setting open the site binding again and select Https binding and click on ‘Browser’. You might see below error.

clip_image012

11. To get rid of this error use the machine name exactly same as your certificate section “Issued to” says. E.g. If you open your certificate then you’ll see issued to property and which should be your Machine name. If your machine is part of a domain then machine name would be like <machinename>.<xyz>.<domain> etc. so if you open it in your browser will fully qualified name of your machine then you won’t be getting that error.

clip_image014

Setting up WCF REST service to use SSL (Https)

To enable the SSL over Http protocol follow below steps:

1. Add Protocol mapping for the webhttpbinding to use https.

<protocolMapping>
<add binding="webHttpBinding" scheme="https"/>
</protocolMapping>
2. Under binding -> webhttpbindings enable security mode Transport.
<bindings>
<webHttpBinding>
<security mode="Transport" />
</binding>
</webHttpBinding>
</bindings>
3. Add a host base address under services -> service.
<service name="WcfWebHttpIISHostingSample.TestService" behaviorConfiguration="ServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="https://desktop-pc.mydomain/WcfWebHttpIISHostingSample/api/"/>
</baseAddresses>
</host>


</services>
4. Now rebuild the service and test it in the browser. You will not see the warning of in-secure server communication any more.

clip_image015

I hope this series of WCF REST API tutorial will help you. Feel free to like and share. The complete sample used in this Guide can be found here on Github.

Download the complete tutorial Guide as PDF from here.

Basic Authentication in WCF REST on IIS

A complete guide to create secure WCF REST API with custom Basic Authentication

WCF REST API services are still being used by many developers for client server connectivity for data and messaging. This blog is a complete guide on creating a WCF Rest service from scratch and Adding security to the service using Basic Authentication. Then we’ll learn how to encrypt the basic authentication information which would be sent over the network using SSL. The main sections of this guide are:

Pre-requisite:

  • Basic knowledge of Visual studio/WCF basics.
  • Visual studio version > 2008
  • .Net framework > 3.5 installed
  • IIS server >7 or equal

Adding Basic authentication

The REST services are built and run over http protocol. A simple way to enable the authentication is to use Basic Authentication(i.e. user/pwd). Basic authentication can be enabled over http protocol. Now here are the choices that we have:

We can use simple transport level basic authentication by using Custom username and password validator as mentioned here. But the author has explicitly stated that this will only work in self hosted environment. Which is not our case as we are using IIS to host our service. Also there are other method available on the internet like by extending ServiceAuthenticationManager or using a custom MessageInspector and use it like a custom user/pwd validator but I was not really convinced with those methods because somehow they were not best candidate for our scenario. The challenge comes with IIS is that IIS does the authentication before WCF receives the request. And Till now there’s no out of the box support for Basic Authentication for WCF REST on IIS. So we have to go with our custom solution which is by extending ServiceAuthorizationManager class and override method CheckAccessCore and using it in Service Behaviors as default Authorization manager. The configuration would look something like below after setting up a custom service Authorization manager.

      <serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceAuthorization
serviceAuthorizationManagerType
=" WcfWebHttpIISHostingSample.RestAuthorizationManager, WcfWebHttpIISHostingSample"/>
</behavior>
</serviceBehaviors>
Now I have to extend the class ServiceAuthorizationManager with a custom class RestAuthorizationManager which I named it to make sense with the context.
   public class RestAuthorizationManager : ServiceAuthorizationManager
{
/// <summary>
/// Method source sample taken from here: http://bit.ly/1hUa1LR
/// </summary>
protected override bool CheckAccessCore(OperationContext operationContext)
{
//Extract the Authorization header, and parse out the credentials converting the Base64 string:
var authHeader = WebOperationContext.Current.IncomingRequest.Headers["Authorization"];
if ((authHeader != null) && (authHeader != string.Empty))
{
var svcCredentials = System.Text.ASCIIEncoding.ASCII
.GetString(Convert.FromBase64String(authHeader.Substring(6)))
.Split(':');
var user = new { Name = svcCredentials[0], Password = svcCredentials[1] };
if ((user.Name == "testuser" && user.Password == "testpassword"))
{
//User is authrized and originating call will proceed
return true;
}
else
{
//not authorized
return false;
}
}
else
{
//No authorization header was provided, so challenge the client to provide before proceeding:
WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"MyWCFService\"");
//Throw an exception with the associated HTTP status code equivalent to HTTP status 401
throw new WebFaultException(HttpStatusCode.Unauthorized);
}
}
}
Now your application is ready to challenge any request with Basic Authentication. To test it you can use any client like Fiddler or Chrome’s post man plugin and see what outcome you get. Let’s simply make a request from normal browser, I’ll get a challenge for basic authentication prompting user/password.

clip_image002

Enter the username - testuser and password – testpassword which we have used to validate the values in our RestAuthorizationManager class.

clip_image004

Continue to – Using Https and SSL to encrypt the Basic authentication information, Creating a self signed certificate and Setup IIS and configure WCF REST Service.


Or Download the complete tutorial Guide as PDF from here.

Compiling C# 6.0 code using Roslyn Microsoft.CodeAnalysis v1.0.0 Programmatically

Since the release of recent release of Roslyn aka Microsoft.CodeAnlysis all the article and blogs on internet which were written using Alpha\Beta version of Roslyn are now out dated.
Recently I wanted to write a program using latest stable version (v1.0.0) of Roslyn to compile the CSharp6 versioned code against .Net 4.6 framework. In old beta version there was no option for specifying Target framework and compiler RunTime or maybe I missed it somehow. So I was wondering how to achieve in latest release. I tried searching internet, stackoverflow but finally I end reading and comparing old methods to new and renamed methods and finally created a working sample.

Roslyn Version – Microsoft.CodeAnalysis version="1.0.0"

Install it from Nuget:

> Install-Package Microsoft.CodeAnalysis -Version 1.0.0

Sharing my initial observations of this encounter:

1. Roslyn have become more extensible.

2. Less dependency on the platform version on Roslyn based utilities.

3. The problem was with one package “Microsoft.Workspaces.Desktop” which failed by build because this library requires 4.5.2 or latest .Net version 4.6. So I had to install 4.6 to make it working.

4. Now you can specify almost everything required for customized compilation.

Here’s my complete program. This is a console application that compile a csharp file to Dll. The latest functions in Roslyn have options to supply more information e.g. which platform you want to use for Compilation and what compilation or language version you want to use.

public class Program
{
private static readonly IEnumerable<string> DefaultNamespaces =
new[]
{
"System",
"System.IO",
"System.Net",
"System.Linq",
"System.Text",
"System.Text.RegularExpressions",
"System.Collections.Generic"
};

private static string runtimePath = @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6\{0}.dll";

private static readonly IEnumerable<MetadataReference> DefaultReferences =
new[]
{
MetadataReference.CreateFromFile(string.Format(runtimePath, "mscorlib")),
MetadataReference.CreateFromFile(string.Format(runtimePath, "System")),
MetadataReference.CreateFromFile(string.Format(runtimePath, "System.Core"))
};

private static readonly CSharpCompilationOptions DefaultCompilationOptions =
new CSharpCompilationOptions(OutputKind.WindowsRuntimeApplication)
.WithOverflowChecks(true)
.WithOptimizationLevel(OptimizationLevel.Release)
.WithUsings(DefaultNamespaces);

public static SyntaxTree Parse(string text, string filename = "", CSharpParseOptions options = null)
{
var stringText = SourceText.From(text, Encoding.UTF8);
return SyntaxFactory.ParseSyntaxTree(stringText, options, filename);
}

public static void Main(string[] args)
{
var fileToCompile = @"C:\Users\....\Documents\Visual Studio 2013\Projects\ConsoleForEverything\SignalR_Everything\Program.cs";
var source = File.ReadAllText(fileToCompile);
var parsedSyntaxTree = Parse(source, "", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6));

var compilation
= CSharpCompilation.Create("Test.dll", new SyntaxTree[] { parsedSyntaxTree }, DefaultReferences, DefaultCompilationOptions);
try
{
var result = compilation.Emit(@"c:\temp\Test.dll");

Console.WriteLine(result.Success ? "Sucess!!" : "Failed");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.Read();
}
}
Although this program could have been much better with all refactoring and organizing but this will give you a kick start.

The new Code Analyzer and CSharp syntax rewriters are more interesting things and are on my list to explore.

Hosting WCF REST service in IIS

A complete guide to create secure WCF REST API with custom Basic Authentication

WCF REST API services are still being used by many developers for client server connectivity for data and messaging. This blog is a complete guide on creating a WCF Rest service from scratch and Adding security to the service using Basic Authentication. Then we’ll learn how to encrypt the basic authentication information which would be sent over the network using SSL. The main sections of this guide are:

Pre-requisite:

  • Basic knowledge of Visual studio/WCF basics.
  • Visual studio version > 2008
  • .Net framework > 3.5 installed
  • IIS server >7 or equal

Hosting and Deploying a WCF REST service in IIS

To Host the above service in IIS follow below steps:
1. Right click on the project and go to Properties. In properties window select Web.
2. Now under Servers on Web settings you’ll see following details change the “IIS Express” to “IIS Server”.

clip_image002

3. Now Click on Create Virtual Directory. Now if you have Visual Studio running As Administrator then you’ll get a message The Virtual directory was created successfully! Otherwise you’ll receive an error message and you need to launch again Visual studio as Administrator. I mentioned it in the start of this Guide.

4. Now press F5 and your website will be up and running on IIS server instead of your IIS express.

clip_image003


Deploying a WCF REST service on IIS Local machine (optional)

(Optional) You don’t actually need to deploy the current WCF service because the visual studio already using IIS server for hosting as detailed in above step. This is just to let you know how to deploy a WCF REST service on IIS.
Follow below steps:
1. Right click on Project -> Goto Publish.

image

2. In Publish windows open the dropdown for profiles and select New Profile.

image

3. Select publish method as “Web Deploy”. Enter server as “Localhost”. Add site name as “Default Web site/WcfWebHttpIISHostingSample_Demo2”. Click Validate connection it’ll verify access rights and other information provided.

SNAGHTMLc4aa1c7

4. Once the Validate connection succeeds click publish. You’ll get the success message in output window in Visual studio.

5. Test the service by entering in browser following url - http://localhost/WcfWebHttpIISHostingSample_Demo2/Data/TestingDeploymentSuccess

Continue reading - Adding security to the WCF REST service using custom Basic Authentication

Or Download the complete tutorial Guide as PDF from here.