RESTful Day #5: Security in Web APIs-Basic Authentication and Token based custom Authorization in Web APIs using Action Filters


Introduction

Security has always been a major concern we talk about enterprise level applications, especially when we talk about exposing our business through services. I have already explained a lot on WebAPI in my earlier articles of the series. I explained, how do we create a WebAPI, how to resolve dependencies to make it a loosely coupled design, defining custom routes, making use of attribute routing. My article will explain how we can achieve security in a WebAPI. This article will explain how to make WebAPI secure using Basic Authentication and Token based authorization. I’ll also explain how we can leverage token based authorization and Basic authentication in WebAPI to maintain sessions in WebAPI. There is no standard way of achieving security in WebAPI. We can design our own security technique and structure which suits best to our application.

Roadmap

Following is the roadmap I have setup to learn WebAPI step by step,

I’ll purposely use Visual Studio 2010 and .NET Framework 4.0 because there are few implementations that are very hard to find in .NET Framework 4.0, but I’ll make it easy by showing how we can do it.

Security in WebAPI

Security in itself is very complicated and tricky topic. I’ll try to explain how we can achieve it in WebAPI in my own way.
When we plan to create an enterprise level application, we especially want to take care of authentication and authorization. These are two techniques if used well makes our application secure, in our case makes our WebAPI more secure.

Authentication

Authentication is all about the identity of an end user. It’s about validating the identity of a user who is accessing our system, that he is authenticated enough to use our resources or not. Does that end user have valid credentials to log in our system? Credentials can be in the form of a user name and password. We’ll use Basic Authentication technique to understand how we can achieve authentication in WebAPI.

Authorization

Authorization should be considered as a second step after authentication to achieve security. Authorization means what all permissions the authenticated user has to access web resources. Is allowed to access/ perform action on that resource? This could be achieved by setting roles and permissions for an end user who is authenticated, or can be achieved through providing a secure token, using which an end user can have access to other services or resources.

Maintaining Session

RESTful services work on a stateless protocol i.e. HTTP. We can achieve maintaining session in Web API through token based authorization technique. An authenticated user will be allowed to access resources for a particular period of time, and can re-instantiate the request with an increased session time delta to access other resource or the same resource. Websites using WebAPIs as RESTful services may need to implement login/logout for a user, to maintain sessions for the user, to provide roles and permissions to their user, all these features could be achieved using basic authentication and token based authorization. I’ll explain this step by step.

Basic Authentication

Basic authentication is a mechanism, where an end user gets authenticated through our service i.e. RESTful service with the help of plain credentials such as user name and password. An end user makes a request to the service for authentication with user name and password embedded in request header. Service receives the request and checks if the credentials are valid or not, and returns the response accordingly, in case of invalid credentials, service responds with 401 error code i.e. unauthorized. The actual credentials through which comparison is don may lie in database , any config file like web.config or in the code itself.

Pros and Cons of Basic Authentication

Basic authentication has its own pros and cons. It is advantageous when it comes to implementation, it is very easy to implement, it is nearly supported by all modern browsers and has become an authentication standard in RESTful / Web APIs. It has disadvantages like sending user credentials in plain text, sending user credentials inside request header, i.e. prone to hack. One have to send credentials each time a service is called. No session is maintained and a user cannot logout once logged in through basic authentication. It is very prone to CSRF (Cross Site Request Forgery).

Token Based Authorization

Authorization part comes just after authentication, once authenticated a service can send a token to an end user through which user can access other resources. The token could be any encrypted key, which only server/service understands and when it fetches the token from the request made by end user, it validates the token and authorizes user into the system. Token generated could be stored in a database or an external file as well i.e. we need to persist the token for future references. Token can have its own lifetime, and may expire accordingly. In that case user will again have to be authenticated into the system.

WebAPI with Basic Authentication and Token Based Authorization

Creating User Service

Just open your WebAPI project or the WebAPI project that we discussed in the last part of learning WebAPI.
We have BusinessEntities, BusinessServices, DataModel, DependencyResolver and a WebApi project as well.
We already have a User table in database, or you can create your own database with a table like User Table as shown below,
I am using WebAPI database, scripts I have attached for download.

UserServices

Go to BusinessServices project and add a new interface IUserService and a service named UserServices implementing that interface,
Just define one method named Authenticate in the interface.
namespace BusinessServices
{
    public interface IUserServices
    {
        int Authenticate(string userName, string password);
    }
}
This method takes username and password as a parameter and returns particular userId if the user is authenticated successfully.
Just implement this method in UserServices.cs class, just like we created services earlier in the series,
using DataModel.UnitOfWork;

namespace BusinessServices
{
    /// <summary>
    /// Offers services for user specific operations
    /// </summary>
    public class UserServices : IUserServices
    {
        private readonly UnitOfWork _unitOfWork;

        /// <summary>
        /// Public constructor.
        /// </summary>
        public UserServices(UnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        /// <summary>
        /// Public method to authenticate user by user name and password.
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public int Authenticate(string userName, string password)
        {
            var user = _unitOfWork.UserRepository.Get(u => u.UserName == userName && u.Password == password);
            if (user != null && user.UserId > 0)
            {
                return user.UserId;
            }
            return 0;
        }
    }
}
You can clearly see that Authenticate method just checks user credentials from UserRepository and returns the values accordingly. The code is very much self-explanatory.

Resolve dependency of UserService

Just open DependencyResolver class in BusinessServices project itself and add its dependency type so that we get UserServices dependency resolved at run time,so add
registerComponent.RegisterType();
line to SetUP method. Our class becomes,
using System.ComponentModel.Composition;
using DataModel;
using DataModel.UnitOfWork;
using Resolver;

namespace BusinessServices
{
    [Export(typeof(IComponent))]
    public class DependencyResolver : IComponent
    {
        public void SetUp(IRegisterComponent registerComponent)
        {
            registerComponent.RegisterType();
            registerComponent.RegisterType();
        }
    }
}

Implementing Basic Authentication

Step 1: Create generic Authentication Filter

Add a folder named Filters to the WebAPI project and add a class named GenericAuthenticationFilter under that folder.
Derive that class from AuthorizationFilterAttribute, this is a class under System.Web.Http.Filters.
I have created the generic authentication filter will be like,
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class GenericAuthenticationFilter : AuthorizationFilterAttribute
    {
      
        /// <summary>
        /// Public default Constructor
        /// </summary>
        public GenericAuthenticationFilter()
        {
        }

        private readonly bool _isActive = true;

        /// <summary>
        /// parameter isActive explicitly enables/disables this filetr.
        /// </summary>
        /// <param name="isActive"></param>
        public GenericAuthenticationFilter(bool isActive)
        {
            _isActive = isActive;
        }

        /// <summary>
        /// Checks basic authentication request
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(HttpActionContext filterContext)
        {
            if (!_isActive) return;
            var identity = FetchAuthHeader(filterContext);
            if (identity == null)
            {
                ChallengeAuthRequest(filterContext);
                return;
            }
            var genericPrincipal = new GenericPrincipal(identity, null);
            Thread.CurrentPrincipal = genericPrincipal;
            if (!OnAuthorizeUser(identity.Name, identity.Password, filterContext))
            {
                ChallengeAuthRequest(filterContext);
                return;
            }
            base.OnAuthorization(filterContext);
        }

        /// <summary>
        /// Virtual method.Can be overriden with the custom Authorization.
        /// </summary>
        /// <param name="user"></param>
        /// <param name="pass"></param>
        /// <param name="filterContext"></param>
        /// <returns></returns>
        protected virtual bool OnAuthorizeUser(string user, string pass, HttpActionContext filterContext)
        {
            if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(pass))
                return false;
            return true;
        }

        /// <summary>
        /// Checks for autrhorization header in the request and parses it, creates user credentials and returns as BasicAuthenticationIdentity
        /// </summary>
        /// <param name="filterContext"></param>
        protected virtual BasicAuthenticationIdentity FetchAuthHeader(HttpActionContext filterContext)
        {
            string authHeaderValue = null;
            var authRequest = filterContext.Request.Headers.Authorization;
            if (authRequest != null && !String.IsNullOrEmpty(authRequest.Scheme) && authRequest.Scheme == "Basic")
                authHeaderValue = authRequest.Parameter;
            if (string.IsNullOrEmpty(authHeaderValue))
                return null;
            authHeaderValue = Encoding.Default.GetString(Convert.FromBase64String(authHeaderValue));
            var credentials = authHeaderValue.Split(':');
            return credentials.Length < 2 ? null : new BasicAuthenticationIdentity(credentials[0], credentials[1]);
        }


        /// <summary>
        /// Send the Authentication Challenge request
        /// </summary>
        /// <param name="filterContext"></param>
        private static void ChallengeAuthRequest(HttpActionContext filterContext)
        {
            var dnsHost = filterContext.Request.RequestUri.DnsSafeHost;
            filterContext.Response = filterContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            filterContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", dnsHost));
        }
    }
Since this is an AuthorizationFilter derived class, we need to override its methods to add our custom logic. Here “OnAuthorization” method is overridden to add a custom logic. Whenever we get ActionContext onOnAuthorization, we’ll check for its header, since we are pushing our service to followBasicAuthentication, the request headers should contain this information. I have used FetchAuthHeader to check the scheme, if it comes to be “Basic” and thereafter store the credentials i.e. user name and password in a form of an object of class BasicAuthenticationIdentity, therefore creating an identity out of valid credentials.
        protected virtual BasicAuthenticationIdentity FetchAuthHeader(HttpActionContext filterContext)
        {
            string authHeaderValue = null;
            var authRequest = filterContext.Request.Headers.Authorization;
            if (authRequest != null && !String.IsNullOrEmpty(authRequest.Scheme) && authRequest.Scheme == "Basic")
                authHeaderValue = authRequest.Parameter;
            if (string.IsNullOrEmpty(authHeaderValue))
                return null;
            authHeaderValue = Encoding.Default.GetString(Convert.FromBase64String(authHeaderValue));
            var credentials = authHeaderValue.Split(':');
            return credentials.Length < 2 ? null : new BasicAuthenticationIdentity(credentials[0], credentials[1]);
        }
I am expecting values to be encrypted using Base64 string; You can use your own encryption mechanism as well.
Later on in OnAuthorization method we create a genericPrincipal with the created identity and assign it to current Thread principal,
            var genericPrincipal = new GenericPrincipal(identity, null);
            Thread.CurrentPrincipal = genericPrincipal;
            if (!OnAuthorizeUser(identity.Name, identity.Password, filterContext))
            {
                ChallengeAuthRequest(filterContext);
                return;
            }
            base.OnAuthorization(filterContext);
Once done, a challenge to that request is added, where we add response and tell the Basic realm,
filterContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic
realm=\"{0}\"", dnsHost));
in ChallengeAuthRequest method.
If no credentials is provided in the request, this generic authentication filter sets generic authentication principal to the current thread principal.
Since we know the drawback that in basic authentication credentials are passed in a plain text, so it would be good if our service uses SSL for communication or message passing.
We have an overridden constructor as well that allows to stop the default behavior of the filter by just passing in a parameter i.e. true or false.
  public GenericAuthenticationFilter(bool isActive)
        {
            _isActive = isActive;
        }
We can use OnAuthorizeUser for custom authorization purposes.

Step 2: Create Basic Authentication Identity

Before we proceed further, we also need the BasicIdentity class, that takes hold of credentials and assigns it to Generic Principal. So just add one more class named BasicAuthenticationIdentity deriving fromGenericIdentity.
This class contains three properties i.e. UserNamePassword and UserId. I purposely added UserId because we’ll need that in future. So our class will be like,
using System.Security.Principal;

namespace WebApi.Filters
{
    /// <summary>
    /// Basic Authentication identity
    /// </summary>
    public class BasicAuthenticationIdentity : GenericIdentity
    {
        /// <summary>
        /// Get/Set for password
        /// </summary>
        public string Password { get; set; }
        /// <summary>
        /// Get/Set for UserName
        /// </summary>
        public string UserName { get; set; }
        /// <summary>
        /// Get/Set for UserId
        /// </summary>
        public int UserId { get; set; }

        /// <summary>
        /// Basic Authentication Identity Constructor
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        public BasicAuthenticationIdentity(string userName, string password)
            : base(userName, "Basic")
        {
            Password = password;
            UserName = userName;
        }
    }
}

Step 3: Create a Custom Authentication Filter

Now you are ready to use your own Custom Authentication filter. Just add one more class under that Filters project and call it ApiAuthenticationFilter, this class will derive from GenericAuthenticationFilter, that we created in first step. This class overrider OnAuthorizeUser method to add custom logic for authenticating a request it makes use of UserService that we created earlier to check the user,
protected override bool OnAuthorizeUser(string username, string password, HttpActionContext actionContext)
        {
            var provider = actionContext.ControllerContext.Configuration
                               .DependencyResolver.GetService(typeof(IUserServices)) as IUserServices;
            if (provider != null)
            {
                var userId = provider.Authenticate(username, password);
                if (userId>0)
                {
                    var basicAuthenticationIdentity = Thread.CurrentPrincipal.Identity as BasicAuthenticationIdentity;
                    if (basicAuthenticationIdentity != null)
                        basicAuthenticationIdentity.UserId = userId;
                    return true;
                }
            }
            return false;
        }
Complete class
using System.Threading;
using System.Web.Http.Controllers;
using BusinessServices;

namespace WebApi.Filters
{
    /// <summary>
    /// Custom Authentication Filter Extending basic Authentication
    /// </summary>
    public class ApiAuthenticationFilter : GenericAuthenticationFilter
    {
        /// <summary>
        /// Default Authentication Constructor
        /// </summary>
        public ApiAuthenticationFilter()
        {
        }

        /// <summary>
        /// AuthenticationFilter constructor with isActive parameter
        /// </summary>
        /// <param name="isActive"></param>
        public ApiAuthenticationFilter(bool isActive)
            : base(isActive)
        {
        }

        /// <summary>
        /// Protected overriden method for authorizing user
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="actionContext"></param>
        /// <returns></returns>
        protected override bool OnAuthorizeUser(string username, string password, HttpActionContext actionContext)
        {
            var provider = actionContext.ControllerContext.Configuration
                               .DependencyResolver.GetService(typeof(IUserServices)) as IUserServices;
            if (provider != null)
            {
                var userId = provider.Authenticate(username, password);
                if (userId>0)
                {
                    var basicAuthenticationIdentity = Thread.CurrentPrincipal.Identity as BasicAuthenticationIdentity;
                    if (basicAuthenticationIdentity != null)
                        basicAuthenticationIdentity.UserId = userId;
                    return true;
                }
            }
            return false;
        }
    }
}

Step 4: Basic Authentication on Controller

Since we already have our products controller,
   public class ProductController : ApiController
    {
        #region Private variable.

        private readonly IProductServices _productServices;

        #endregion

        #region Public Constructor

        /// <summary>
        /// Public constructor to initialize product service instance
        /// </summary>
        public ProductController(IProductServices productServices)
        {
            _productServices = productServices;
        }

        #endregion

        // GET api/product
        [GET("allproducts")]
        [GET("all")]
        public HttpResponseMessage Get()
        {
            var products = _productServices.GetAllProducts();
            var productEntities = products as List ?? products.ToList();
            if (productEntities.Any())
                return Request.CreateResponse(HttpStatusCode.OK, productEntities);
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Products not found");
        }

        // GET api/product/5
        [GET("productid/{id?}")]
        [GET("particularproduct/{id?}")]
        [GET("myproduct/{id:range(1, 3)}")]
        public HttpResponseMessage Get(int id)
        {
            var product = _productServices.GetProductById(id);
            if (product != null)
                return Request.CreateResponse(HttpStatusCode.OK, product);
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for this id");
        }

        // POST api/product
        [POST("Create")]
        [POST("Register")]
        public int Post([FromBody] ProductEntity productEntity)
        {
            return _productServices.CreateProduct(productEntity);
        }

        // PUT api/product/5
        [PUT("Update/productid/{id}")]
        [PUT("Modify/productid/{id}")]
        public bool Put(int id, [FromBody] ProductEntity productEntity)
        {
            if (id > 0)
            {
                return _productServices.UpdateProduct(id, productEntity);
            }
            return false;
        }

        // DELETE api/product/5
        [DELETE("remove/productid/{id}")]
        [DELETE("clear/productid/{id}")]
        [PUT("delete/productid/{id}")]
        public bool Delete(int id)
        {
            if (id > 0)
                return _productServices.DeleteProduct(id);
            return false;
        }
    }
There are three ways in which you can use this authentication filter.
Just apply this filer to ProductController. You can add this filter at the top of the controller, for all API requests to be validated,
    [ApiAuthenticationFilter]
    [RoutePrefix("v1/Products/Product")]
    public class ProductController : ApiController
You can also globally add this in Web API configuration file , so that filter applies to all the controllers and all the actions associated to it,
GlobalConfiguration.Configuration.Filters.Add(new ApiAuthenticationFilter());
You can also apply it to Action level too by your wish to apply or not apply authentication to that action,
       // GET api/product
        [ApiAuthenticationFilter(true)]
        [GET("allproducts")]
        [GET("all")]
        public HttpResponseMessage Get()
        {
             …………………
        }
        // GET api/product/5
         [ApiAuthenticationFilter(false)]
        [GET("productid/{id?}")]
        [GET("particularproduct/{id?}")]
        [GET("myproduct/{id:range(1, 3)}")]
        public HttpResponseMessage Get(int id)
        {
             ……………………..
        }

Running the application

We have already implemented Basic Authentication, just try to run the application to test if it is working
Just run the application, we get,
We already have our test client added, but for new readers, just go to Manage Nuget Packages, by right clicking WebAPI project and type WebAPITestClient in searchbox in online packages,
You’ll get “A simple Test Client for ASP.NET Web API”, just add it. You’ll get a help controller in Areas-> HelpPage like shown below,
I have already provided the database scripts and data in my previous article, you can use the same.
Append “/help” in the application url, and you’ll get the test client,
GET:
POST:
PUT:
DELETE:
You can test each service by clicking on it. Once you click on the service link, you’ll be redirected to test the service page of that particular service. On that page there is a button Test API in the right bottom corner, just press that button to test your service,
Service for Get All products,
When you click on Send request, a popup will come asking Authentication required. Just cancel that popup and let request go without credentials. You’ll get a response of Unauthorized i.e. 401,
This means our authentication mechanism is working.
Just to double sure it, let’s send the request with credentials now. Just add a header too with the request. Header should be like ,
Authorization : Basic YWtoaWw6YWtoaWw=
Here “YWtoaWw6YWtoaWw=” is my Base64 encoded user name and password i.e. akhil:akhil
Click on Send and we get the response as desired,
Likewise you can test all the service endpoints.
This means our service is working with Basic Authentication.

Design discrepancy

This design when running on SSL is very good for implementing Basic Authentication. But there are few scenarios in which, along with Basic Authentication I would like to leverage authorization too and not even authorization but sessions too. When we talk about creating an enterprise application, it just does not limit to securing our endpoint with authentication only.
In this design, each time I’ll have to send user name and password with every request. Suppose I want to create such application, where authentication only occurs only once as my login is done and after successfully authenticated i.e. logging in I must be able to use other services of that application i.e. I am authorized now to use those services. Our application should be that robust that it restricts even authenticated user to use other services until he is not authorized. Yes I am talking about Token based authorization.
I’ll expose only one endpoint for authentication and that will be my login service .So client only knows about that login service that needs credentials to get logged in to system.
After client successfully logs in I’ll send a token that could be a GUID or an encrypted key by any xyz algorithm that I want when user makes request for any other services after login, should provide this token along with that request.
And to maintain sessions, our token will have an expiry too, that will last for 15 minutes, can be made configurable with the help of web.config file. After session is expired, user will be logged out, and will again have to use login service with credentials to get a new token. Seems exciting to me, let’s implement this Smile | :)

Implementing Token-based Authorization

To overcome above mentioned scenarios, let’s start developing and giving our application a shape of thick client enterprise architecture.

Set Database

Let’s start with setting up a database. When we see our already created database that we had set up in first part of the series, we have a token table. We require this token table for token persistence. Our token will persist in database with an expiry time. If you are using your own database, you can create token table as,

Set Business Services

Just navigate to BusinessServices and create one more Interface named ITokenServices for token based operations,
using BusinessEntities;

namespace BusinessServices
{
    public interface ITokenServices
    {
        #region Interface member methods.
        /// <summary>
        ///  Function to generate unique token with expiry against the provided userId.
        ///  Also add a record in database for generated token.
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        TokenEntity GenerateToken(int userId);

        /// <summary>
        /// Function to validate token againt expiry and existance in database.
        /// </summary>
        /// <param name="tokenId"></param>
        /// <returns></returns>
        bool ValidateToken(string tokenId);

        /// <summary>
        /// Method to kill the provided token id.
        /// </summary>
        /// <param name="tokenId"></param>
        bool Kill(string tokenId);

        /// <summary>
        /// Delete tokens for the specific deleted user
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        bool DeleteByUserId(int userId);
        #endregion
    }
}
We have four methods defined in this interface. Let’s create TokenServices class which implementsITokenServices and understand each method.
GenerateToken method takes userId as a parameter and generates a token, encapsulates that token in a token entity with Token expiry time and returns it to caller.
  public TokenEntity GenerateToken(int userId)
        {
            string token = Guid.NewGuid().ToString();
            DateTime issuedOn = DateTime.Now;
            DateTime expiredOn = DateTime.Now.AddSeconds(
                                              Convert.ToDouble(ConfigurationManager.AppSettings["AuthTokenExpiry"]));
            var tokendomain = new Token
                                  {
                                      UserId = userId,
                                      AuthToken = token,
                                      IssuedOn = issuedOn,
                                      ExpiresOn = expiredOn
                                  };

            _unitOfWork.TokenRepository.Insert(tokendomain);
            _unitOfWork.Save();
            var tokenModel = new TokenEntity()
                                 {
                                     UserId = userId,
                                     IssuedOn = issuedOn,
                                     ExpiresOn = expiredOn,
                                     AuthToken = token
                                 };

            return tokenModel;
        }
While generating token, it names a database entry into Token table.
ValidateToken method just validates that the token associated with the request is valid or not i.e. it exists in the database within its expiry time limit.
  public bool ValidateToken(string tokenId)
        {
            var token = _unitOfWork.TokenRepository.Get(t => t.AuthToken == tokenId && t.ExpiresOn > DateTime.Now);
            if (token != null && !(DateTime.Now > token.ExpiresOn))
            {
                token.ExpiresOn = token.ExpiresOn.AddSeconds(
                                              Convert.ToDouble(ConfigurationManager.AppSettings["AuthTokenExpiry"]));
                _unitOfWork.TokenRepository.Update(token);
                _unitOfWork.Save();
                return true;
            }
            return false;
        }
It just takes token Id supplied in the request.
Kill Token just kills the token i.e. removes the token from database.
  public bool Kill(string tokenId)
        {
            _unitOfWork.TokenRepository.Delete(x => x.AuthToken == tokenId);
            _unitOfWork.Save();
            var isNotDeleted = _unitOfWork.TokenRepository.GetMany(x => x.AuthToken == tokenId).Any();
            if (isNotDeleted) { return false; }
            return true;
        }
DeleteByUserId method deletes all token entries from the database w.r.t particular userId associated with those tokens.
public bool DeleteByUserId(int userId)
{
_unitOfWork.TokenRepository.Delete(x => x.UserId == userId);
_unitOfWork.Save();

var isNotDeleted = _unitOfWork.TokenRepository.GetMany(x => x.UserId == userId).Any();
return !isNotDeleted;
}
So with _unitOfWork and along with Constructor our class becomes,
using System;
using System.Configuration;
using System.Linq;
using BusinessEntities;
using DataModel;
using DataModel.UnitOfWork;

namespace BusinessServices
{
public class TokenServices:ITokenServices
{
#region Private member variables.
private readonly UnitOfWork _unitOfWork;
#endregion

#region Public constructor.
/// <summary>
/// Public constructor.
/// </summary>
public TokenServices(UnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
#endregion


#region Public member methods.

/// <summary>
///  Function to generate unique token with expiry against the provided userId.
///  Also add a record in database for generated token.
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public TokenEntity GenerateToken(int userId)
{
string token = Guid.NewGuid().ToString();
DateTime issuedOn = DateTime.Now;
DateTime expiredOn = DateTime.Now.AddSeconds(
Convert.ToDouble(ConfigurationManager.AppSettings["AuthTokenExpiry"]));
var tokendomain = new Token
{
UserId = userId,
AuthToken = token,
IssuedOn = issuedOn,
ExpiresOn = expiredOn
};

_unitOfWork.TokenRepository.Insert(tokendomain);
_unitOfWork.Save();
var tokenModel = new TokenEntity()
{
UserId = userId,
IssuedOn = issuedOn,
ExpiresOn = expiredOn,
AuthToken = token
};

return tokenModel;
}

/// <summary>
/// Method to validate token against expiry and existence in database.
/// </summary>
/// <param name="tokenId"></param>
/// <returns></returns>
public bool ValidateToken(string tokenId)
{
var token = _unitOfWork.TokenRepository.Get(t => t.AuthToken == tokenId && t.ExpiresOn > DateTime.Now);
if (token != null && !(DateTime.Now > token.ExpiresOn))
{
token.ExpiresOn = token.ExpiresOn.AddSeconds(
Convert.ToDouble(ConfigurationManager.AppSettings["AuthTokenExpiry"]));
_unitOfWork.TokenRepository.Update(token);
_unitOfWork.Save();
return true;
}
return false;
}

/// <summary>
/// Method to kill the provided token id.
/// </summary>
/// <param name="tokenId">true for successful delete</param>
public bool Kill(string tokenId)
{
_unitOfWork.TokenRepository.Delete(x => x.AuthToken == tokenId);
_unitOfWork.Save();
var isNotDeleted = _unitOfWork.TokenRepository.GetMany(x => x.AuthToken == tokenId).Any();
if (isNotDeleted) { return false; }
return true;
}

/// <summary>
/// Delete tokens for the specific deleted user
/// </summary>
/// <param name="userId"></param>
/// <returns>true for successful delete</returns>
public bool DeleteByUserId(int userId)
{
_unitOfWork.TokenRepository.Delete(x => x.UserId == userId);
_unitOfWork.Save();

var isNotDeleted = _unitOfWork.TokenRepository.GetMany(x => x.UserId == userId).Any();
return !isNotDeleted;
}

#endregion
}
}

Do not forget to resolve the dependency of this Token service in DependencyResolver class.  Add  registerComponent.RegisterType();  to the SetUp method of DependencyResolver class in BusinessServices project.

  [Export(typeof(IComponent))]
    public class DependencyResolver : IComponent
    {
        public void SetUp(IRegisterComponent registerComponent)
        {
            registerComponent.RegisterType();
            registerComponent.RegisterType();
            registerComponent.RegisterType();

        }
    }
Do not forget to resolve the dependency of this Token service in DependencyResolver class. AddregisterComponent.RegisterType(); to the SetUp method ofDependencyResolver class in BusinessServices project.
  [Export(typeof(IComponent))]
    public class DependencyResolver : IComponent
    {
        public void SetUp(IRegisterComponent registerComponent)
        {
            registerComponent.RegisterType();
            registerComponent.RegisterType();
            registerComponent.RegisterType();

        }
    }

Setup WebAPI/Controller

Now since we decided, that we don’t want authentication to be applied on each and every API exposed, I’ll create a single Controller/API endpoint that takes authentication or login request and makes use of Token Service to generate token and respond client/caller with a token that persists in database with expiry details.
Add a new Controller under Controllers folder in WebAPI with a name Authenticate,

AuthenticateController

using System.Configuration;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AttributeRouting.Web.Http;
using BusinessServices;
using WebApi.Filters;

namespace WebApi.Controllers
{
    [ApiAuthenticationFilter]
    public class AuthenticateController : ApiController
    {
        #region Private variable.

        private readonly ITokenServices _tokenServices;

        #endregion

        #region Public Constructor

        /// <summary>
        /// Public constructor to initialize product service instance
        /// </summary>
        public AuthenticateController(ITokenServices tokenServices)
        {
            _tokenServices = tokenServices;
        }

        #endregion

       /// <summary>
       /// Authenticates user and returns token with expiry.
       /// </summary>
       /// <returns></returns>
        [POST("login")]
        [POST("authenticate")]
        [POST("get/token")]
        public HttpResponseMessage Authenticate()
        {
            if (System.Threading.Thread.CurrentPrincipal!=null && System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated)
            {
                var basicAuthenticationIdentity = System.Threading.Thread.CurrentPrincipal.Identity as BasicAuthenticationIdentity;
                if (basicAuthenticationIdentity != null)
                {
                    var userId = basicAuthenticationIdentity.UserId;
                    return GetAuthToken(userId);
                }
            }
           return null;
        }

        /// <summary>
        /// Returns auth token for the validated user.
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        private HttpResponseMessage GetAuthToken(int userId)
        {
            var token = _tokenServices.GenerateToken(userId);
            var response = Request.CreateResponse(HttpStatusCode.OK, "Authorized");
            response.Headers.Add("Token", token.AuthToken);
            response.Headers.Add("TokenExpiry", ConfigurationManager.AppSettings["AuthTokenExpiry"]);
            response.Headers.Add("Access-Control-Expose-Headers", "Token,TokenExpiry" );
            return response;
        }
    }
}
The controller is decorated with our authentication filter,
[ApiAuthenticationFilter]
public class AuthenticateController : ApiController
So, each and every request coming through this controller will have to pass through this authentication filter, that check for BasicAuthentication header and credentials.Authentication filter sets CurrentThreadprincipal to the authenticated Identity.
There is a single Authenticate method / action in this controller. You can decorate it with multiple endpoints like we discussed in fourth part of the series,
        [POST("login")]
        [POST("authenticate")]
        [POST("get/token")]
Authenticate method first checks for CurrentThreadPrincipal and if the user is authenticated or not i.e job done by authentication filter,
if (System.Threading.Thread.CurrentPrincipal!=null && 
    System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated)
When it finds that the user is authenticated, it generates an auth token with the help of TokenServices and returns user with Token and its expiry,
response.Headers.Add("Token", token.AuthToken);
response.Headers.Add("TokenExpiry", ConfigurationManager.AppSettings["AuthTokenExpiry"]);
response.Headers.Add("Access-Control-Expose-Headers", "Token,TokenExpiry" );
return response;
In our BasicAuthenticationIdentity class, I purposely used userId property so that we can make use of this property when we try to generate token, that we are doing in this controller’s Authenticate method,
var basicAuthenticationIdentity = System.Threading.Thread.CurrentPrincipal.Identity as BasicAuthenticationIdentity;
if (basicAuthenticationIdentity != null)
{
var userId = basicAuthenticationIdentity.UserId;
return GetAuthToken(userId);
}
Now when you run this application, You’ll see Authenticate api as well, just invoke this api with Baisc Authentication and User credentials, you’ll get the token with expiry,let’s do this step by step.
  1. Run the application.
  2. Click on first api link i.e. POST authenticate. You’ll get the page to test the api,
  3. Press the TestAPI button in the right corner.In the test console, provide Header information with Authorization as Basic and user credentials in Base64 format, like we did earlier. Click on Send.
  4. Now since we have provided valid credentials, we’ll get a token from the Authenticate controller, with its expiry time,
In database,
Here we get response 200, i.e. our user is authenticated and logged into system. TokenExpiry in 900 i.e. 15 minutes. Note that the time difference between IssuedOn and ExpiresOn is 15 minutes, this we did in TokenServices class method GenerateToken, you can set the time as per your need. Token is 604653d8-eb21-495c-8efd-da50ef4e56d3. Now for 15 minutes we can use this token to call our other services. But before that we should mark our other services to understand this token and respond accordingly. Keep the generated token saved so that we can use it further in calling other services that I am about to explain. So let’s setup authorization on other services.

Setup Authorization Action Filter

We already have our Authentication filter in place and we don’t want to use it for authorization purposes. So we have to create a new Action Filter for authorization. This action filter will only recognize Token coming in requests. It assumes that, requests are already authenticated through our login channel, and now user is authorized/not authorized to use other services like Products in our case, there could be n number of other services too, which can use this authorization action filter. For request to get authorized, nbow we don’t have to pass user credentials. Only token(received from Authenticate controller after successful validation) needs to be passed through request.
Add a folder named ActionFilters in WebAPI project. And add a class named AuthorizationRequiredAttribute
Deriving from ActionFilterAttribute,
Override the OnActionExecuting method of ActionFilterAttribute, this is the way we define an action filter in API project.
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using BusinessServices;

namespace WebApi.ActionFilters
{
public class AuthorizationRequiredAttribute : ActionFilterAttribute
{
private const string Token = "Token";

public override void OnActionExecuting(HttpActionContext filterContext)
{
//  Get API key provider
var provider = filterContext.ControllerContext.Configuration
.DependencyResolver.GetService(typeof(ITokenServices)) as ITokenServices;

if (filterContext.Request.Headers.Contains(Token))
{
var tokenValue = filterContext.Request.Headers.GetValues(Token).First();

// Validate Token
if (provider != null && !provider.ValidateToken(tokenValue))
{
var responseMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Invalid Request" };
filterContext.Response = responseMessage;
}
}
else
{
filterContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
}

base.OnActionExecuting(filterContext);

}
}
}
The overridden method checks for “Token” attribute in the Header of every request, if token is present, it callsValidateToken method from TokenServices to check if the token exists in the database. If token is valid, our request is navigated to the actual controller and action that we requested, else you’ll get an error message saying unauthorized.

Mark Controllers with Authorization filter

We have our action filter ready. Now let’s mark our controller ProductController with this attribute. Just open Product controller class and at the top just decorate that class with this ActionFilter attribute,
    [AuthorizationRequired]
    [RoutePrefix("v1/Products/Product")]
    public class ProductController : ApiController
    {
We have marked our controller with the action filter that we created, now every request coming to the actions of this controller will have to be passed through this ActionFilter, that checks for the token in request.
You can mark other controllers as well with the same attribute, or you can do marking at action level as well. Supoose you want certain actions should be available to all users irrespective of their authorization then you can just mark only those actions which require authorization and leave other actions as they are like I explained in Step 4 of Implementing Basic Authentication.

Maintaining Session using Token

We can certainly use these tokens to maintain session as well. The tokens are issues for 900 seconds i.e. 15 minutes. Now we want that user should continue to use this token if he is using other services as well for our application. Or suppose there is a case where we only want user to finish his work on the site within 15 minutes or within his session time before he makes a new request. So while validating token in TokenServices, what I have done is, to increase the time of the token by 900 seconds whenever a valid request comes with a valid token,
        /// <summary>
        /// Method to validate token against expiry and existence in database.
        /// </summary>
        /// <param name="tokenId"></param>
        /// <returns></returns>
        public bool ValidateToken(string tokenId)
        {
            var token = _unitOfWork.TokenRepository.Get(t => t.AuthToken == tokenId && t.ExpiresOn > DateTime.Now);
            if (token != null && !(DateTime.Now > token.ExpiresOn))
            {
                token.ExpiresOn = token.ExpiresOn.AddSeconds(
                                              Convert.ToDouble(ConfigurationManager.AppSettings["AuthTokenExpiry"]));
                _unitOfWork.TokenRepository.Update(token);
                _unitOfWork.Save();
                return true;
            }
            return false;
        }
In above code for token validation, first we check if the requested token exists in the database and is not expired. We check expiry by comparing it with current date time. If it is valid token we just update the token into database with a new ExpiresOn time that is adding 900 seconds.
            if (token != null && !(DateTime.Now > token.ExpiresOn))
            {
                token.ExpiresOn = token.ExpiresOn.AddSeconds(
                                              Convert.ToDouble(ConfigurationManager.AppSettings["AuthTokenExpiry"]));
                _unitOfWork.TokenRepository.Update(token);
                _unitOfWork.Save();
By doing this we can allow end user or client to maintain session and keep using our services/application with a session timeout of 15 minutes. This approach can also be leveraged in multiple ways, like making different services with different session timeouts or many such conditions could be applied when we work on real time application using APIs.

Running the application

Our job is almost done.
We just need to run the application and test if it is working fine or not. If you have saved the token you generated earlier while testing authentication you can use same to test authorization. I am just again running the whole cycle to test application.

Test Authentication

Repeat the tests we did earlier to get Auth Token.Just invoke the Authenticate controller with valid credentials and Basic authorization header. I get,
And without providing Authorization header as basic with credentials I get,
I just saved the token that I got in first request.
Now try to call ProductController actions.

Test Authorization

Run the application to invoke Product Controller actions.Try to invoke them without providing any Token,
Invoke first service in the list,
Click send,
Here we get Unauthorized, i.e. because our ProductController is marked with authorization attribute that checks for a Token. So here our request is invalid. Now try calling this action by providing the token that we saved,
Click on Send and we get,
That means we got the response and our token was valid. Now we see our Authentication and Authorization, both functionalities are working fine. You can test Sessions by your own.
Likewise you can test all actions. You can create other controllers and test the security, and play around with different set of permutations and combinations.

Conclusion

We covered and learnt a lot. In this article I tried to explain about how we can build an API application with basic Authentication and Authorization. One can mould this concept to achieve the level of security needed. Like token generation mechanism could be customized as per one’s requirement. Two level of security could be implemented where authentication and authorization is needed for every service. One can also implement authorization on actions based on Roles.
I already stated that there is no specific way of achieving security, the more you understand the concept, the more secure system you can make. The techniques used in this article or the design implemented in this article should be leveraged well if you use it with SSL (Secure Socket Layer), running the REST apis on https. In my next article I’ll try to explain some more beautiful implementations and concepts. Till then Happy Coding Smile | :)
You can also download the complete source code with all packages from Github.

References

Read more:

Other Series

My other series of articles:

For more technical articles you can reach out to CodeTeddy.

Advertisements

RESTful Day #4: Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs


Download Source Code

Introduction

We have already learnt a lot on WebAPI. I have already explained how to create WebAPI, connect it with database using Entity Framework, resolving dependencies using Unity Container as well as using MEF. In all our sample applications we were using default route that MVC provides us for CRUD operations. In this article I’ll explain how to write your own custom routes using Attribute Routing. We’ll deal with Action level routing as well as Controller level routing. I’ll explain this in detail with the help of a sample application. My new readers can use any Web API sample they have, else you can also use the sample applications we developed in my previous articles.
Let’s revisit the road map that I started on Web API,
 Here is my roadmap for learning RESTful APIs,
I’ll purposely use Visual Studio 2010 and .NET Framework 4.0 because there are few implementations that are very hard to find in .NET Framework 4.0, but I’ll make it easy by showing how we can do it.

Routing

Routing in generic terms for any service, API, website is a kind of pattern defining system that tries to maps all request from the clients and resolves that request by providing some response to that request. In WebAPI we can define routes in WebAPIConfig file, these routes are defined in an internal Route Table. We can define multiple sets of Routes in that table.

Existing Design and Problem

We already have an existing design. If you open the solution, you’ll get to see the structure as mentioned below,
In our existing application, we created WebAPI with default routes as mentioned in the file named WebApiConfig in App_Start folder of WebApi project. The routes were mentioned in the Register method as,
config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
Do not get confused by MVC routes, since we are using MVC project we also get MVC routes defined inRouteConfig.cs file as,
public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
We need to focus on the first one i.e. WebAPI route. As you can see in the following image, what each property signifies,
We have a route name, we have a common URL pattern for all routes, and option to provide optional parameters as well.
Since our application do not have particular different action names, and we were using HTTP VERBS as action names, we didn’t bother much about routes. Our Action names were like,
1. public HttpResponseMessage Get()
2. public HttpResponseMessage Get(int id)
3. public int Post([FromBody] ProductEntity productEntity)
4. public bool Put(int id, [FromBody]ProductEntity productEntity)
5. public bool Delete(int id)

Default route defined does not takes HTTP VERBS action names into consideration and treat them default actions, therefore it does not mentions {action} in routeTemplate. But that’s not limitation, we can have our own routes defined in WebApiConfig, for example, check out the following routes,

  public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Routes.MapHttpRoute(
               name: "ActionBased",
               routeTemplate: "api/{controller}/{action}/{id}",
               defaults: new { id = RouteParameter.Optional }
           );
            config.Routes.MapHttpRoute(
              name: "ActionBased",
              routeTemplate: "api/{controller}/action/{action}/{id}",
              defaults: new { id = RouteParameter.Optional }
          );
        }
And etc. In above mentioned routes, we can have action names as well, if we have custom actions.
So there is no limit to define routes in WebAPI. But there are few limitations to this, note we are talking about WebAPI 1 that we use with .NET Framework 4.0 in Visual Studio 2010. Web API 2 has overcome those limitations by including the solution that I’ll explain in this article. Let’s check out the limitations of these routes,
Yes, these are the limitations that I am talking about in Web API 1.
If we have route template like routeTemplate: “api/{controller}/{id}” or routeTemplate: “api/{controller}/{action}/{id}” or routeTemplate: “api/{controller}/action/{action}/{id}“,
We can never have custom routes and will have to slick to old route convention provided by MVC. Suppose your client of the project wants to expose multiple endpoints for the service, he can’t do so. We also can not have our own defined names for the routes, so lots of limitation.
Let’s suppose we want to have following kind of routes for my web API endpoints, where I can define versions too,
v1/Products/Product/allproducts
v1/Products/Product/productid/1
v1/Products/Product/particularproduct/4
v1/Products/Product/myproduct/
v1/Products/Product/create
v1/Products/Product/update/3
and so on, then we cannot achieve this with existing model.
Fortunately these things have been taken care of in WebAPI 2 with MVC 5, but for this situation we have AttributeRouting to resolve and overcome these limitations.

Attribute Routing

Attribute Routing is all about creating custom routes at controller level, action level. We can have multiple routes using Attribute Routing. We can have versions of routes as well, in short we have the solution for our exiting problems. Let’s straight away jump on how we can implement this in our exising project. I am not explaining on how to create a WebAPI, for that you can refer my first post of the series.
Step 1: Open the solution ,and open Package Manage Console like shown below in the figure,
Goto Tools->Library Packet manage-> Packet Manager Console
 
Step 2: In the package manager console window at left corner of Visual Studio type, Install-Package AttributeRouting.WebApi, and choose the project WebApi or your own API project if you are using any other code sample, then press enter.
 
Step 3: As soon as the package is installed, you’ll get a class named AttributeRoutingHttpConfig.cs in yourApp_Start folder.
This class has its own method to RegisterRoutes, which internally maps attribute routes. It has a start method that picks Routes defined from GlobalConfiguration and calls the RegisterRoutes method,
using System.Web.Http;
using AttributeRouting.Web.Http.WebHost;

[assembly: WebActivator.PreApplicationStartMethod(typeof(WebApi.AttributeRoutingHttpConfig), "Start")]

namespace WebApi 
{
    public static class AttributeRoutingHttpConfig
 {
  public static void RegisterRoutes(HttpRouteCollection routes) 
  {    
   // See http://github.com/mccalltd/AttributeRouting/wiki for more options.
   // To debug routes locally using the built in ASP.NET development server, go to /routes.axd

            routes.MapHttpAttributeRoutes();
  }

        public static void Start() 
  {
            RegisterRoutes(GlobalConfiguration.Configuration.Routes);
        }
    }
}
We don’t even have to touch this class, our custom routes will automatically be taken care of using this class.We just need to focus on defining routes. No coding :-).  You can now use route specific stuff like route names, verbs, constraints, optional parameters, default parameters, methods, route areas, area mappings, route prefixes, route conventions etc.

Setup REST endpoint / WebAPI project to define Routes

Our 90% of the job is done.
We now need to setup or WebAPI project and define our routes.
Our existing ProductController class looks something like shown below,
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using BusinessEntities;
using BusinessServices;

namespace WebApi.Controllers
{
    public class ProductController : ApiController
    {

        private readonly IProductServices _productServices;

        #region Public Constructor

        /// <summary>
        /// Public constructor to initialize product service instance
        /// </summary>
        public ProductController(IProductServices productServices)
        {
            _productServices = productServices;
        }

        #endregion

        // GET api/product
        public HttpResponseMessage Get()
        {
            var products = _productServices.GetAllProducts();
            var productEntities = products as List ?? products.ToList();
            if (productEntities.Any())
                return Request.CreateResponse(HttpStatusCode.OK, productEntities);
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Products not found");
        }

        // GET api/product/5
        public HttpResponseMessage Get(int id)
        {
            var product = _productServices.GetProductById(id);
            if (product != null)
                return Request.CreateResponse(HttpStatusCode.OK, product);
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for this id");
        }

        // POST api/product
        public int Post([FromBody] ProductEntity productEntity)
        {
            return _productServices.CreateProduct(productEntity);
        }

        // PUT api/product/5
        public bool Put(int id, [FromBody] ProductEntity productEntity)
        {
            if (id > 0)
            {
                return _productServices.UpdateProduct(id, productEntity);
            }
            return false;
        }

        // DELETE api/product/5
        public bool Delete(int id)
        {
            if (id > 0)
                return _productServices.DeleteProduct(id);
            return false;
        }
    }
}
Where we have a controller name Product and Action names as Verbs. When we run the application, we get following type of endpoints only (please ignore port and localhost setting. It’s because I run this application from my local environment),
Get All Products:
Get product By Id:
Create product :
Update product:
Delete product:
Step 1: Add two namespaces to your controller,
using AttributeRouting;
using AttributeRouting.Web.Http;
 

Step 2: Decorate your action with different routes,

Like in above image, I defined a route with name productid which taked id as a parameter. We also have to provide verb (GET, POST, PUT, DELETE, PATCH) along with the route like shown in image. So it is[GET("productid/{id?}")]. You can define whatever route you want for your Action like[GET("product/id/{id?}")], [GET("myproduct/id/{id?}")] and many more.
Now when I run the application and navigate to /help page, I get this,
i.e. I got one more route for Getting product by id. When you’ll test this service you’ll get your desired URL something like: http://localhost:55959/Product/productid/3, that sounds like real REST Smile | :)
Similarly decorate your Action with multiple routes like show below,
        // GET api/product/5
        [GET("productid/{id?}")]
        [GET("particularproduct/{id?}")]
        [GET("myproduct/{id:range(1, 3)}")]
        public HttpResponseMessage Get(int id)
        {
            var product = _productServices.GetProductById(id);
            if (product != null)
                return Request.CreateResponse(HttpStatusCode.OK, product);
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for this id");
        }
Therefore we see, we can have our custom route names and as well as multiple endpoints for a single Action. That’s exciting.Each endpoint will be different but will serve same set of result.
  • {id?} : here ‘?’ means that parameter can be optional.
  • [GET(“myproduct/{id:range(1, 3)}”)], signifies that the product id’s falling in this range will only be shown.

More Routing Constraints

You can leverage numerous Routing Constraints provided by Attribute Routing. I am taking example of some of them,

Range

To get the product within range, we can define the value, on condition that it should exist in database.
        [GET("myproduct/{id:range(1, 3)}")]
        public HttpResponseMessage Get(int id)
        {
            var product = _productServices.GetProductById(id);
            if (product != null)
                return Request.CreateResponse(HttpStatusCode.OK, product);
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for this id");
        }

Regular Expression

You can use it well for text/string parameters more efficiently.
        [GET(@"id/{e:regex(^[0-9]$)}")]
        public HttpResponseMessage Get(int id)
        {
            var product = _productServices.GetProductById(id);
            if (product != null)
                return Request.CreateResponse(HttpStatusCode.OK, product);
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for this id");
        }

e.g. [GET(@"text/{e:regex(^[A-Z][a-z][0-9]$)}")]

Optional Parameters and Default Parameters

You can also mark the service parameters as optional in the route. For example you want to fetch an employee detail from the data base with his name,
[GET("employee/name/{firstname}/{lastname?}")]
public string GetEmployeeName(string firstname, string lastname="mittal")
{
   …………….
  ……………….
}
In the above mentioned code, I marked last name as optional by using question mark ‘?’ to fetch the employee detail. It’s my end user wish to provide the last name or not.
So the above endpoint could be accessed through GET verb with urls,
~/employee/name/akhil/mittal
~/employee/name/akhil
If a route parameter defined is marked optional, you must also provide a default value for that method parameter.
In the above example, I marked ‘lastname’ as an optional one and so provided a default value in the method parameter , if user doesn’t send any value, “mittal” will be used.
In .NET 4.5 Visual Studio > 2010 with WebAPI 2, you can define DefaultRoute as an attribute too, just try it by your own. Use attribute [DefaultRoute] to define default route values.
You can try giving custom routes to all your controller actions.
I marked my actions as,
        // GET api/product
        [GET("allproducts")]
        [GET("all")]
        public HttpResponseMessage Get()
        {
            var products = _productServices.GetAllProducts();
            var productEntities = products as List ?? products.ToList();
            if (productEntities.Any())
                return Request.CreateResponse(HttpStatusCode.OK, productEntities);
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Products not found");
        }

        // GET api/product/5
        [GET("productid/{id?}")]
        [GET("particularproduct/{id?}")]
        [GET("myproduct/{id:range(1, 3)}")]
        public HttpResponseMessage Get(int id)
        {
            var product = _productServices.GetProductById(id);
            if (product != null)
                return Request.CreateResponse(HttpStatusCode.OK, product);
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for this id");
        }

        // POST api/product
        [POST("Create")]
        [POST("Register")]
        public int Post([FromBody] ProductEntity productEntity)
        {
            return _productServices.CreateProduct(productEntity);
        }

        // PUT api/product/5
        [PUT("Update/productid/{id}")]
        [PUT("Modify/productid/{id}")]
        public bool Put(int id, [FromBody] ProductEntity productEntity)
        {
            if (id > 0)
            {
                return _productServices.UpdateProduct(id, productEntity);
            }
            return false;
        }

        // DELETE api/product/5
        [DELETE("remove/productid/{id}")]
        [DELETE("clear/productid/{id}")]
        [PUT("delete/productid/{id}")]
        public bool Delete(int id)
        {
            if (id > 0)
                return _productServices.DeleteProduct(id);
            return false;
        }
And therefore get the routes as,

GET

POST / PUT / DELETE

Check for more constraints here.
You must be seeing “v1/Products” in every route, that is due to RoutePrefix I have used at controller level. Let’s discuss RoutePrefix in detail.

RoutePrefix: Routing at Controller level

We were marking our actions with particular route, but guess what, we can mark our controllers too with certain route names, we can achieve this by using RoutePrefix attribute of AttributeRouting. Our controller was named Product, and I want to append Products/Product before my every action, there fore without duplicating the code at each and every action, I can decorate my Controller class with this name like shown below,
    [RoutePrefix("Products/Product")]
    public class ProductController : ApiController
    {
Now, since our controller is marked with this route, it will append the same to every action too. For e.g. route of following action,
        [GET("allproducts")]
        [GET("all")]
        public HttpResponseMessage Get()
        {
            var products = _productServices.GetAllProducts();
            var productEntities = products as List ?? products.ToList();
            if (productEntities.Any())
                return Request.CreateResponse(HttpStatusCode.OK, productEntities);
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Products not found");
        }
Now becomes,
~/Products/Product/allproducts
~/Products/Product/all

RoutePrefix: Versioning

Route prefix can also be used for versioning of the endpoints, like in my code I provided “v1” as version in my RoutePrefix as shown below,
    [RoutePrefix("v1/Products/Product")]
    public class ProductController : ApiController
    {
Therefore “v1” will be appended to every route / endpoint of the service. When we release next version, we can certainly maintain a change log separately and mark the endpoint as “v2” at controller level, that will append “v2” to all actions,
e.g.
~/v1/Products/Product/all

~/v2/Products/Product/allproducts
~/v2/Products/Product/all

RoutePrefix: Overriding

This functionality is present in .NET 4.5 with Visual Studio > 2010 with WebAPI 2. You can test it there.
There could be situations that we do not want to use RoutePrefix for each and every action. AttributeRoutingprovides such flexibility too, that despite of RoutePrefix present at controller level, an individual action could have its own route too. It just need to override the default route like shown below,

RoutePrefix at Controller

     [RoutePrefix("v1/Products/Product")]
    public class ProductController : ApiController
    {

Independent Route of Action

       [Route("~/MyRoute/allproducts")]
        public HttpResponseMessage Get()
        {
            var products = _productServices.GetAllProducts();
            var productEntities = products as List ?? products.ToList();
            if (productEntities.Any())
                return Request.CreateResponse(HttpStatusCode.OK, productEntities);
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Products not found");
        }

Disable Default Routes

You must be wondering that in the list of all the URL’s on service help page, we are getting some different/other routes that we have not defined through attribute routing starting like ~/api/Product. These routes are the outcome of default route provided in WebApiConfig file, remember? If you want to get rid of those unwanted routes, just go and comment everything written in Register method in WebApiConfig.cs file under Appi_Startfolder,
            //config.Routes.MapHttpRoute(
            //    name: "DefaultApi",
            //    routeTemplate: "api/{controller}/{id}",
            //    defaults: new { id = RouteParameter.Optional }
            //);
You can also remove the complete Register method, but for that you need to remove its calling too fromGlobal.asax file.

Running the application

Just run the application, we get,
We already have our test client added, but for new readers, just go to Manage Nuget Packages, by right clicking WebAPI project and type WebAPITestClient in searchbox in online packages,
You’ll get “A simple Test Client for ASP.NET Web API”, just add it. You’ll get a help controller in Areas-> HelpPage like shown below,
I have already provided the database scripts and data in my previous article, you can use the same.
Append “/help” in the application url, and you’ll get the test client,

GET

POST

PUT

DELETE

You can test each service by clicking on it. Once you click on the service link, you’ll be redirected to test the service page of that particular service. On that page there is a button Test API in the right bottom corner, just press that button to test your service,
Service for Get All products,
Likewise you can test all the service endpoints.

Conclusion

We now know how to define our custom endpoints and what its benefits are. Just to share that this library was introduced by Tim Call, author of http://attributerouting.net and Microsoft has included this in WebAPI 2 by default. My next article will explain token based authentication using ActionFilters in WepAPI. ’til then Happy Coding Smile | :) you can also download the complete source code from GitHub. Add the required packages, if they are missing in the source code.
Click Github Repository to browse for complete source code.

Download Source Code

References

My other series of articles:

RESTful Day #3: Resolve dependency of dependencies using Inversion of Control and dependency injection in ASP.NET Web APIs with Unity Container and Managed Extensibility Framework (MEF)


Download Source Code

Introduction

In my last two articles, I explained how to create a RESTful service using ASP.NET Web API working with Entity Framework and resolving dependencies using Unity Container. In this article, I’ll explain how to create a loosely coupled system with Unity Container and MEF (Managed Extensibility Framework) using Inversion of Control. I’ll not be explaining much theory but rather focus more on practical implementations. For the readers who are following this series, they can use their existing solution that they have created till time. For my new readers of this article, I have provided the download link for the previous source code and current source code as well.
For theory and understanding of DI and IOC you can follow the following links: Unity and Inversion of Control(IOC).

Roadmap

Here is my roadmap for learning RESTful APIs,
I’ll purposely use Visual Studio 2010 and .NET Framework 4.0 because there are few implementations that are very hard to find in .NET Framework 4.0, but I’ll make it easy by showing how we can do it.

Existing Design and Problem

We already have an existing design. If you open the solution, you’ll get to see the structure as mentioned below,
We tried to design a loosely coupled architecture in the following way,
  • DataModel (responsible for communication with database) : Only talks to service layer.
  • Services (acts as a business logic layer between REST endpoint and data access) : Communicates between REST endpoint and DataModel.
  • REST API i.e. Controllers: Only talks to services via the interfaces exposed.
But when we tried to resolve the dependency of UnitOfWork from Services, we had to reference
DataModel dll in to our WebAPI project; this violated our system like shown in following image,
In this article we’ll try to resolve dependency (data model) of a dependency (services) from our existing solution. My controller depended on services and my services depended on data model. Now we’ll design an architecture in which components will be independent of each other in terms of object creation and instantiation. To achieve this we’ll make use of MEF(Managed Extensibility Framework) along with Unity Container and reflection.
Ideally, we should not be having the below code in our Bootstrapper class,
container.RegisterType().RegisterType(new HierarchicalLifetimeManager());

Managed Extensibility Framework (MEF)

You can have a read about Unity from msdn link. I am just quoting some lines from msdn,

“The Managed Extensibility Framework or MEF is a library for creating lightweight, extensible applications. It allows application developers to discover and use extensions with no configuration required. It also lets extension developers easily encapsulate code and avoid fragile hard dependencies. MEF not only allows extensions to be reused within applications, but across applications as well.”
“MEF is an integral part of the .NET Framework 4, and is available wherever the .NET Framework is used. You can use MEF in your client applications, whether they use Windows Forms, WPF, or any other technology, or in server applications that use ASP.NET.”

Creating a Dependency Resolver with Unity and MEF

Open your Visual studio, I am using VS 2010, you can use VS version 2010 or above. Load the solution.
Step 1: Right click solution explorer and add a new project named Resolver,
I have intentionally chosen this name, and you already know it why J
Step 2: Right click Resolver project and click on ManageNugetPackage, in the interface of adding new package, search Unity.MVC3 in online library,
Install the package to your solution.
Step 3: Right click resolver project and add a reference to System.ComponentModel.Composition.
You can find the dll into your GAC.I am using framework 4.0, so referring to the same version dll.
This DLL is the part of MEF and is already installed with .NET Framework 4.0 in the system GAC. This DLL provides classes that are very core of MEF.
Step 4: Just add an interface named IComponent to Resolver project that contains the initialization method named Setup. We’ll try to implement this interface into our Resolver class that we’ll create in our other projects like DataModel, Services and WebApI.
namespace Resolver
{
    /// <summary>
    /// Register underlying types with unity.
    /// </summary>
    public interface IComponent
    {
      
    }
}
Step 5: Before we declare our Setup method, just add one more interface responsible for serving as a contract to register types. I name this interface as IRegisterComponent,
namespace Resolver
{
    /// <summary>
    /// Responsible for registering types in unity configuration by implementing IComponent
    /// </summary>
    public interface IRegisterComponent
    {
        /// <summary>
        /// Register type method
        /// </summary>
        /// <typeparam name="TFrom"></typeparam>
        /// <typeparam name="TTo"></typeparam>
        /// <param name="withInterception"></param>
        void RegisterType(bool withInterception = false) where TTo : TFrom;
 
        /// <summary>
        /// Register type with container controlled life time manager
        /// </summary>
        /// <typeparam name="TFrom"></typeparam>
        /// <typeparam name="TTo"></typeparam>
        /// <param name="withInterception"></param>
        void RegisterTypeWithControlledLifeTime(bool withInterception = false) where TTo : TFrom;
    }
}
In this interface I have declared two methods, one RegisterType and other in to RegisterType with Controlled life time of the object, i.e. the life time of an object will be hierarchal in manner. This is kind of same like we do in Unity.
Step 6: Now declare Setup method on our previously created IComponent interface, that takes instance ofIRegisterComponent as a parameter,
void SetUp(IRegisterComponent registerComponent);
So our IComponent interface becomes,
namespace Resolver
{
    /// <summary>
    /// Register underlying types with unity.
    /// </summary>
    public interface IComponent
    {
        void SetUp(IRegisterComponent registerComponent);
    }
}
Step 6: Now we’ll write a packager or you can say a wrapper over MEF and Unity to register types/ components. This is the core MEF implementation. Create a class named ComponentLoader, and add following code to it,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Reflection;
 
namespace Resolver
{
    public static class ComponentLoader
    {
        public static void LoadContainer(IUnityContainer container, string path, string pattern)
        {
            var dirCat = new DirectoryCatalog(path, pattern);
            var importDef = BuildImportDefinition();
            try
            {
                using (var aggregateCatalog = new AggregateCatalog())
                {
                    aggregateCatalog.Catalogs.Add(dirCat);
 
                    using (var componsitionContainer = new CompositionContainer(aggregateCatalog))
                    {
                        IEnumerable exports = componsitionContainer.GetExports(importDef);
 
                        IEnumerable modules =
                            exports.Select(export => export.Value as IComponent).Where(m => m != null);
 
                        var registerComponent = new RegisterComponent(container);
                        foreach (IComponent module in modules)
                        {
                            module.SetUp(registerComponent);
                        }
                    }
                }
            }
            catch (ReflectionTypeLoadException typeLoadException)
            {
                var builder = new StringBuilder();
                foreach (Exception loaderException in typeLoadException.LoaderExceptions)
                {
                    builder.AppendFormat("{0}\n", loaderException.Message);
                }
 
                throw new TypeLoadException(builder.ToString(), typeLoadException);
            }
        }
 
        private static ImportDefinition BuildImportDefinition()
        {
            return new ImportDefinition(
                def => true, typeof(IComponent).FullName, ImportCardinality.ZeroOrMore, false, false);
        }
    }
 
    internal class RegisterComponent : IRegisterComponent
    {
        private readonly IUnityContainer _container;
 
        public RegisterComponent(IUnityContainer container)
        {
            this._container = container;
            //Register interception behaviour if any
        }
 
        public void RegisterType(bool withInterception = false) where TTo : TFrom
        {
            if (withInterception)
            {
                //register with interception
            }
            else
            {
                this._container.RegisterType();
            }
        }
 
        public void RegisterTypeWithControlledLifeTime(bool withInterception = false) where TTo : TFrom
        {
            this._container.RegisterType(new ContainerControlledLifetimeManager());
        }
    }
}
Step 7: Now our Resolver wrapper is ready. Build the project and add its reference to DataModel, BusinessServices and WebApi project like shown below,

Setup Business Services

We already have added reference of Resolver in BusinessServices project. We agreed to implement IComponent interface in each of our project.
So create a class named DependencyResolver and implement IComponent interface into it, we make use of reflection too to import IComponent type. So add a class and add following code to that DependencyResolverclass,
using System.ComponentModel.Composition;
using DataModel;
using DataModel.UnitOfWork;
using Resolver;
 
namespace BusinessServices
{
    [Export(typeof(IComponent))]
    public class DependencyResolver : IComponent
    {
        public void SetUp(IRegisterComponent registerComponent)
        {
            registerComponent.RegisterType();
 
        }
    }
}
Note that we have implemented SetUp method and in the same method we registered type for my ProductService.
All of the existing code base remains same. We don’t need to touch the IProductServices interface or ProductServices class.

Setup DataModel

We have added Resolver project reference to DataModel project as well. So we’ll try to register the type of UnitOfWork in this project. We proceed in same fashion, just add a DependencyResolver class and implement its Setup method to register type of UnitOfWork. To make the code more readable and standard, I made a change.I just added an interface for UnitOfWork and named it IUnitOfWork. Now my UnitOfWork class derives from this, you can do this exercise in earlier versions of projects we discussed in first two articles.
So my IUnitOfWork contains declaration of a single public method in UnitOfWork,
namespace DataModel.UnitOfWork
{
    public interface IUnitOfWork
    {
        /// <summary>
        /// Save method.
        /// </summary>
        void Save();
    }
}
Now register the type for UnitOfWork in DepenencyResolver class, our class becomes as shown below,
using System.ComponentModel.Composition;
using System.Data.Entity;
using DataModel.UnitOfWork;
using Resolver;
 
namespace DataModel
{
    [Export(typeof(IComponent))]
    public class DependencyResolver : IComponent
    {
        public void SetUp(IRegisterComponent registerComponent)
        {
            registerComponent.RegisterType();
        }
    }
}
Again, no need to touch any existing code of this project.

Setup REST endpoint / WebAPI project

Our 90% of the job is done.
We now need to setup or WebAPI project. We’ll not add any DependencyResolver class in this project. We’ll invert the calling mechanism of layers in Bootstrapper class that we already have, so when you open your bootstrapper class, you’ll get the code something like,
using System.Web.Http;
using System.Web.Mvc;
using BusinessServices;
using DataModel.UnitOfWork;
using Microsoft.Practices.Unity;
using Unity.Mvc3;
 
namespace WebApi
{
    public static class Bootstrapper
    {
        public static void Initialise()
        {
            var container = BuildUnityContainer();
 
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
 
            // register dependency resolver for WebAPI RC
            GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
        }
 
        private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();
 
            // register all your components with the container here
            // it is NOT necessary to register your controllers
           
            // e.g. container.RegisterType();       
            container.RegisterType().RegisterType(new HierarchicalLifetimeManager());
 
            return container;
        }
    }
}
Now, we need to change the code base a bit to make our system loosely coupled.Just remove the reference of DataModel from WebAPI project.
We don’t want our DataModel to be exposed to WebAPI project, that was our aim though, so we cut down the dependency of DataModel project now.
Add following code of Bootstrapper class to the existing Bootstarpper class,
using System.Web.Http;
//using DataModel.UnitOfWork;
using Microsoft.Practices.Unity;
using Resolver;
using Unity.Mvc3;
 
namespace WebApi
{
    public static class Bootstrapper
    {
        public static void  Initialise()
        {
            var container = BuildUnityContainer();
 
            System.Web.Mvc.DependencyResolver.SetResolver(new UnityDependencyResolver(container));
 
            // register dependency resolver for WebAPI RC
            GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
        }
 
        private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();
 
            // register all your components with the container here
            // it is NOT necessary to register your controllers
           
            // e.g. container.RegisterType();       
           // container.RegisterType().RegisterType(new HierarchicalLifetimeManager());
 
            RegisterTypes(container);
 
            return container;
        }
 
        public static void RegisterTypes(IUnityContainer container)
        {
 
            //Component initialization via MEF
            ComponentLoader.LoadContainer(container, ".\\bin", "WebApi.dll");
            ComponentLoader.LoadContainer(container, ".\\bin", "BusinessServices.dll");
 
        }
    }
}
It is kind of redefining Bootstrapper class without touching our existing controller methods. We now don’t even have to register type for ProductServices as well, we already did this in BusinessServices project.
Note that in RegisterTypes method we load components/dlls through reflection making use of ComponentLoader.We wrote two lines, first to load WebAPI.dll and another one to load Business Services.dll.
Had the name of BusinessServicess.dll be WebAPI.Services.dll, then we would have only written one line of code to load both the WebAPI and BusinessService dll like shown below,
ComponentLoader.LoadContainer(container, ".\\bin", "WebApi*.dll");
Yes we can make use of Regex.

Running the application

Just run the application, we get,
We already have our test client added, but for new readers, just go to Manage Nuget Packages, by right clicking WebAPI project and type WebAPITestClient in searchbox in online packages,
You’ll get “A simple Test Client for ASP.NET Web API”, just add it. You’ll get a help controller in Areas-> HelpPage like shown below,
I have already provided the database scripts and data in my previous article, you can use the same.
Append “/help” in the application url, and you’ll get the test client,
You can test each service by clicking on it. Once you click on the service link, you’ll be redirected to test the service page of that particular service. On that page there is a button Test API in the right bottom corner, just press that button to test your service,
Service for GetAllProduct,
For Create a new product,
In database, we get new product,
Update product:
We get in database,
Delete product:
In database:

Advantages of this design

In my earlier articles I focussed more on design flaws, but our current design have emerged with few added advantages,
  1. We got an extensible and loosely coupled application design that can go far with more new components added in the same way.
  2. Registering types automatically through reflection. Suppose we want to register any Interface implementation to our REST endpoint, we just need to load that dll in our Bootstrapper class, or if dll’s are of common suffix names then we just have to place that DLL in bin folder, and that will automatically be loaded at run time.
  3. Database transactions or any of such module is now not exposed to the service endpoint, this makes our service more secure and maintains the design structure too.

Conclusion

We now know how to use Unity container to resolve dependency and perform inversion of control using MEF too. In my next article I’ll try to explain how we can open multiple endpoints to our REST service and create custom url’s in the true REST fashion in my WebAPI. Till then Happy Coding Smile | :) You can also download the source code from GitHub. Add the required packages, if they are missing in the source code.

Download Source Code

RESTful Day #2: Inversion of control using dependency injection in Web API’s using Unity Container and Bootstrapper


Introduction

My article will explain how we can make our Web API service architecture loosely coupled and more flexible. We already learnt that how we can create a RESTful service using Asp.net Web API and Entity framework in my last article. If you remember we ended up in a solution with a design flaw, we’ll try to overcome that flaw by resolving the dependencies of dependent components. For those who have not followed my previous article, they can learn by having the sample project attached as a test application from my first article.

There are various methods you can use to resolve dependency of components. In my article I’ll explain how to resolve dependency with the help of Unity Container provided by Microsoft’s Unity Application Block.
We’ll not go into very detailed theory, for theory and understanding of DI and IOC you can follow the following links: Unity and Inversion of Control(IOC). We’ll straight away jump into practical implementation.

Roadmap

Our roadmap for learning RESTful APIs remains same,

I’ll purposely use Visual Studio 2010 and .NET Framework 4.0 because there are few implementations that are very hard to find in .NET Framework 4.0, but I’ll make it easy by showing how we can do it.

Existing Design and Problem

We already have an existing design. If you open the solution, you’ll get to see the structure as mentioned below,
The modules are dependent in a way,
There is no problem with the structure, but the way they interact to each other is really problematic. You must have noticed that we are trying to communicate with layers, making the physical objects of classes.
For e.g.
Controller constructor makes an object of Service layer to communicate,
        /// <summary>
        /// Public constructor to initialize product service instance
        /// </summary>
        public ProductController()
        {
            _productServices =new ProductServices();
        }
Service constructor, in turn, makes and object of UnitOfWork to communicate to database,
        /// <summary>
        /// Public constructor.
        /// </summary>
        public ProductServices()
        {
            _unitOfWork = new UnitOfWork();
        }
The problem lies in these code pieces. We see Controller is dependent upon instantiation of Service and Service is dependent upon UnitOfWork to get instantiated. Our Layers should not be that tightly coupled and should be dependent on each other.
The work of creating object should be assigned to someone else. Our layers should not worry about creating objects.
We’ll assign this role to a third party that will be called our container. Fortunately, Unity provides that help to us, to get rid of this dependency problem and invert the control flow by injecting dependency not by creating objects by new but through constructors or properties. There are other methods too, but I am not going into detail.

Introduction to Unity

You can have a read about Unity from this link; I am just quoting some lines,
“The Unity Application Block (Unity) is a lightweight, extensible dependency injection container that supports constructor injection, property injection, and method call injection. It provides developers with the following advantages:
  • It provides simplified object creation, especially for hierarchical object structures and dependencies, which simplifies application code.
  • It supports abstraction of requirements; this allows developers to specify dependencies at run time or in configuration and simplify management of crosscutting concerns.
  • It increases flexibility by deferring component configuration to the container.
  • It has a service location capability; this allows clients to store or cache the container. This is especially useful in ASP.NET Web applications where developers can persist the container in the ASP.NET session or application.”

Setup Unity

Open your Visual studio, I am using VS 2010, You can use VS version 2010 or above. Load the solution.
Step 1: browse to Tools-> Library Packet Manager – > Packet manager Console,
We’ll add package for Unity Application Block.
In the left bottom corner of Visual Studio, You’ll find where to write the command.
Type command Unity.MVC3 and choose “WebApi” project before you fire the command.
Step 2: Bootstrapper class
Unity.MVC3 comes with a Bootstrapper class, as soon as you run the command, the Bootstrapper class will be generated in your solution->WebAPI project,
using System.Web.Http;
using System.Web.Mvc;
using BusinessServices;
using DataModel.UnitOfWork;
using Microsoft.Practices.Unity;
using Unity.Mvc3;

namespace WebApi
{
    public static class Bootstrapper
    {
        public static void Initialise()
        {
            var container = BuildUnityContainer();

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));

            // register dependency resolver for WebAPI RC
            GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
        }

        private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();

            // register all your components with the container here
            // it is NOT necessary to register your controllers
            
            // e.g. container.RegisterType();        
            container.RegisterType().RegisterType(new HierarchicalLifetimeManager());

            return container;
        }
    }
}
This class comes with an initial configuration to setup your container. All the functionality is inbuilt, we only need to specify the dependencies that we need to resolve in the “BuildUnityContainer“, like it says in the commented statement,
            // register all your components with the container here
            // it is NOT necessary to register your controllers
            
            // e.g. container.RegisterType();
Step 3: Just specify the components below these commented lines that we need to resolve. In our case, it’sProductServices and UnitOfWork, so just add,
container.RegisterType().RegisterType(new HierarchicalLifetimeManager());
HierarchicalLifetimeManager” maintains the lifetime of the object and child object depends upon parent object’s lifetime.
If you don’t find “UnitOfWork“, just add reference to DataModel project in WebAPI project.
So our Bootstrapper class becomes,
   public static class Bootstrapper
    {
        public static void Initialise()
        {
            var container = BuildUnityContainer();

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));

            // register dependency resolver for WebAPI RC
            GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
        }

        private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();

            // register all your components with the container here
            // it is NOT necessary to register your controllers
            
            // e.g. container.RegisterType();        
            container.RegisterType().RegisterType(new HierarchicalLifetimeManager());

            return container;
        }
Like this we can also specify other dependent objects in BuildUnityContainerMethod.
Step 4: Now we need to call the Initialise method of Bootstrapper class. Note , we need the objects as soon as our modules load, therefore we require the container to do its work at the time of application load, therefore go to Global.asax file and add one line to call Initialise method, since this is a static method, we can directly call it using class name,
Bootstrapper.Initialise();
Our global.asax becomes,
using System.Linq;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Newtonsoft.Json;
using WebApi.App_Start;

namespace WebApi
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            //Initialise Bootstrapper
            Bootstrapper.Initialise();

            //Define Formatters
            var formatters = GlobalConfiguration.Configuration.Formatters;
            var jsonFormatter = formatters.JsonFormatter;
            var settings = jsonFormatter.SerializerSettings;
            settings.Formatting = Formatting.Indented;
            // settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            var appXmlType = formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
            formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

            //Add CORS Handler
            GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());
        }
    }
}
Half of the job is done. We now need to touchbase our controller and Service class constructors to utilize the instances already created for them at application load.

Setup Controller

We have already set up unity in our application. There are various methods in which we can inject dependency, like constructor injection, property injection, via service locator. I am here using Constructor Injection, because I find it best method to use with Unity Container to resolve dependency.
Just go to your ProductController, you find your constructor written as,
        /// <summary>
        /// Public constructor to initialize product service instance
        /// </summary>
        public ProductController()
        {
            _productServices =new ProductServices();
        }
Just add a parameter to your constructor that takes your ProductServices reference, like we did below
       /// <summary>
        /// Public constructor to initialize product service instance
        /// </summary>
        public ProductController(IProductServices productServices)
        {
            _productServices = productServices;
        }
And initialize your “productServices” variable with the parameter. In this case when the constructor of the controller is called, It will be served with pre-instantiated service instance, and does not need to create an instance of the service, our unity container did the job of object creation.

Setup Services

For services too, we proceed in a same fashion. Just open your ProductServices class, we see the dependency of UnitOfWork here as,
        /// <summary>
        /// Public constructor.
        /// </summary>
        public ProductServices()
        {
            _unitOfWork = new UnitOfWork();
        }
Again, we perform the same steps ,and pass a parameter of type UnitOfWork to our constructor,
Our code becomes,
        /// <summary>
        /// Public constructor.
        /// </summary>
        public ProductServices(UnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }
Here also we’ll get the pre instantiated object on UnitOfWork. So service does need to worry about creating objects. Remember we did .RegisterType() in Bootstrapper class.
We have now made our components independent.

Running the application

Our job is almost done.We need to run the application, Just hit F5. To our surprise we’ll end up in an error page,
Do you remember we added a test client to our project to test our API in my first article. That test client have a controller too, we need to override its settings to make our application work.Just go to Areas->HelpPage->Controllers->HelpController in WebAPI project like shown below,
Comment out the existing constructors and add a Configuration property like shown below,
      //Remove constructors and existing Configuration property.

        //public HelpController()
        //    : this(GlobalConfiguration.Configuration)
        //{
        //}

        //public HelpController(HttpConfiguration config)
        //{
        //    Configuration = config;
        //}

        //public HttpConfiguration Configuration { get; private set; }

        /// <summary>
        /// Add new Configuration Property
        /// </summary>
        protected static HttpConfiguration Configuration
        {
            get { return GlobalConfiguration.Configuration; }
        }
Our controller code becomes,
using System;
using System.Web.Http;
using System.Web.Mvc;
using WebApi.Areas.HelpPage.Models;

namespace WebApi.Areas.HelpPage.Controllers
{
    /// <summary>
    /// The controller that will handle requests for the help page.
    /// </summary>
    public class HelpController : Controller
    {
        //Remove constructors and existing Configuration property.

        //public HelpController()
        //    : this(GlobalConfiguration.Configuration)
        //{
        //}

        //public HelpController(HttpConfiguration config)
        //{
        //    Configuration = config;
        //}

        //public HttpConfiguration Configuration { get; private set; }

        /// <summary>
        /// Add new Configuration Property
        /// </summary>
        protected static HttpConfiguration Configuration
        {
            get { return GlobalConfiguration.Configuration; }
        }

        public ActionResult Index()
        {
            return View(Configuration.Services.GetApiExplorer().ApiDescriptions);
        }

        public ActionResult Api(string apiId)
        {
            if (!String.IsNullOrEmpty(apiId))
            {
                HelpPageApiModel apiModel = Configuration.GetHelpPageApiModel(apiId);
                if (apiModel != null)
                {
                    return View(apiModel);
                }
            }

            return View("Error");
        }
    }
}
Just run the application, we get,
We alreay have our test client added, but for new readers, I am just again explaining on how to add a test client to our API project.
Just go to Manage Nuget Packages, by right clicking WebAPI project and type WebAPITestClient in searchbox in online packages,
You’ll get “A simple Test Client for ASP.NET Web API”, just add it. You’ll get a help controller in Areas-> HelpPage like shown below,
I have already provided the database scripts and data in my previous article, you can use the same.
Append “/help” in the application url, and you’ll get the test client,
You can test each service by clicking on it.
Service for GetAllProduct,
For Create a new product,
In database, we get new product,
Update product:
We get in database,
Delete product:
In database:
Job done.

Design Flaws

What if I say there are still flaws in this design, the design is still not loosely coupled.
Do you remember what we decided while writing our first application?
Our API talks to Services and Services talk to DataModel. We’ll never allow DataModel talk to APIs for security reasons. But did you notice that when we were registering the type in Bootstrapper class, we also registered the type of UnitOfWork that means we added DataModel as a reference to our API project. This is a design breach. We tried to resolve dependency of a dependency by violating our design and compromising security.
In my next article, we’ll overcome this situation, we’ll try to resolve dependency and its dependency without violating our design and compromising security. In fact we’ll make it more secure and loosely coupled.
In my next article we’ll make use of Managed Extensibility Framework(MEF) to achieve the same.

Conclusion

We now know how to use Unity container to resolve dependency and perform inversion of control.
But still there are some flaws in this design. In my next article, I’ll try to make the system more strong. Till then Happy Coding  :-). You can also download the source code from GitHub. Add the required packages, if they are missing in the source code.

RESTful Day #1: Enterprise Level Application Architecture with Web API’s using Entity Framework, Generic Repository Pattern and Unit of Work


Introduction

I have been practicing, reading a lot about RESTful services for past few days. To my surprise I could not find a complete series of practical implementations of ASP.NET Web API’s on the web. My effort in this series will be to focus on how we can develop basic enterprise level application architecture with Web API’s.
We’ll be discussing less theory and doing more practical to understand how RESTful services can be created using an ORM, we choose Entity Framework here. My first article in the series is to set up a basic architecture of REST service based application. Later on in my upcoming articles, I’ll explain how we can follow best standards to achieve enterprise level architecture.

Roadmap

 My road for the series is as follows,
I’ll purposely use Visual Studio 2010 and .NET Framework 4.0 because there are few implementations that are very hard to find in .NET Framework 4.0, but I’ll make it easy by showing how we can do it.

REST

Here is an extract from Wikipedia,
Unlike SOAP-based web services, there is no “official” standard for RESTful web APIs. This is because REST is an architectural style, while SOAP is a protocol. Even though REST is not a standard per se, most RESTful implementations make use of standards such as HTTP, URI, JSON, and XML.
I agree to it . Let’s do some coding.

Setup database

I am using SQL Server 2008 as a database server. I have provided the sql scripts to create the database in Sql Server, you can use the same to create one.I have given WebApiDb as my database name. My database contains three tables for now, Products, Tokens, User. In this tutorial we’ll only be dealing with product table to perform CURD operations using Web API and Entity framework. We’ll use Tokens and User in my upcoming article. For those who fail to create database through scripts, here is the structure you can follow,

Web API project

Open your Visual Studio, I am using VS 2010, You can use VS version 2010 or above.
Step 1: Create a new Project in your visual studio,
Step 2: There after choose to create ASP.NET MVC 4 Web application, and give it a name of your choice, I gave itWebAPI.
Step 3: Out of different type of project templates shown to you, choose Web API project,
Once done, you’ll get a project structure like shown below, with a default Home and Values controller.
You can choose to delete this ValuesController, as we’ll be using our own controller to learn.

Setup Data Access Layer

Let’s setup or data access layer first. We’ll be using Entity Framework 5.0 to talk to database. We’ll use Generic Repository Pattern and Unit of work pattern to standardize our layer.
Let’s have a look at the standard definition of Entity Framework given by Microsoft:
“The Microsoft ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework that enables developers to work with relational data as domain-specific objects, eliminating the need for most of the data access plumbing code that developers usually need to write. Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects. The Entity Framework’s ORM implementation provides services like change tracking, identity resolution, lazy loading, and query translation so that developers can focus on their application-specific business logic rather than the data access fundamentals.”
In simple language, Entity framework is an Object/Relational Mapping (ORM) framework. It is an enhancement to ADO.NET, an upper layer to ADO.NET that gives developers an automated mechanism for accessing and storing the data in the database.
Step 1 : Create a new class library in your visual studio, and name it DataModel as shown below,
Step2: In the same way, create one more project i.e. again a class library and call it BusinessEntities,
I’ll explain the use of this class library soon.
Step 3: Move on to your DataModel project , right click on it and add a new item, in the list shown, choose ADO.NET Data Model, and name it WebApiDataModel.edmx.
The file .edmx will contain the database information of our database that we created earlier, let’s set up this. You’ll be presented a wizard like follows,
Choose, generate from database. Choose Microsoft SQl Server like shown in the following image,
Click continue, then provide the credentials of your database, i.e. WebAPIdb, and connect it,
You’ll get a screen, showing the connection string of the database we chose,
Provide the name of the connection string as WebApiDbEntities and click Next.
Choose all the database objects, check all the check boxes, and provide a name for the model. I gave it a name WebApiDbModel.
Once you finish this wizard, you’ll get the schema ready in your datamodel project as follows,
We’ve got our schema in-place using Entity Framework. But few work is still remaining. We need our data context class and entities through which we’ll communicate with database.
So, moving on to next step.
Step 3: Click on tools in Visual Studio and open Extension manager. We need to get db context generator for our datamodel. We can also do it using default code generation item by right clicking in the edmx view and add code generation item, but that will generate object context class and that is heavier than db context. I want light weighted db context class to be created, so we’ll use extension manager to add a package and then create a db context class.
Search for Entity Framework Dbcontext generator in online gallery and select the one for EF 5.x like below,
I guess you need to restart Visual studio to get that into your templates.
Step 4 : Now right click in the .edmx file schema designer and choose “Add Code Generation Item..”.
Step 5 : Now you’ll see that we have got the template for the extension that we added, select that EF 5.x DbContext Generator and click Add.
After adding this we’ll get the db context class and its properties, this class is responsible for all database transactions that we need to perform, so our structure looks like as shown below,
Wow, we ended up in errors. But we got our db context class and our entity models, You can see them in our DataModel project. Errors? Nothing to worry about, it’s just we did not reference entity framework in our project. We’ll do it right away.
Step 6 : Go to Tools -> Library Packet Manager->Packet manager Console. You’ll get the console in left bottom of Visual studio.
Select dataModel project and write a command “Install-Package EntityFramework –Version 5.0.0” to install Entity Framework 5 in our DataModel project.
Press enter. And all the errors get resolved.

Generic Repository and Unit of Work

You can read about repository pattern and creating a repository in detail from my article :https://codeteddy.com/2013/09/03/learning-mvc-part-5repository-pattern-in-mvc3-application-with-entity-framework/.
Just to list down the benefits of Repository pattern,
  • It centralizes the data logic or Web service access logic.
  • It provides a substitution point for the unit tests.
  • It provides a flexible architecture that can be adapted as the overall design of the application evolves.
We’ll create a generic repository that works for all our entities. Creating repositories for each and every entity may result in lots of duplicate code in large projects.For creating Generic Repository you can follow : https://codeteddy.com/2013/09/03/learning-mvc-part-6-generic-repository-pattern-in-mvc3-application-with-entity-framework/
Step 1: Add a folder named GenericRepository in DataModel project and to that folder add a class named Generic Repository. Add following code to that class, that servers as a template based generic code for all the entities that will interact with database,
#region Using Namespaces...

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;

#endregion

namespace DataModel.GenericRepository
{
/// <summary>
    /// Generic Repository class for Entity Operations
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    public class GenericRepository where TEntity : class
    {
#region Private member variables...
internal WebApiDbEntities Context;
internal DbSet DbSet;
#endregion

#region Public Constructor...
/// <summary>
        /// Public Constructor,initializes privately declared local variables.
        /// </summary>
        /// <param name="context"></param>
        public GenericRepository(WebApiDbEntities context)
        {
this.Context = context;
this.DbSet = context.Set();
        }
#endregion

#region Public member methods...

/// <summary>
        /// generic Get method for Entities
        /// </summary>
        /// <returns></returns>
        public virtual IEnumerable Get()
        {
            IQueryable query = DbSet;
return query.ToList();
        }

/// <summary>
        /// Generic get method on the basis of id for Entities.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual TEntity GetByID(object id)
        {
return DbSet.Find(id);
        }

/// <summary>
        /// generic Insert method for the entities
        /// </summary>
        /// <param name="entity"></param>
        public virtual void Insert(TEntity entity)
        {
            DbSet.Add(entity);
        }

/// <summary>
        /// Generic Delete method for the entities
        /// </summary>
        /// <param name="id"></param>
        public virtual void Delete(object id)
        {
            TEntity entityToDelete = DbSet.Find(id);
            Delete(entityToDelete);
        }

/// <summary>
        /// Generic Delete method for the entities
        /// </summary>
        /// <param name="entityToDelete"></param>
        public virtual void Delete(TEntity entityToDelete)
        {
if (Context.Entry(entityToDelete).State == EntityState.Detached)
            {
                DbSet.Attach(entityToDelete);
            }
            DbSet.Remove(entityToDelete);
        }

/// <summary>
        /// Generic update method for the entities
        /// </summary>
        /// <param name="entityToUpdate"></param>
        public virtual void Update(TEntity entityToUpdate)
        {
            DbSet.Attach(entityToUpdate);
            Context.Entry(entityToUpdate).State = EntityState.Modified;
        }

/// <summary>
        /// generic method to get many record on the basis of a condition.
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public virtual IEnumerable GetMany(Func<TEntity, bool> where)
        {
return DbSet.Where(where).ToList();
        }

/// <summary>
        /// generic method to get many record on the basis of a condition but query able.
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public virtual IQueryable GetManyQueryable(Func<TEntity, bool> where)
        {
return DbSet.Where(where).AsQueryable();
        }

/// <summary>
        /// generic get method , fetches data for the entities on the basis of condition.
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public TEntity Get(Func<TEntity, Boolean> where)
        {
return DbSet.Where(where).FirstOrDefault();
        }

/// <summary>
        /// generic delete method , deletes data for the entities on the basis of condition.
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public void Delete(Func<TEntity, Boolean> where)
        {
            IQueryable objects = DbSet.Where(where).AsQueryable();
foreach (TEntity obj in objects)
                DbSet.Remove(obj);
        }

/// <summary>
        /// generic method to fetch all the records from db
        /// </summary>
        /// <returns></returns>
        public virtual IEnumerable GetAll()
        {
return DbSet.ToList();
        }

/// <summary>
        /// Inclue multiple
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="include"></param>
        /// <returns></returns>
        public IQueryable GetWithInclude(
            System.Linq.Expressions.Expression<Func<TEntity, 
bool>> predicate, params string[] include)
        {
            IQueryable query = this.DbSet;
            query = include.Aggregate(query, (current, inc) => current.Include(inc));
return query.Where(predicate);
        }

/// <summary>
        /// Generic method to check if entity exists
        /// </summary>
        /// <param name="primaryKey"></param>
        /// <returns></returns>
        public bool Exists(object primaryKey)
        {
return DbSet.Find(primaryKey) != null;
        }

/// <summary>
        /// Gets a single record by the specified criteria (usually the unique identifier)
        /// </summary>
        /// <param name="predicate">Criteria to match on</param>
        /// <returns>A single record that matches the specified criteria</returns>
        public TEntity GetSingle(Func<TEntity, bool> predicate)
        {
return DbSet.Single(predicate);
        }

/// <summary>
        /// The first record matching the specified criteria
        /// </summary>
        /// <param name="predicate">Criteria to match on</param>
        /// <returns>A single record containing the first record matching the specified criteria</returns>
        public TEntity GetFirst(Func<TEntity, bool> predicate)
        {
return DbSet.First(predicate);
        }


#endregion
    }
}

Unit of Work

Again I’ll not explain in detail what Unit of Work is. You can google about the theory or follow my existing article on MVC with Unit of Work.
To give a heads up, again from my existing article, the important responsibilities of Unit of Work are,
  • To manage transactions.
  • To order the database inserts, deletes, and updates.
  • To prevent duplicate updates. Inside a single usage of a Unit of Work object, different parts of the code may mark the same Invoice object as changed, but the Unit of Work class will only issue a single UPDATE command to the database.
The value of using a Unit of Work pattern is to free the rest of our code from these concerns so that you can otherwise concentrate on business logic.
Step 1: Create a folder named UnitOfWork, add a class to that folder named UnitOfWork.cs,
Add GenericRepository properties for all the three entities that we got. The class also implementsIDisposableinterface and it’s method Dispose to free up connections and objects. The class will be as follows,
#region Using Namespaces...

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Data.Entity.Validation;
using DataModel.GenericRepository;

#endregion

namespace DataModel.UnitOfWork
{
/// <summary>
    /// Unit of Work class responsible for DB transactions
    /// </summary>
    public class UnitOfWork : IDisposable
    {
#region Private member variables...

private WebApiDbEntities _context = null;
private GenericRepository _userRepository;
private GenericRepository _productRepository;
private GenericRepository _tokenRepository;
#endregion

public UnitOfWork()
        {
            _context = new WebApiDbEntities();
        }

#region Public Repository Creation properties...

/// <summary>
        /// Get/Set Property for product repository.
        /// </summary>
        public GenericRepository ProductRepository
        {
get
            {
if (this._productRepository == null)
this._productRepository = new GenericRepository(_context);
return _productRepository;
            }
        }

/// <summary>
        /// Get/Set Property for user repository.
        /// </summary>
        public GenericRepository UserRepository
        {
get
            {
if (this._userRepository == null)
this._userRepository = new GenericRepository(_context);
return _userRepository;
            }
        }

/// <summary>
        /// Get/Set Property for token repository.
        /// </summary>
        public GenericRepository TokenRepository
        {
get
            {
if (this._tokenRepository == null)
this._tokenRepository = new GenericRepository(_context);
return _tokenRepository;
            }
        }
#endregion

#region Public member methods...
/// <summary>
        /// Save method.
        /// </summary>
        public void Save()
        {
try
            {
                _context.SaveChanges();
            }
catch (DbEntityValidationException e)
            {

var outputLines = new List<string>();
foreach (var eve in e.EntityValidationErrors)
                {
                    outputLines.Add(string.Format(
"{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:", DateTime.Now, 
                        eve.Entry.Entity.GetType().Name, eve.Entry.State));
foreach (var ve in eve.ValidationErrors)
                    {
                        outputLines.Add(string.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage));
                    }
                }
                System.IO.File.AppendAllLines(@"C:\errors.txt", outputLines);

throw e;
            }

        }

#endregion

#region Implementing IDiosposable...

#region private dispose variable declaration...
private bool disposed = false; 
#endregion

/// <summary>
        /// Protected Virtual Dispose method
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
if (!this.disposed)
            {
if (disposing)
                {
                    Debug.WriteLine("UnitOfWork is being disposed");
                    _context.Dispose();
                }
            }
this.disposed = true;
        }

/// <summary>
        /// Dispose method
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        } 
#endregion
    }
}
Now we have completely set up our data access layer, and our project structure looks like as shown below,

Setup Business Entities

Remember, we created a business entities project. You may wonder, we already have database entities to interact with database then why do we need Business Entities? The answer is as simple as that, we are trying to follow a proper structure of communication, and one would never want to expose the database entities to the end client, in our case is Web API, it involves lot of risk. Hackers may manipulate the details and get accessto your database.Instead we’ll use database entities in our business logic layer and use Business Entities as transfer objects to communicate between business logic and Web API project. So business entities may have different names but, their properties remains same as database entities. In our case we’ll add same name business entity classes appendint word “Entity” to them in our BusinessEntity project. So we’ll end up having three classes as follows,

Product entity

public class ProductEntity
    {
public int ProductId { get; set; }
public string ProductName { get; set; }
    }

Token entity

public class TokenEntity
    {
public int TokenId { get; set; }
public int UserId { get; set; }
public string AuthToken { get; set; }
public System.DateTime IssuedOn { get; set; }
public System.DateTime ExpiresOn { get; set; }
    }

User entity

public class UserEntity
    {
public int UserId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Name { get; set; }
    }

Setup Business Services Project

Add a new class library to the solution named BusinessServices. This layer will act as our business logic layer. Note that, we can make use of our API controllers to write business logic, but I am trying to segregate my business logic in an extra layer so that if in future I want to use WCF, MVC, ASP.NET Web Pages or any other application as my presentation layer then I can easily integrate my Business logic layer in it.
We’ll make this layer testable, so we need to create an interface in and declare CURD operations that we need to perform over product table.Before we proceed, add the reference of BusinessEntities project and DataModel project to this newly created project
Step 1 : Create an interface named IProductServices and add following code to it for CURD operations methods,
using System.Collections.Generic;
using BusinessEntities;

namespace BusinessServices
{
/// <summary>
    /// Product Service Contract
    /// </summary>
    public interface IProductServices
    {
        ProductEntity GetProductById(int productId);
        IEnumerable GetAllProducts();
int CreateProduct(ProductEntity productEntity);
bool UpdateProduct(int productId,ProductEntity productEntity);
bool DeleteProduct(int productId);
    }
}
Step 2 : Create a class to implement this interface.name that class ProductServices,
The class contains a private variable of UnitOfWork and a constructor to initialize that variable,
private readonly UnitOfWork _unitOfWork;

/// <summary>
        /// Public constructor.
        /// </summary>
        public ProductServices()
        {
            _unitOfWork = new UnitOfWork();
        }
We have decided not to expose our db entities to Web API project, so we need something to map the db entities data to my business entity classes. We’ll make use of AutoMapper.You can read about AutoMapper in my this article.
Step 3: Just right click project-> Extension manager, search for AutoMapper in online galary and add to BusinessServices project,
Step 4: Implement methods in ProductServices class,
Add following code to the class,
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using AutoMapper;
using BusinessEntities;
using DataModel;
using DataModel.UnitOfWork;

namespace BusinessServices
{
/// <summary>
    /// Offers services for product specific CRUD operations
    /// </summary>
    public class ProductServices:IProductServices
    {
private readonly UnitOfWork _unitOfWork;

/// <summary>
        /// Public constructor.
        /// </summary>
        public ProductServices()
        {
            _unitOfWork = new UnitOfWork();
        }

/// <summary>
        /// Fetches product details by id
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public BusinessEntities.ProductEntity GetProductById(int productId)
        {
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
            {
                Mapper.CreateMap();
var productModel = Mapper.Map(product);
return productModel;
            }
return null;
        }

/// <summary>
        /// Fetches all the products.
        /// </summary>
        /// <returns></returns>
        public IEnumerable GetAllProducts()
        {
var products = _unitOfWork.ProductRepository.GetAll().ToList();
if (products.Any())
            {
                Mapper.CreateMap();
var productsModel = Mapper.Map<List, List>(products);
return productsModel;
            }
return null;
        }

/// <summary>
        /// Creates a product
        /// </summary>
        /// <param name="productEntity"></param>
        /// <returns></returns>
        public int CreateProduct(BusinessEntities.ProductEntity productEntity)
        {
using (var scope = new TransactionScope())
            {
var product = new Product
                {
                    ProductName = productEntity.ProductName
                };
                _unitOfWork.ProductRepository.Insert(product);
                _unitOfWork.Save();
                scope.Complete();
return product.ProductId;
            }
        }

/// <summary>
        /// Updates a product
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="productEntity"></param>
        /// <returns></returns>
        public bool UpdateProduct(int productId, BusinessEntities.ProductEntity productEntity)
        {
var success = false;
if (productEntity != null)
            {
using (var scope = new TransactionScope())
                {
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
                    {
                        product.ProductName = productEntity.ProductName;
                        _unitOfWork.ProductRepository.Update(product);
                        _unitOfWork.Save();
                        scope.Complete();
                        success = true;
                    }
                }
            }
return success;
        }

/// <summary>
        /// Deletes a particular product
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public bool DeleteProduct(int productId)
        {
var success = false;
if (productId > 0)
            {
using (var scope = new TransactionScope())
                {
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
                    {

                        _unitOfWork.ProductRepository.Delete(product);
                        _unitOfWork.Save();
                        scope.Complete();
                        success = true;
                    }
                }
            }
return success;
        }
    }
}
Let me explain the idea of the code. We have 5 methods as follows,
  1. To get product by id ( GetproductById ) : We call repository to get the product by id. Id comes as a parameter from the calling method to that service method. It returns the product entity from the database. Note that it will not return the exact db entity, instead we’ll map it with our business entity usingAutoMapper and return it to calling method.
    /// <summary>
            /// Fetches product details by id
            /// </summary>
            /// <param name="productId"></param>
            /// <returns></returns>
            public BusinessEntities.ProductEntity GetProductById(int productId)
            {
    var product = _unitOfWork.ProductRepository.GetByID(productId);
    if (product != null)
                {
                    Mapper.CreateMap();
    var productModel = Mapper.Map(product);
    return productModel;
                }
    return null;
            }
  2. Get all products from database (GetAllProducts) : This method returns all the products residing in database, again we make use of AutoMapper to map the list and return back.
    /// <summary>
            /// Fetches all the products.
            /// </summary>
            /// <returns></returns>
            public IEnumerable GetAllProducts()
            {
    var products = _unitOfWork.ProductRepository.GetAll().ToList();
    if (products.Any())
                {
                    Mapper.CreateMap();
    var productsModel = Mapper.Map<List, List>(products);
    return productsModel;
                }
    return null;
            }
  3. Create a new product (CreateProduct) : This method takes productBusinessEntity as an argument and creates a new object of actual database entity and insert it using unit of work.
    /// <summary>
            /// Creates a product
            /// </summary>
            /// <param name="productEntity"></param>
            /// <returns></returns>
            public int CreateProduct(BusinessEntities.ProductEntity productEntity)
            {
    using (var scope = new TransactionScope())
                {
    var product = new Product
                    {
                        ProductName = productEntity.ProductName
                    };
                    _unitOfWork.ProductRepository.Insert(product);
                    _unitOfWork.Save();
                    scope.Complete();
    return product.ProductId;
                }
            }
I guess you can now write update and delete methods. So I am writing the code of complete class,
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using AutoMapper;
using BusinessEntities;
using DataModel;
using DataModel.UnitOfWork;

namespace BusinessServices
{
/// <summary>
    /// Offers services for product specific CRUD operations
    /// </summary>
    public class ProductServices:IProductServices
    {
private readonly UnitOfWork _unitOfWork;

/// <summary>
        /// Public constructor.
        /// </summary>
        public ProductServices()
        {
            _unitOfWork = new UnitOfWork();
        }

/// <summary>
        /// Fetches product details by id
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public BusinessEntities.ProductEntity GetProductById(int productId)
        {
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
            {
                Mapper.CreateMap();
var productModel = Mapper.Map(product);
return productModel;
            }
return null;
        }

/// <summary>
        /// Fetches all the products.
        /// </summary>
        /// <returns></returns>
        public IEnumerable GetAllProducts()
        {
var products = _unitOfWork.ProductRepository.GetAll().ToList();
if (products.Any())
            {
                Mapper.CreateMap();
var productsModel = Mapper.Map<List, List>(products);
return productsModel;
            }
return null;
        }

/// <summary>
        /// Creates a product
        /// </summary>
        /// <param name="productEntity"></param>
        /// <returns></returns>
        public int CreateProduct(BusinessEntities.ProductEntity productEntity)
        {
using (var scope = new TransactionScope())
            {
var product = new Product
                {
                    ProductName = productEntity.ProductName
                };
                _unitOfWork.ProductRepository.Insert(product);
                _unitOfWork.Save();
                scope.Complete();
return product.ProductId;
            }
        }

/// <summary>
        /// Updates a product
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="productEntity"></param>
        /// <returns></returns>
        public bool UpdateProduct(int productId, BusinessEntities.ProductEntity productEntity)
        {
var success = false;
if (productEntity != null)
            {
using (var scope = new TransactionScope())
                {
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
                    {
                        product.ProductName = productEntity.ProductName;
                        _unitOfWork.ProductRepository.Update(product);
                        _unitOfWork.Save();
                        scope.Complete();
                        success = true;
                    }
                }
            }
return success;
        }

/// <summary>
        /// Deletes a particular product
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public bool DeleteProduct(int productId)
        {
var success = false;
if (productId > 0)
            {
using (var scope = new TransactionScope())
                {
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
                    {

                        _unitOfWork.ProductRepository.Delete(product);
                        _unitOfWork.Save();
                        scope.Complete();
                        success = true;
                    }
                }
            }
return success;
        }
    }
}
Job done at business service level. Let’s move on to API controller to call these methods.

Setup WebAPI project

Step1 : Just add the reference of BusinessEntity and BusinessService in the WebAPI project, our architecture becomes like this,
Step 2: Add a new WebAPI controller in Controller folder. Right click Controller folder and add a new controller.
We get a controller as follows,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace WebApi.Controllers
{
public class ProductController : ApiController
    {
// GET api/product
        public IEnumerable<string> Get()
        {
return new string[] { "value1", "value2" };
        }

// GET api/product/5
        public string Get(int id)
        {
return "value";
        }

// POST api/product
        public void Post([FromBody]string value)
        {
        }

// PUT api/product/5
        public void Put(int id, [FromBody]string value)
        {
        }

// DELETE api/product/5
        public void Delete(int id)
        {
        }
    }
}
We get HTTP VERBS as method names. Web API is smart enough to recognize request with the name of the VERB itself. In our case we are doing CRUD operations, so we don’t need to change the names of the method, we just needed this. We only have to write calling logic inside these methods. In my upcoming articles of the series, we will figure out how we can define new routes and provide method names of our choice with those routes.
Step 3: Add logic to call Business Service methods, just make an object of Business Service and call its respective methods, our Controller class becomes like,
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using BusinessEntities;
using BusinessServices;

namespace WebApi.Controllers
{
public class ProductController : ApiController
    {

private readonly IProductServices _productServices;

#region Public Constructor

/// <summary>
        /// Public constructor to initialize product service instance
        /// </summary>
        public ProductController()
        {
            _productServices =new ProductServices();
        }

#endregion

// GET api/product
        public HttpResponseMessage Get()
        {
var products = _productServices.GetAllProducts();
if (products != null)
            {
var productEntities = products as List ?? products.ToList();
if (productEntities.Any())
return Request.CreateResponse(HttpStatusCode.OK, productEntities);
            }
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Products not found");
        }

// GET api/product/5
        public HttpResponseMessage Get(int id)
        {
var product = _productServices.GetProductById(id);
if (product != null)
return Request.CreateResponse(HttpStatusCode.OK, product);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for this id");
        }

// POST api/product
        public int Post([FromBody] ProductEntity productEntity)
        {
return _productServices.CreateProduct(productEntity);
        }

// PUT api/product/5
        public bool Put(int id, [FromBody]ProductEntity productEntity)
        {
if (id  > 0)
            {
return _productServices.UpdateProduct(id, productEntity);
            }
return false;
        }

// DELETE api/product/5
        public bool Delete(int id)
        {
if (id > 0)
return _productServices.DeleteProduct(id);
return false;
        }
    }
}
Just run the application, we get,
But now how do we test our API? We don’t have client. Guys, we’ll not be writing a client now to test it.We’ll add a package that will do all our work.
Just go to Manage Nuget Packages, by right clicking WebAPI project and type WebAPITestClient in searchbox in online packages,
You’ll get “A simple Test Client for ASP.NET Web API”, just add it. You’ll get a help controller in Areas-> HelpPage like shown below,

Running the Application

Before running the application, I have put some test data in our product table.
Just hit F5, you get the same page as you got earlier, just append “/help” in its url, and you’ll get the test client,
You can test each service by clicking on it.
Service for GetAllProduct,
For Create a new product,
In database, we get new product,
Update product:
We get in database,
Delete product:
In database:
Job done.

Design Flaws

  1. Architecture is tightly coupled. IOC (Inversion of Control) needs to be there.
  2. We cannot define our own routes.
  3. No exception handling and logging.
  4. No unit tetsts.

Conclusion

We now know how to create a WebAPI and perform CRUD operations using n layered architecture.
But still there are some flaws in this design.In my next two articles I’ll explain how to make the system loosely coupled using Dependency Injection Principle. We’ll also cover all the design flaws to make our design better and stronger. Till then Happy Coding J You can also download the source code from GitHub.

Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)


Introduction

My article of the series “Diving in OOP” will explain enum datatype in C#. We’ll learn by doing hands on lab and not only by theory. We’ll explore the power of enum and will cover almost every scenario in which we can use enum. We’ll follow a practical approach of learning to understand this concept. We may come across complex examples to understand the concept more deeply.

Enums (The Definition)

Let’s start with the definition taken from MSDN:

“The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list.
Usually it is best to define an enum directly within a namespace so that all classes in the namespace can access it with equal convenience. However, an enum can also be nested within a class or struct.
By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. For example, in the following enumeration, Sat is 0, Sun is 1, Mon is 2, and so forth.”

Pre-requisites

I expect that my readers of this article should have very basic knowledge of C# and I always wish that my readers should enjoy while reading this article. Also, keep writing programs by yourself that are given as examples in this article, to get hands on and understand the concept more deeply.

Roadmap

Let’s recall our road map.

A Practical Approach

Enum plays almost the same responsibility as the class does, i.e., creating a new data type, and it exists at the same level as class, interfaces or structs.
Just open your Visual Studio and add a console application named Enums. You’ll get Program.cs class.
Note: Each and every code snippet in this article is tried and tested.
Declare an enum at the same level as of Program class, call it as Color.

Program.cs

namespace Enums
{
class Program
    {
static void Main(string[] args)
        {
        }
    }

enum Color
{
Yellow,
Blue,
Brown,
Green
}
}

In the above mentioned example, we created a new datatype with the help of enum. The datatype is Colorhaving four distinct values, Yellow,BlueBrown and Green. The text that we write inside the declared enum could be anything of your wish; it just provides a custom enumerated list to you.
Modify your main program as shown below:
using System;
namespace Enums
{
class Program
    {
static void Main(string[] args)
        {
            Console.WriteLine(Color.Yellow);
            Console.ReadLine();
        }
    }

enum Color
{
Yellow,
Blue,
Brown,
Green
}
}

Run the program.
 
OutputYellow
 
Now just typecast Color.Yellow to int, what do we get?
using System;
namespace Enums
{
class Program
    {
static void Main(string[] args)
        {
            Console.WriteLine((int)Color.Yellow);
            Console.ReadLine();
        }
    }

enum Color
{
Yellow,
Blue,
Brown,
Green
}
}

 
Output0
 
We see that enum is called as static variables, so an enum can be considered here as static objects. Thereforeother enums in the above example can be declared in the same way as Yellow, like Blue can be declared asColor.Blue. The output in the above two examples we see is when we typecast and Yellow without typecasting, hence we see here that its behaviour is very similar to an array where Yellow has a value 0, similarly Blue has a value 1Brown2Green3.
Therefore, when we do Color.Yellow, it’s like displaying a number 0, so from this can we infer that an enumrepresents a constant number, therefore an enum type is a distinct type having named constants.
Point to remember: An enum represents for a constant number, and an enum type is known as a distinct type having named constants.

Underlying Data type

Program.cs

using System;
namespace Enums
{
class Program
    {
static void Main(string[] args)
        {
            Console.WriteLine((byte)Color.Yellow);
            Console.WriteLine((byte)Color.Blue);
            Console.ReadLine();
        }
    }

enum Color:byte
{
Yellow,
Blue,
Brown,
Green
}
}

Output

0
1
 
Note: Each and every code snippet in this article is tried and tested.
The only change we did here is that we specified the type to the underlying enum that we declared. The defaultdatatype for the enum is int, here we have specified the data type as byte and we get the result.
There are more data types that can be specified
for enum like longulongshortushortintuint,byte andsbyte.
Point to remember: We can’t declare char as an underlying data type for enum objects because char stores Unicode characters, but enum objects data type can only be number.

Inheritance in Enum

Program.cs

using System;
namespace Enums
{
class Program
    {
static void Main(string[] args)
        {
            Console.WriteLine((byte)Color.Yellow);
            Console.WriteLine((byte)Color.Blue);
            Console.ReadLine();
        }
    }

enum Color:byte
{
Yellow,
Blue,
Brown,
Green

}

enum Shades:Color
{

}
}

Output

Compile time error: Type bytesbyteshortushortintuintlong, or ulong expected.
We clearly see here enums can’t be derived from any other type except that of mentioned in the error.
Point to rememberenum can’t be derived from any other type except that of type bytesbyteshortushort,intuintlong, or ulong.
Let’s derive a class from enum, call it class Derived, so our code.

Program.cs

class Program
    {
static void Main(string[] args)
        {
            Console.WriteLine((byte)Color.Yellow);
            Console.WriteLine((byte)Color.Blue);
            Console.ReadLine();
        }
    }

Enum

enum Color:byte
    {
        Yellow,
        Blue,
        Brown,
        Green
    }

Derived.cs

class Derived:Color
    {

}

Compile the code.

Output

Compile time error: ‘Enums.Derived’: cannot derive from sealed type ‘Enums.Color’
Point to remember: By default, enum is a sealed class and therefore sticks to all the rules that a sealed class follows, so no class can derive from enum, i.e., a sealed type.
Can System.Enum be a base class toenum?

Program.cs

using System;

namespace Enums
{
internal enum Color: System.Enum
{
Yellow,
Blue
}

internal class Program
{
private static void Main(string[] args)
{
}
}
}

Output

Compile time error: Type bytesbyteshortushortintuintlong, or ulong expected.
Point to remember: The enum type is implicitly derived from System.Enum and so we cannot explicitly derive it from System.Enum.
To add more,enum is also derived from three interfaces IComparableIFormattable and IConvertible.

A. IComparable

Let’s check,

Program.cs

using System;

namespace Enums
{
internal enum Color
{
Yellow,
Blue,
Green
}

internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(Color.Yellow.CompareTo(Color.Blue));
Console.WriteLine(Color.Blue.CompareTo(Color.Green));
Console.WriteLine(Color.Blue.CompareTo(Color.Yellow));
Console.WriteLine(Color.Green.CompareTo(Color.Green));
Console.ReadLine();
}
}
}

Output

-1
-1
 1
 0
Sometimes, we may get into situations where we have large number of enums defined and we want to compare the values of enum to each other to check if they are smaller, larger or equal value to one another.
Since all enums implicitly derive from Enum class that implements the interface IComparable, they all have a methodCompareTo(), that we just used in the above example. The method being nonstatic has to be used through a member. Yellow has value 0, Blue as 1 and Green as 2. In the first statement, when Color.Yellow compared toColor.Blue, value of Yellow is smaller than Blue hence -1 returned, same applied for the second statement when Color.Blue compared to Color.GreenGreen has larger value, i.e., 2 than that of Color.Blue having value 1 only. In the third statement, i.e., vice versa of first statement, we get the result of camparisonas 1,becauseBlue is larger than Yellow. In the last statement where Color.Green compares to itself, we undoubtedly get the value 0.
So value -1 means the value is smaller, 1 means value is larger and 0 means equal values for both the enummembers.
Another comparison example is shown below:

Program.cs

using System;

namespace Enums
{
enum Color
{
Yellow,
Blue,
Green
}

internal class Program
{
private static void Main(string[] args)
{
int myColor = 2;
if(myColor== Color.Green)
{
Console.WriteLine(my color”);
}
Console.ReadLine();
}
}
}

Output

Compile time error : Operator '==' cannot be applied to operands of type 'int' and 'Enums.Color'
In the above example, we tried to compare an int type to Enum type and resulted in a compile time error. Sinceenum acts as an individual data type so it cannot be directly compared to an int, however, we can typecast the enumtype to int to perform comparison, like in the below example:

Program.cs

using System;

namespace Enums
{
enum Color
{
Yellow,
Blue,
Green
}

internal class Program
{
private static void Main(string[] args)
{
int myColor = 2;
if(myColor== (int)Color.Green)
{
Console.WriteLine(my color”);
}
Console.ReadLine();
}
}
}

 
Output: my color

B. IFormattable

Program.cs

using System;

namespace Enums
{
internal enum Color
{
Yellow,
Blue,
Green
}

internal class Program
{
private static void Main(string[] args)
{
System.Console.WriteLine(Color.Format(typeof(Color), Color.Green, X”));
System.Console.WriteLine(Color.Format(typeof(Color), Color.Green, d”));
Console.ReadLine();
}
}
}

Output

00000002
2
Format is the method derived from IFormatter interface. It’s a static method so can be used directly with theenum class defined as Color. It’sfirst parameter is the type of the enum class, second is the member that has to be formatted and third is the format, i.e., hexadecimal or decimal, like we used in the above example, and we got a positive result output too.

C. IConvertible

using System;

namespace Enums
{
enum Color
{
Yellow,
Blue,
Green
}

internal class Program
{
private static void Main(string[] args)
{
string[] names;
names = Color.GetNames(typeof (Color));
foreach (var name in names)
{
Console.WriteLine(name);
}
Console.ReadLine();
}
}
}

Output

Yellow
Blue
Green
 
Note: Each and every code snippet in this article is tried and tested.
GetNames is a static method that accepts Type, i.e., instance of type as a parameter and in return gives an array of strings. Like in the above example, we had array of 3 members in our enum, therefore their names are displayed one by one.
Another example is as follows:

Program.cs

using System;

namespace Enums
{
enum Color
{
Yellow,
Blue,
Green
}

internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(Color.Blue.ToString());
Console.WriteLine(Color.Green.ToString());
Console.ReadLine();
}
}
}

Output

Blue
Green
As we see in the above example, we converted an enum type to staring type and got an output too, so, numerous predefined conversion methods can be used to convert enum from one data type to another.
 
Point to remember: Numerous predefined conversion methods can be used to convert enum from one data type to another.
Duplicity, default values and initialization:

Program.cs

using System;
namespace Enums
{
class Program
    {
static void Main(string[] args)
        {
            Console.WriteLine((byte)Color.Yellow);
            Console.WriteLine((byte)Color.Blue);
            Console.ReadLine();
        }
    }

enum Color
{
Yellow,
Blue,
Brown,
Green,
Blue
}
}

Output

Compile time error: The type 'Enums.Color' already contains a definition for 'Blue'
In the above example, we just repeated the enum member Blue of Color, and we got a compile time error, hence we now know that an enum cannot contain two members having the same name. By default, if the first value is not specified, the first member takes the value and increments it by one to succeeding members.
Let’s take one more example.

Program.cs

using System;
namespace Enums
{
class Program
    {
static void Main(string[] args)
        {
            Console.WriteLine((int)Color.Yellow);
            Console.WriteLine((int)Color.Blue);
            Console.WriteLine((int)Color.Brown);
            Console.WriteLine((int)Color.Green);

Console.ReadLine();
}
}

enum Color
{
Yellow =2,
Blue,
Brown=9,
Green,

}
}

Output

2
3
9
10
Surprised! We can always specify the default constant value to any enum member, here we see, we specified value 2to yellow, so as per law of enum, the value of blue will be incremented by one and gets the value 3. We again specified as a default value toBrown, and so its successor Green gets incremented by one and gets that value 10.
Moving on to another example.

Program.cs

using System;
namespace Enums
{
class Program
    {
static void Main(string[] args)
        {

}
}

enum Color:byte
{
Yellow =300 ,
Blue,
Brown=9,
Green,
}
}

Output

Compile time error: Constant value '300' cannot be converted to a 'byte'
We just derived ourenum from byte, we know we can do that? We then changed the value of yellow from 2 to300, and we resulted in a compile time error. Since here our underlying data type was byte, so it is as simple as that, that we cannot specify the value to enum members which exceeds the range of underlying data types. The value 300is beyond the range of byte. It is similar to assigning the beyond range value to a byte data type variable.
Another example:

Program.cs

using System;
namespace Enums
{
class Program
    {
static void Main(string[] args)
        {
            Console.WriteLine((int)Color.Yellow);
            Console.WriteLine((int)Color.Blue);
            Console.WriteLine((int)Color.Brown);
            Console.WriteLine((int)Color.Green);

Console.ReadLine();
}
}

enum Color
{
Yellow = 2,
Blue,
Brown = 9,
Green = Yellow
}
}

Output

2
3
9
2
Here we initialized Green to Yellow, and we did not get any error, so we see, more than one enum members can be initialized a same constant value.
Point to remember: More than one enum members can be initialized a same constant value.

Program.cs

using System;
namespace Enums
{
class Program
    {
static void Main(string[] args)
        {
            Color.Yellow = 3;
        }
    }

enum Color
{
Yellow = 2,
Blue,
Brown = 9,
Green = Yellow
}
}

Output

Compile time error: The left-hand side of an assignment must be a variable, property or indexer
In the above example, we tried to initialize the enum member out of the scope of defined enum, i.e., in another class, and got a compile time error. We must not forget that an enum acts as a constant, which cannot change its value.
Point to remember: An enum acts as a constant, so its value cannot be changed once initialized.

Readability

Program.cs

using System;

namespace Enums
{
internal enum Color
{
Yellow,
Blue,
Brown,
Green
}

internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(CheckColor(Color.Yellow));
Console.WriteLine(CheckColor(Color.Brown));
Console.WriteLine(CheckColor(Color.Green));
Console.ReadLine();
}

public static string CheckColor(Color color)
{
switch (color)
{
case Color.Yellow:
return Yellow”;
case Color.Blue:
return Blue”;
case Color.Brown:
return Brown”;
case Color.Green:
return Green”;
default:
return no color”;
}
}
}
}

Output

Yellow
Brown
Green
Here, in the above example, we have declared an enum Color containing various color members.There is a class named program that contains a static method named CheckColor, that has a switch statement checkingcolor on the basis of passed parameter to the method, i.e., Enum Color. In Main method, we try to access thatCheckColor method, passing various parameters. We see that the switch statement in CheckColor method can take any of the datatype passed and in return case statements use name of that type and not the plain intnumber to compare the result. We see that this made our program more readable. So enum plays an important role in making the program more readable and structured, easy to grasp.

Circular Dependency

Program.cs

using System;

namespace Enums
{
internal enum Color
{
Yellow=Blue,
Blue
}

internal class Program
{
private static void Main(string[] args)
{
}
}
}

Output

Compile time error: The evaluation of the constant value for 'Enums.Color.Yellow' involves a circular definition
Like constants, we also cannot have circular dependency in enums. We assigned valueBlue to Yellow, and Blue in turn is incremented by one as a next enum member, this results in a circular dependency of Blue to yellow, and resulted in error, C# is smart enough to catch these kind of tricks.

Diving Deep

Let’s take some complex scenarios:

Lab1

Program.cs

using System;

namespace Enums
{
enum Color
{

}

internal class Program
{
private static void Main(string[] args)
{
Color color = (Color) -1;
Console.ReadLine();
}
}
}

 
Note: Each and every code snippet in this article is tried and tested.

Output

Compile time error: 
To cast a negative value, you must enclose the value in parentheses
'Enums.Color' is a 'type' but is used like a 'variable'
In the above example, we are casting a negative value to enum, but the compiler says that while casting a negative value, we must keep that in parenthesis. It’s not strange, as C# knows that “-” is also a unary operator, that while using above code may create a confusion for compiler that we are using subtraction or typecasting a negative value. So always use parenthesis while typecasting negative values.

Lab2

Program.cs

using System;

namespace Enums
{
enum Color
{
value__
}

internal class Program
{
private static void Main(string[] args)
{

}
}
}

Output

Compile time error: The enumerator name 'value__' is reserved and cannot be used
We clearly see here that we have value__ as reserved member for the enumerator. C# compiler like this keyword has large number of reserved inbuilt keywords.
Image credit: www.vector.rs
It may keep this reserved keyword to keep track of the enum members internally but not sure.

Summary

Let’s recall all the points that we have to remember.
  1. An enum represents for a constant number, and an enum type is known as a distinct type having named constants.
  2. We can’t declare char as an underlying data type for enum objects because char stores Unicode characters, but enum objects data type can only be number.
  3. An enum can’t be derived from any other type except that of type bytesbyteshortushortintuint,long, or ulong.
  4. By default, enum is a sealed class and therefore sticks to all the rules that a sealed class follows, so no class can derive from enum, i.e., a sealed type.
  5. The enum type is implicitly derived from System.Enum and so we cannot explicitly derive it fromSystem.Enum.
  6. enum is also derived from three interfaces IComparableIFormattable and IConvertible.
  7. Numerous predefined conversion methods can be used to convert enum from one data type to another.
  8. More than one enum members can be initialized a same constant value.
  9. An enum acts as a constant, so its value cannot be changed once initialized.
  10. The enumerator name ‘value__‘ is reserved and cannot be used.

Conclusion

With this article, we completed almost all the scenarios related to enum. We did a lot of hands-on lab to clear our concepts. I hope my readers now know by heart about these basic concepts and will never forget them.
These may also help you in cracking C# interviews.
Keep coding and enjoy reading.
Also, do not forget to rate/comment/like my article if it helped you by any means, this helps me to get motivated and encourages me to write more and more.

Read more:

Other Series

My other series of articles:

For more informative articles visit my Blog.

For more technical articles you can reach out to CodeTeddy.

Read More

For more technical articles, you can reach out to A Practical Approach.

Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protected/Internal/Sealed/Constants/Static and Readonly Fields)


Introduction

Thanks to my readers for their tremendous support which has motivated me to continue this OOP series further.
We have already covered almost all the aspects of Inheritance and Polymorphism in C#. My article will highlight almost all the aspects/scenarios of access modifiers in C#. We’ll learn by doing hands on lab and not only by theory. We’ll cover my favourite topic Constants in a very different manner by categorizing the sections in the form of “Labs”. My effort in this article will be to cover each and every concept of the related topic, so that at the end of the article, we can confidently say that we know “All about access modifiers in C#”. Just dive into OOP.

Pre-requisites

I expect that readers of this article should have very basic knowledge of C#. The reader should only know the definition of access modifiers. Last but not the least, as always, I wish that my readers should enjoy reading this article.

Roadmap

Let’s recall our road map:

Access Modifiers

Let us take the definition from Wikipedia this time:

“Access modifiers (or access specifiers) are keywords in object-oriented languages that set the accessibility of classes, methods, and other members. Access modifiers are a specific part of programming language syntax used to facilitate the encapsulation of components.”

Like the definition says, we can control the accessibility of our class methods and members through access modifiers, let us understand this in detail by taking every access modifier one by one.

Public, Private, Protected at Class Level

Whenever we create a class, we always want to have the scope to decide who can access certain members of the class. In other words, we would sometimes need to restrict access to the class members. The one thumb rule is that members of a class can freely access each other. A method in one class can always access another method of the same class without any restrictions. When we talk about the default behavior, the same class is allowed complete access but no else is provided access to the members of the class. The default access modifier is private for class members.
Point to remember: The default access modifier is private for class members.
Let’s do some hands on lab. Just open your Visual Studio and add a console application in C# namedAccessModifiers. You’ll get a Program.cs class file by default. In the same file, add a new class named Modifiersand add the following code to it:
using System;

namespace AccessModifiers
{
class Modifiers
{
static void AAA()
{
Console.WriteLine(Modifiers AAA”);
}

public static void BBB()
{
Console.WriteLine(Modifiers BBB”);
AAA();
}
}

class Program
{
static void Main(string[] args)
{
Modifiers.BBB();
}
}
}

So, your Program.cs file becomes like shown in the above code snippet. We added a class Modifiers and two staticmethods AAA and BBB. Method BBB is marked as public. We call the method BBB from Main method.The method is called directly by the class name because it is marked static.
When we run the application, we get the output as follows:

Output

Modifiers BBB
Modifiers AAA
 
BBB is marked public and so anyone is allowed to call and run it. Method AAA is not marked with any access modifier which automatically makes it private, that is the default. The private modifier has no effect on members of the same class and so method BBB is allowed to call method AAA. Now this concept is called member access.
Modify the Program class and try to access AAA as:
class Program
    {
static void Main(string[] args)
        {
            Modifiers.AAA();
            Console.ReadKey();
        }
    }

Output

'AccessModifiers.Modifiers.AAA()' is inaccessible due to its protection level
So , since methodAAA is private, therefore no one else can have access to it except Modifiers class.
Note: Each and every code snippet written in this article is tried and tested.
 
Modifiers
Now mark the AAA method as protected, our class looks like:
class Modifiers
    {
protected static void AAA()
        {
            Console.WriteLine("Modifiers AAA");
        }

public static void BBB()
{
Console.WriteLine(Modifiers BBB”);
AAA();
}
}

Program

class Program
    {
static void Main(string[] args)
        {
            Modifiers.AAA();
            Console.ReadKey();
        }
    }

Output

'AccessModifiers.Modifiers.AAA()' is inaccessible due to its protection level
Again the same output. We cannot access the method AAA even after we introduced a new modifier namedprotected. But BBB can access AAA method because it lies in the same class.

Modifiers in Inheritance

Let’s add one more class and make a relation of base and derived class to our existing class and add one more method to our base class. So our class structure will look something like this:

Modifiers Base Class

class ModifiersBase
    {
static void AAA()
        {
            Console.WriteLine("ModifiersBase AAA");
        }
public static void BBB()
        {
            Console.WriteLine("ModifiersBase BBB");
        }
protected static void CCC()
        {
            Console.WriteLine("ModifiersBase CCC");
        }
    }

Modifiers Derive Class

class ModifiersDerived:ModifiersBase
    {
public static void XXX()
        {
            AAA();
            BBB();
            CCC();
        }
    }

Program Class

class Program
    {
static void Main(string[] args)
        {
            ModifiersDerived.XXX();
            Console.ReadKey();
        }
    }

Output

'AccessModifiers.ModifiersBase.AAA()' is inaccessible due to its protection level
Now in this case, we are dealing with derived class. Whenever we mark a method with the specifier, protected, we are actually telling C# that only derived classes can access that method and no one else can. Therefore in method XXX, we can call CCC because it is marked protected, but it cannot be called from anywhere else including Main function. The method AAA is made private and can be called only from the class ModifiersBase. If we remove AAA from method XXX, the compiler will give no error.
Therefore, now we are aware of three important concepts. Private means only the same class has access to the members, public means everybody has access and protected lies in between where only derived classes have access to the base class method.
All the methods for example reside in a class. The accessibility of that method is decided by the class in which it resides as well as the modifiers on the method. If we are allowed an access to a member, then we say that the member is accessible, else it is inaccessible.

Internal Modifier at Class Level

Let’s take one another scenario. Create a class library with a name “AccessModifiersLibrary” in your Visual Studio. Add a class named ClassA in that class library and mark the class as internal, the code will be as shown below:
AccessModifiersLibrary.ClassA:

namespace AccessModifiersLibrary
{
internal class ClassA
{
}
}

Now compile the class, and leave it. Its DLL will be generated in ~\AccessModifiersLibrary\bin\Debug folder.
Now in your console application, “AccessModifiers” i.e. created earlier. Add the reference ofAccessModifiersLibrary library by adding its compiled DLL as a reference to AccessModifiers.
In Program.cs of AccessModifiers console application, modify the Program class like shown below:

AccessModifiers.Program

using AccessModifiersLibrary;

namespace AccessModifiers
{
class Program
{
static void Main(string[] args)
{
ClassA classA;
}
}
}

And compile the code.

Output

Compile time error: 'AccessModifiersLibrary.ClassA' is inaccessible due to its protection level
We encountered this error because the access specifier internal means that we can only access ClassA fromAccessModifiersLibrary.dll and not from any other file or code. Internal modifier means that access is limited to current program only. So try never to create a component and mark the class internal as no one would be able to use it.
And what if we remove the field internal from ClassA, will the code compile? i.e.,

AccessModifiersLibrary.ClassA

namespace AccessModifiersLibrary
{
class ClassA
    {
    }
}

AccessModifiers.Program

using AccessModifiersLibrary;

namespace AccessModifiers
{
class Program
{
static void Main(string[] args)
{
ClassA classA;
}
}
}

Output

Compile time error: 'AccessModifiersLibrary.ClassA' is inaccessible due to its protection level
We again got the same error. We should not forget that by default if no modifier is specified, the class is internal. So our class ClassA is internal by default even if we do not mark it with any access modifier, so the compiler results remain the same.
Had the class ClassA been marked public, everything would have gone smooth without any error.
Point to remember: A class marked as internal can only be have its access limited to the current assembly only.

Namespaces with Modifiers

Let’s for fun, mark a namespace of AccessModifiers class library as public in Program class:

Program

public namespace AccessModifiers
{
class Program
    {
static void Main(string[] args)
        {

}
}
}

Compile the application.

Output

Compile time error: A namespace declaration cannot have modifiers or attributes
 
Point to remember: Namespaces as we see by default can have no accessibility specifiers at all. They are by defaultpublic and we cannot add any other access modifier including public again too.

Private Class

Let’s do one more experiment and mark the class Program as private, so our code becomes:
namespace AccessModifiers
{
private class Program
    {
static void Main(string[] args)
        {

}
}
}

Compile the code.

Output

Compile time error: Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal
Point to remember: A class can only be public or internal. It cannot be marked as protected or private. The default is internal for the class.
Access modifiers for the members of the class:
Now here is a big statement, that the members of a class can have all the above explained access modifiers, but default modifier is private.
Point to remember: Members of a class can be marked with all the access modifiers, and the default access modifier isprivate.
What if we want to mark a method with two access modifiers?
namespace AccessModifiers
{
public class Program
    {
static void Main(string[] args)
        {
        }

public private void Method1()
{

}
}
}

Compile the code.

Output

Compile time error: More than one protection modifier
Therefore, we can’t mark a member with more than one access modifier often. But there are such scenarios too, we’ll cover them in next sections. Already defined types like int and object have no accessibility restrictions. They can be used anywhere and everywhere.

Internal Class and Public Method

Create a class library with a class named ClassA marked internal and have a public method MethodClassA(), as:
namespace AccessModifiersLibrary
{
internal class ClassA
    {
public void MethodClassA(){}
    }
}
Add the reference of class library to our console application. Now in Program.cs of console application, try to access that method MethodClassA of ClassA.

Program

using AccessModifiersLibrary;

namespace AccessModifiers
{
public class Program
{
public static void Main(string[] args)
{
ClassA classA = new ClassA();
classA.MethodClassA();
}
}
}

Output

Compile time errors:
'AccessModifiersLibrary.ClassA' is inaccessible due to its protection level
The type 'AccessModifiersLibrary.ClassA' has no constructors defined
'AccessModifiersLibrary.ClassA' is inaccessible due to its protection level
'AccessModifiersLibrary.ClassA' does not contain a definition for 'MethodClassA' and
no extension method 'MethodClassA' accepting a first argument of type 'AccessModifiersLibrary.ClassA'
could be found (are you missing a using directive or an assembly reference?)
So many errors. The errors are self explanatory though. Even the method MethodClassA of ClassA is public, it could not be accessed in Program class due to protection level of ClassA, i.e. internal. The type enclosing the method MethodClassA is internal, so no matter if the method is marked public, we cannot access it in any other assembly.

Public Class and Private Method

Let’s make the class ClassA as public and method as private:
AccessModifiersLibrary.ClassA:

namespace AccessModifiersLibrary
{
public class ClassA
{
private void MethodClassA(){}
}
}

Program

using AccessModifiersLibrary;

namespace AccessModifiers
{
public class Program
{
public static void Main(string[] args)
{
ClassA classA = new ClassA();
classA.MethodClassA();
}
}
}

Output on compilation

'AccessModifiersLibrary.ClassA' does not contain a definition
for 'MethodClassA' and no extension method 'MethodClassA' accepting a first argument
of type 'AccessModifiersLibrary.ClassA' could be found (are you missing a using directive or an assembly reference?)
Now we marked our class Public, still can’t access the private method. So for accessing a member of the class, the access modifier of class as well as method is very important.
 
Note: Each and every code snippet written in this article is tried and tested.

Public Class and Internal Method

Make ClassA as public and MethodClassA as internal:
AccessModifiersLibrary.ClassA:

namespace AccessModifiersLibrary
{
public class ClassA
{
Internal void MethodClassA(){}
}
}

Program

using AccessModifiersLibrary;

namespace AccessModifiers
{
public class Program
{
public static void Main(string[] args)
{
ClassA classA = new ClassA();
classA.MethodClassA();
}
}
}

Output on compilation

'AccessModifiersLibrary.ClassA' does not contain a definition for 'MethodClassA' and no extension
method 'MethodClassA' accepting a first argument of type 'AccessModifiersLibrary.ClassA' could be
found (are you missing a using directive or an assembly reference?)
So an internal marked member means that no one from outside that DLL can access the member.

Protected Internal

In the class library, make three classes ClassAClassB and ClassC, and place the code somewhat like this:
namespace AccessModifiersLibrary
{
public class ClassA
    {
protected internal void MethodClassA()
        {

}
}

public class ClassB:ClassA
{
protected internal void MethodClassB()
{
MethodClassA();
}
}

public class ClassC
{
public void MethodClassC()
{
ClassA classA=new ClassA();
classA.MethodClassA();
}
}
}

And in Program class in our console application, call the MethodClassC of ClassC.

Program

using AccessModifiersLibrary;

namespace AccessModifiers
{
public class Program
{
public static void Main(string[] args)
{
ClassC classC=new ClassC();
classC.MethodClassC();
}
}
}

Compiler output

The code successfully compiles with no error.
 
Protected internal modifier indicates two things, that either the derived class or the class in the same file can have access to that method, therefore in the above mentioned scenario, the derived class ClassB and the class in the same file, i.e., ClassC can access that method of ClassA marked as protected internal.
 
Point to rememberProtected internal means that the derived class and the class within the same source code file can have access.

Protected Member

In our Program.cs in console application, place the following code:
namespace AccessModifiers
{
class AAA
    {
protected int a;
void MethodAAA(AAA aaa,BBB bbb)
        {
            aaa.a = 100;
            bbb.a = 200;
        }
    }
class BBB:AAA
     {
void MethodBBB(AAA aaa, BBB bbb)
         {
             aaa.a = 100;
             bbb.a = 200;
         }
     }
public class Program
    {
public static void Main(string[] args)
        {
        }
    }
}

Compiler Output

Cannot access protected member 'AccessModifiers.AAA.a' via a qualifier of type 'AccessModifiers.AAA';
the qualifier must be of type 'AccessModifiers.BBB' (or derived from it)
Class AAA is containing a protected member, i.e., a. But to the same class, no modifiers make sense. However as isprotected, in the derived class method MethodBBB, we cannot access it through AAA as aaa.a gives us an error. However bbb which looks like BBB does not give an error. To check this out, comment out the line aaa.a=100 inMethodBBB (). This means that we cannot access the protected members from an object of the base class, but from the objects of derived class only. This is in spite of the fact that is a member of AAA i.e. the base class. Even so, we still cannot access it. Also we cannot access from the method Main.

Accessibility Priority in Inheritance

Program

namespace AccessModifiers
{
class AAA
    {

}
public class BBB:AAA
{

}
public class Program
{
public static void Main(string[] args)
{
}
}
}

Compiler Output

Compile time error: Inconsistent accessibility: base class 'AccessModifiers.AAA' is less accessible than class 'AccessModifiers.BBB'
The error again gives us one more point to remember.
 
Point to remember: In between public and internalpublic always allows greater access to its members.
The class AAA is by default marked internal and BBB that derives from AAA is made public explicitly. We got an error as the derived class BBB has to have an access modifier which allows greater access than the base class access modifier. Here internal seems to be more restrictive than public.
But if we reverse the modifiers to both the classes i.e. ClassA marked as public and ClassB internal or default, we get rid of the error.
 
Point to remember: The base class always allows more accessibility than the derived class.
Another scenario:

Program

namespace AccessModifiers
{
class AAA
    {

}
public class BBB
{
public AAA MethodB()
{
AAA aaa= new AAA();
return aaa;
}
}
public class Program
{
public static void Main(string[] args)
{
}
}
}

Compiler output

Inconsistent accessibility: return type 'AccessModifiers.AAA' is less accessible than method 'AccessModifiers.BBB.MethodB()'
Here the accessibility of AAA is internal which is more restrictive than public. The accessibility of method MethodBis public which is more than that of the typeAAA. Now the error occurred because return values of a method must have greater accessibility than that of the method itself, which is not true in this case.
 
Point to remember: The return values of a method must have greater accessibility than that of the method itself.

Program

namespace AccessModifiers
{
class AAA
    {

}
public class BBB
{
public AAA aaa;
}
public class Program
{
public static void Main(string[] args)
{
}
}
}

Compiler Output

Inconsistent accessibility: field type 'AccessModifiers.AAA' is less accessible than field 'AccessModifiers.BBB.aaa'
Now rules are the same for everyone. The class AAA or data type aaa is internalaaa field is public which makes it more accessible than AAA which is internal. So we got the error.
Change the code to:
namespace AccessModifiers
{
class AAA
    {

}
public class BBB
{
AAA a;
}
public class Program
{
public static void Main(string[] args)
{
}
}
}

The output compilation results in no error.
We learnt a lot about these access modifiers like publicprivateprotectedinternalprotected internal. We also learnt about their priority of access and usage, let’s summarize their details in a tabular format for revision. Later, we’ll move to other types as well.
Tables taken from MSDN:
Declared accessibility Meaning
public Access is not restricted.
protected Access is limited to the containing class or types derived from the containing class.
internal Access is limited to the current assembly.
protected internal Access is limited to the current assembly or types derived from the containing class.
private Access is limited to the containing type.
“Only one access modifier is allowed for a member or type, except when you use the protected internalcombination.
Access modifiers are not allowed on namespaces. Namespaces have no access restrictions.
Depending on the context in which a member declaration occurs, only certain declared accessibilities are permitted. If no access modifier is specified in a member declaration, a default accessibility is used.
Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these types is internal.
Nested types, which are members of other types, can have declared accessibilities as indicated in the following table.”
Members of Default member accessibility Allowed declared accessibility of the member
enum Public None
class Private public
protected
internal
private
protected internal
interface Public None
struct Private public
internal
private

Sealed Classes

Sealed” is a special class of access modifier in C#. If a class is marked as sealed, no other class can derive from thatsealed class. In other words, a class marked as sealed can’t act as a base class to any other class.

Program

namespace AccessModifiers
{
sealed class AAA
    {

}
class BBB:AAA
{

}
public class Program
{
public static void Main(string[] args)
{
}
}
}

Compiler Output

'AccessModifiers.BBB': cannot derive from sealed type 'AccessModifiers.AAA'
Hence proved.
 
Point to remember: A class marked sealed can’t act as a base class to any other class.
Access the members of sealed class.

Program

using System;

namespace AccessModifiers
{
sealed class AAA
{
public int x = 100;
public void MethodA()
{
Console.WriteLine(Method A in sealed class”);
}
}
public class Program
{
public static void Main(string[] args)
{
AAA aaa=new AAA();
Console.WriteLine(aaa.x);
aaa.MethodA();
Console.ReadKey();
}
}
}

Compiler Output

100
Method A in sealed class
So, as we discussed, the only difference between a sealed and a non sealed class is that the sealed class cannot be derived from. A sealed class can contain variables, methods, properties like a normal class do.
 
Point to remember: Since we cannot derive from sealed classes, the code from the sealed classes cannot be overridden.
 
Note: Each and every code snippet written in this article is tried and tested.

Constants

Lab1

Our Program class in the console application.

Program

public class Program
    {
private const int x = 100;
public static void Main(string[] args)
        {
            Console.WriteLine(x);
            Console.ReadKey();
        }
    }

Output

100
We see, a constant marked variable or a const variable behaves like a member variable in C#. We can provide it an initial value and can use it anywhere we want.
 
Point to remember: We need to initialize the const variable at the time we create it. We are not allowed to initialize it later in our code or program.

Lab2

using System;

namespace AccessModifiers
{
public class Program
{
private const int x = y + 100;
private const int y = z – 10;
private const int z = 300;

public static void Main(string[] args)
{
System.Console.WriteLine({0} {1} {2}”,x,y,z);
Console.ReadKey();
}
}
}

Can you guess the output? What? Is it a compiler error?

Output

390 290 300
Shocked? A constant field can no doubt depend upon another constant. C# is very smart to realize that to calculate the value of variable