Tuesday, February 23, 2016

Custom Validation in MVC/Web API using ValidationAttribute

This article is to help us, how to implement custom validation and use it as Data Annotation.
Custom Validation is very useful when we are using the same Property in number of places in our application, rather than to add AddModelError in ModelState, it is a good practice to create this in a separate reusable library so that we can use this in project with very consistent way and re-use in any other project. This should be project independent library and reusable component. 
Following are the steps to create Custom Validator and use it in view model classes.

  1. Create New class DateRangeAttribute inherit from ValidationAttribute
  2. Ensure value is of type DateTime, if not throw ValidationException.
  3. Create constructor to get values dynamically from the View Model.
  4. Override IsValid method of ValidationAttribute class and write logic to validate Date range.
Example
Date Range Attribute Class
 public class DateRangeAttribute: ValidationAttribute
    {
        private int _endAge;
        private int _startAge;

        public DateRangeAttribute(int startAge, int endAge)
        {
            startAge = _startAge;
            endAge = _endAge;
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if(!(value is DateTime))
            {
                throw new ValidationException("DateRange is valid for DateTime property only.");
            }
            else
            {
                var date = (DateTime)value;
                //Better to create DateTime extension method to calculate Age
                if ((Calculate.GetAge(date)< _startAge) || (Calculate.GetAge(date) < _endAge))
                {
                    return new ValidationResult(this.FormatErrorMessage(validationContext.MemberName));
                }
                else
                {
                    return ValidationResult.Success;
                }
            }
        }

    }
Usage
    public class User
    {
        [Required]
        public string FirstName { get; set; }

        [Required]
        public string LastName { get; set; }

        [DateRange(18, 100)]
        public string BirthDate { get; set; }


    }

Monday, February 22, 2016

Logging in .Net

Coming soon

Creating Windows Service in .Net with Topshelf

Creating Windows Service in .Net with Topshelf

This article is to help us to create windows service in .Net with Topshelf and how to install it.
Microsoft Windows services/NT services, allow us to create long-running applications that run in the background repetitively without the need of any user interface or user interaction like Windows Forms Application, WPF Application, Console Application. 
There are different ways to create Windows Service applications using the .NET Framework, but the one way is to use open source project Topshelf.
Topshelf is an open source Windows service framework for the .Net platform that make it easy to create a Windows Services.
Why would I use Topshelf to create Windows service?
It makes easy to create a Windows service as well as test the service, debug the service, and install it into the Windows Service Control Manager (SCM) with simple commands.
By using Topshelf, we don’t need to understand the complex details of service classes, perform installation via InstallUtil, or learn how to attach the debugger to services for troubleshooting issues.
With Topshelf, creating a Windows service is as easy as creating a console application. Once the console application is created, we need to create a single service class with public Start and Stop methods and configure as service using Topshelf’s configuration API.
Now, we have complete Windows service that can be debugged using the debugger (just by pressing F5) and installed using the Topshelf command (install/uninstall).
Here is link of Topshelf open source project documentation https://topshelf.readthedocs.org/en/latest/.
Following are the steps to create windows service in .Net with Topshelf:
  1. Create a New Project with Console Application Template using Visual Studio.


  1. Install Topshelf using NuGet Package Manager.

  1. Create a class that contain our service logic: MyService.cs
namespace WindowsServiceWithTopshelf
{
    public class MyService
    {
        public void Start()
        {
            // write code here that runs when the Windows Service starts up.
        }
        public void Stop()
        {
            // write code here that runs when the Windows Service stops.
        }
    }
}
  1. Create a class to configure our service logic using the Topshelf project: ConfigureService.cs
using Topshelf;

namespace WindowsServiceWithTopshelf
{
    internal static class ConfigureService
    {
        internal static void Configure()
        {
            HostFactory.Run(
                configure =>
                {
                    configure.Service<MyService>(
                        service =>
                        {
                            service.ConstructUsing(s => new MyService());
                            service.WhenStarted(s => s.Start());
                            service.WhenStopped(s => s.Stop());
                        });
                    //Setup Account that window service use to run.
                    configure.RunAsLocalSystem();
                    configure.SetServiceName("MyWindowServiceWithTopshelf");
                    configure.SetDisplayName("MyWindowServiceWithTopshelf");
                    configure.SetDescription("My .Net windows service with Topshelf");
                }
                );
        }
    }
}
  1. Call configure service in Main():
namespace WindowsServiceWithTopshelf
{
    class Program
    {
        static void Main(string[] args)
        {
            ConfigureService.Configure();
        }
    }
}
  1. Build Console application
  2. Install/uninstall Console Application using Topshelf command
    1. Run Command Prompt as an Administrator and navigate to the bin/debug folder of Console Application.
> WindowsServiceWithTopshelf.exe install


    1. To uninstall windows service run this command
 > WindowsServiceWithTopshelf.exe uninstall
  1. How to Debug Window service created using Topshelf?
Just by pressing F5 like console application.


Git Commands and Using Them in Visual Studio

 Git is a widely used version control system that allows developers to manage changes to their code and collaborate with other IDE like Visu...