Sunday, October 30, 2016

Common Csharp dotnet Format specifiers or Format Strings for display

Name Format String Example Comments
Currency Format C or c or C2 - precision Console.WriteLine(amount.ToString("C")) output depends on your current UI culture
Percent Format P or p or P2 - precision) Console.WriteLine(number.ToString("P")) output depends on your current UI culture
Padding with leading zero Format 0 var input = "123"; Console.WriteLine(input.ToString("0000")); //result will be 0123 Replaces the zero placeholder with the corresponding digit if one is present; otherwise, zero appears in the result string.
Long date Format with no time and zone info just verbose date D var date = DateTime.Now; Console.WriteLine(date.ToString("D")); result will be Sunday,October 30,2015 (output depends on your current UI culture)
Short date Format with no time and zone info just date d var date = DateTime.Now; Console.WriteLine(date.ToString("d")); result will be 10/30/2015 (output depends on your current UI culture)
Full date and time Format with no zone info f or g var date = DateTime.Now; Console.WriteLine(date.ToString("f")); result will be Sunday,October 30,2015 12:23 PM (output depends on your current UI culture)
Just time Format t or T var date = DateTime.Now; Console.WriteLine(date.ToString("t")); result will be 1:23 PM or 1:23:45 PM
Year month Format Y or y var date = DateTime.Now; Console.WriteLine(date.ToString("y")); October, 2015
Month day Format M or m var date = DateTime.Now; Console.WriteLine(date.ToString("M")); October 30 (output depends on UI culture)
UTC time Format O or o var date = DateTime.Now; Console.WriteLine(date.ToString("O")); 2015-10-30T13:45:30.0000000-07:00
Custom date and time Format MMMM dd, yyyy var date = DateTime.Now; Console.WriteLine(date.ToString("MMMM dd, yyyy")); October 30, 2015
Custom date and time Format MM/dd/yy H:mm:ss var date = DateTime.Now;Console.WriteLine(date.ToString("MM/dd/yy H:mm:ss")); 10/30/15 14:14:11
Custom Format d or dd - day of the month
ddd or dddd - abbreviated or full day of the week
M or MM - month of year
MMM or MMMM - abbreviated month or full name of the month
y or yy - two digit year
YYYY - four digit year
var date = DateTime.Now; Console.WriteLine(date.ToString("d MMMM YYYY")); 30 October 2015
Enumeration Format strings G or g Console.WriteLine(LogLevel.Verbose.ToString("G"))); Displays enum entry as a string value. Here result will be Verbose
Enumeration Format strings G or g or F or f Console.WriteLine(LogLevel.Verbose.ToString("G"))); Displays enum entry as a string value. Here result will be Verbose
Enumeration Format strings D or d Console.WriteLine(LogLevel.Verbose.ToString("D"))); Displays enum entry as a integer value. Here result will be 1

Common Csharp dotnet Regex expressions for user input validation

Name Pattern Example
US zip code regex ^\d{5}(?:[-\s]\d{4})?$ 12345 or 12345-2345
Canadian zip code regex ^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$ M4B 1B4
US phone number regex \(?\d{3}\)?-? *\d{3}-? *-?\d{4} (123) 345-234
US Date (MM/dd/YYYY) regex ^(0?[1-9]|[12][0-9]|3[01])[\/](0?[1-9]|1[012])[\/]\d{4}$ 05/31/2016
24 Hour time regex ^(?:0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$ 13:12
12 Hour time regex (AM/PM) ^(([0]?[0-9]|1[0-2]):[0-5][0-9][ ][aApP][mM])|((1[3-9]|2[0-3]):[0-5][0-9])$ 7:00 AM
Url regex ^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$ http://www.test.com or www.test.com
IP address regex ^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$ 127.0.0.1
US social security number rgex ^([0-9]{3}[-]*[0-9]{2}[-]*[0-9]{4})*$ 123-09-2345

Saturday, December 21, 2013

Custom Model Validation Provider for enabling ASP.NET MVC 3 client side validation.


Implementing Custom Model Validation Provider to enable client side MVC 3 validation 

The Validation framework of ASP.NET MVC 3 is designed for extensibility and customization.  It supports validation model using attributes, or by implementing IValidatableObject or unobtrusive javascript based client side validation. It supports both property based or model based validation.

But, again ASP.Net MVC 3 assumes your solution has view models defined in a simple, flat & non hierarchical fashion to make things work. Sometimes, in applications we need to apply or perform validation rather in different ways to comply with existing legacy code, architectural style and culture.

Update: Following solution is applicable to ASP.NET MVC 3 FRAMEWORK ON VS 2010

One last word!! we assume you have in place all necessary jquery /javascript /css files for the MVC client side validation to work

Use case for Implementing Custom ModelValidatorProvider:

In my case, I did not have the pleasure to have view models exclusively defined for the mvc project.

Domain model classes are directly applied to MVC views. I cannot litter domain classes with validation attributes. They are shared components. They derive from some base classes. So, I couldn't really force annotation based validation working directly using this convoluted & hierarchical model classes as shown below:





















Binding JuniorEngineer model to mvc view and enabling property level client side validation declaratively using attributes/annotations seemed difficult for me.

Inject the validation attributes at Run time on the model:

So, we decided to inject validation attributes on model at the run time dynamically. In this case, we have to go for implementing custom validation solution which means we have to create a custom ModelValidatorProvider that allows to inject validation rules on the fly into the model.

Implementing Custom DataAnnotationsModelValidatorProvider:

MVC provides hook to plug in your custom implementation of ModelValidatorProvider. The purpose is to bind validation attributes dynamically to model to enable client side validation.

 public class JuniorEmployeeModelValidator : DataAnnotationsModelValidatorProvider
    {
        protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
        {
            if (metadata.ContainerType != typeof(JuniorEngineer))
                return base.GetValidators(metadata, context, attributes);
            //enable client side validation for name prop for junior engineer model. Name property is inherited from base abstract employee class.
            if (!string.IsNullOrWhiteSpace(metadata.PropertyName) && metadata.PropertyName == "Name")
            {
                //injecting required attribute to name /salary properties.
                attributes = new List<Attribute>()
                {
                    new RequiredAttribute()
                    {
                        ErrorMessage = "Hey babe, we just need a human name."
                    }
                };
            }
            if (!string.IsNullOrWhiteSpace(metadata.PropertyName) && metadata.PropertyName == "Salary")
            {
                attributes = new List<Attribute>()
                {
                    new RequiredAttribute()
                    {
                        ErrorMessage = "No one works for free!! Give him some money."
                    }
                };
            }
            return base.GetValidators(metadata, context, attributes);
        }

      
    }




Register in Global.asax:
Any customization or extension should be registered. Or You get no cookie!!












Saturday, December 14, 2013

Generic TryParse handler for generic .Net Lists



Following C# code sample is a Generic TryParse handler for generic value type 
lists in .Net.  Any character delimited list can be split and use safe TryParse against split list 
to ensure you have valid data.




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GenericTryParsehandler
{
    /// <summary>
    /// Generic TryParsehandler to split and parse generic value type lists.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value"></param>
    /// <param name="result"></param>
    /// <returns></returns>
    public delegate bool TryParseHandler<T>(string value, out T result);
    class Program
    {
        static void Main(string[] args)
        {
            var semiColonDelimitedDateInput = "01/01/2001;2/02/2012;05/31/2013;05/05/1992";
            var commaDelimitedIntInput = "3,4,5,6";
            var intresult = commaDelimitedIntInput.TryParseList<int>(new[] { ',' }, int.TryParse);
            var dateresult = semiColonDelimitedDateInput.TryParseList<DateTime>(new[] { ';' }, DateTime.TryParse);
            
            if (dateresult.Count > 0)
            {
                foreach (var element in dateresult)
                {
                    Console.WriteLine(element);
                }
            }
            else
            {
                Console.WriteLine("Your semiColonDelimitedDateInput cannot be parsed.");
            }
            Console.WriteLine("*******************************************************************");
            if (intresult.Count > 0)
            {
                foreach (var element in intresult)
                {
                    Console.WriteLine(element);
                }
            }
            else
            {
                Console.WriteLine("Your commaDelimitedIntInput cannot be parsed.");
            }
            Console.ReadLine();
        }
    }


    /// <summary>
    /// 
    /// </summary>

    public static class ExtensionMethods
{
        /// <summary>
        /// Generic handler to split and TryParse each item in the list. Handler supports value types.. 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="separator"></param>
        /// <param name="handler"></param>
        /// <returns></returns>
    public static List<T> TryParseList<T>(this string source, char[] separator, TryParseHandler<T> handler)
        where T : struct

    {
        var splitList = new List<T>();
        if (string.IsNullOrEmpty(source)) return splitList;

        var parsedString = source.Split(separator, StringSplitOptions.RemoveEmptyEntries).ToList();

        parsedString.ForEach(x =>
        {
            T result;
            if (handler(x, out result))
            {
                splitList.Add(result);
            }
        });

        return splitList.Count == parsedString.Count ? splitList : new List<T>();
    }
}
}

10 Practical ASP.Net MVC 4 Interview Questions



10  Practical ASP.Net MVC 4 Interview Questions:


1)  Do you think following is valid route definition for ASP.NET MVC solution?






Answer: YES. Variable length routes are valid. This route will match any URL, irrespective of number of placeholders it contains.

_________________________________________________________________________________

2)  Is the following route definition a valid one? If so please explain? 




Answer: This route is constrained using Regular expression. Only numeric values are accepted for the id parameter 

_________________________________________________________________

3)  What is the primary difference between these two Html Helpers for Validation?





Answer: Latter displays only model level validation errors NOT the property level errors. Former displays both model and property level errors

__________________________________________________________

4)   Does this Action Method compiles and redirects the user to another view?

Answer: YES. It is a valid redirect.

_______________________________________________________________________

5) What is the difference between these Html Helpers?



Answer: Latter is destroyed after you read it while former preserves it for next request.

___________________________________________________________

6) What is the difference between two techniques? Which one to prefer?











Answer:  They are one and same. We prefer second approach. It is built in helper method for controller to return 404 code

________________________________________________________________________

7) Can you override MVC convention and define controller name without ending in "Controller" as shown below?







Answer: YES. We can override default MVC convention to define controller name with out ending in "Controller". But, we have to implement our own custom controller factory.

________________________________________________________________________

8) What the result of this view? Will it be a runtime exception or just works fine?








Answer: Session Disabled controller has no impact on ViewBag. View Just renders fine with message: "My Controller has no session".

________________________________________________________________________

9) What is difference between @Url.Action and @Url.RouteUrl?











Answer: Semantically, they are same. 
  •  Url.RouteUrl allows you to specify a particular route by name. 
  • Url.Action will simply pick the first route that matches the criteria.
________________________________________________________________________________

10) List out filters available in MVC world if you can please specify their order of precedence?

Answer: Exception filter can kick in at any time.
  1.  Authorization filter
  2. Action filter
  3. Result filter
  4. Exception filter