Saturday, June 27, 2015

Use Google Drive as your free CDN

If you are interested to enhance speed of your application without spending a single rupees then this solution is for you.

You can use Google Drive as your small CDN. We know Google drive a reliable and certain amount of storage is free there. So, If you are interested to host small amount of css/js and image file then Google drive might be one of the nice option.

Here is the steps to implement.

     
     1)      Create one public folder and put your stuffs there. Share the folder in public domain. Just select public option in sharing.  It will be visible to outer world.



      1)      Get Your folder ID
Once you click and open the folder, In url you will find your folder id. I have hosted bootstrap in my folder. 

     
3)      Browse your folder content by using Folder Id and Enjoy.
And you will find your files there. Just click on the file and it will get browse. 


Monday, June 22, 2015

Value and Constant in AngularJS


Resource sharing in Global position is very common requirement in application development. In angular we have $rootScope service to share common object in global position. Beside $routeScope , we can use Values and Constants to share data from global position and can access from services/controller.

The purpose of Value and Constant  is same in AngularJS but the advantage of constant is that, we can inject this in configuration of module.
Let’s see each one of them with example.

Value :

<script>
        var myApp = angular.module('myApp', []);

        myApp.value('name', 'sourav kayal');

        //Inject value to controller      

        myApp.controller('myController', ['name', function (name) {
            console.log(name);
        }]);

    </script>

Here we have created “name” value and injected this to “myController”.  Now , we can access “name” to any controller/service as soon as we inject this.

We can set multiple property/complex model in value. Just like below.

   myApp.value('Address', {
            state: 'West Bengal',
            district : 'Howrah'
        });

As per our discussion, we cannot inject value in configuration of module. Therefore, it will throw error.

<script>
        var myApp = angular.module('myApp', []);

        myApp.value('name', 'sourav kayal');

        myApp.config(function (name) {
        });

    </script>


Constant :

Constant is very similar to value and the syntax is too same. Here we have defined Address constant and same is injected to controller.

<script>
        var myApp = angular.module('myApp', []);

        myApp.constant('Address', {
            state: 'West Bengal',
            district : 'Howrah'
        });

        myApp.controller('myController', ['Address', function (Address) {
            console.log(Address.state);
        }]);

</script>

We can inject constant to config of module. So this is valid.

<script>
        var myApp = angular.module('myApp', []);

        myApp.value('name', 'sourav kayal');

        myApp.constant('Address', {
            state: 'West Bengal',
            district : 'Howrah'
        });

        myApp.config(function (Address) {

        });
</script>

Saturday, June 20, 2015

Count number of Odd divisor between given range

using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Data.SqlClient;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter number of iteration");
            int n = Convert.ToInt32(Console.ReadLine());

            for (int i = 0; i < n  ; i++)
            {
                Console.WriteLine("Enter lower bound");
                int a = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine("Enter upper bound");
                int b = Convert.ToInt32(Console.ReadLine());
                int countResult = 0;

                for (int j = a; j <= b; j++)
                {
                    int countEven = 0;
                    for (int k = 1; k <= j; k++)
                    {
                        if (j % k == 0)
                        {
                            countEven = countEven + 1;
                        }
                    }
                    if (countEven % 2 != 0)
                    {
                        countResult = countResult + 1;
                    }
                }

                Console.WriteLine("Number of Interesting number " +  countResult);
            }
            Console.ReadLine();
        }
    }
}


Thursday, June 18, 2015

Conditional Model validation in MVC

When we use “IsValid”  property of ModelState, it validate all property of model and summarize the error. If there is use case, where we would like to validate model property individually or we will validate if property is present in form collection.

ModelStateDictionary class provides IsValidField() function which takes property name as argument and returns Boolean as validation result.

Here is sample implementation to validate certain property if it is present in FormCollection.

   public class Employee
    {
        [MinLength(3 , ErrorMessage="minimum 3")]
        public string EmpID { get; set; }

        [MaxLength(3 , ErrorMessage = "maximum 3")]
        public string EmpCode { get; set; }
    }

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Save(Employee p , FormCollection Collection)
        {
            string[] keys = Collection.AllKeys;
            Boolean IsValid = true;

            foreach (var item in keys)
            {
                if (ModelState.IsValidField(item) == false)
                {
                    IsValid = false;
                    break;
                }
            }
            if (IsValid == false)
            {
               var errors = ModelState.Values.SelectMany(v => v.Errors);
               return View("Index", p);
            }
            else
            {
                return View("Index");
            }
        }


    }

Here is view

         <form action="../Home/Save" method="post">
             @Html.ValidationSummary()
            <input type="text" name ="EmpID" value="1" />
            <input type="text" name ="EmpCode" value="123411" />
           
            <input type="submit" name="btnSubmit" value="submit" />
        </form>


We are seeing error message based on availability of property.


Custom model validation in MVC

It is another extension point of MVC. In need we can implement ValidationAttribute class in our custom class and implement model validation logic there.

Let’s explain one use case to implement sample example. For example, we have one Employee class like this

public class Employee
    {
        [CombinedLengthChecking(3, "EmpID", "EmpCode")]
        public string EmpID { get; set; }

        public string EmpCode { get; set; }
    }

And the total length of EmpID and EmpCode should 6 and each one must contain length 3. This validation logic we will implement in “CombinedLengthChecking” class.

public class CombinedLengthChecking : ValidationAttribute
    {
        public CombinedLengthChecking(int minLength, params string[] propertyNames)
        {
            this.PropertyNames = propertyNames;
            this.MinLength = minLength;
        }

        public string[] PropertyNames { get; private set; }
        public int MinLength { get; private set; }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var properties = this.PropertyNames.Select(validationContext.ObjectType.GetProperty);
           
            var values = properties.Select(p => p.GetValue(validationContext.ObjectInstance, null)).OfType<string>();

            var totalLength = values.Sum(x => x.Length);
            if (this.MinLength < 3)
            {
                return new ValidationResult("Length sould more than 3");
            }
            if (totalLength > 6)
            {
                return new ValidationResult("Error in Validation");
            }
            return null;
        }
    }


Here is our code in Controller.

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public void Save(Employee p)
        {

            Boolean value = ModelState.IsValid;
        }


    }


Once we run the application, we will see that the execution flow has reached in error block .



<form action="../Home/Save" method="post">
            <input type="text" name ="EmpID" value="123" />
            <input type="text" name ="EmpCode" value="1234" />
            <input type="submit" name="btnSubmit" value="submit" />
        </form>