Monday, September 15, 2014

how to check data type size in sql server 2008


select COLUMN_NAME 
from INFORMATION_SCHEMA.COLUMNS
where DATA_TYPE = 'Data type of column like varchar ,char etc. '
and CHARACTER_MAXIMUM_LENGTH = size of col like 100 ,200 etc
and TABLE_NAME = 'your_table'
 
 
 
 
Ex:
select COLUMN_NAME 
from EmpDB.INFORMATION_SCHEMA.COLUMNS 
where DATA_TYPE = 'varchar'
and CHARACTER_MAXIMUM_LENGTH = 2000
and TABLE_NAME = 'EmpDemo' 

Wednesday, June 25, 2014

LESS CSS With MVC4 Web Optimization



MVC4 has a built in bundler and optimizer for javascript and css, but when you want to use LESS CSS, there’s a few things you need to do to get set up.

Step 1: Add BundleTransformer.Less from Nuget

BundleTransformer.Less is an excellent modular extension to Web.Optimization by taritsyn, allowing us to get our css and js bundling set up quickly.
We’re going to use the BundleTransformer.Less Nuget Package which will add the bundler core and dotless as well. This package is where most of the magic is performed. In the background it’s just setting up dotless to transform the css before bundling.

Step 2: Set up your CSS and JS bundles

A bundle is just a group of css or js references. When starting a new MVC4 project, you’ll have a file called BundleConfig.cs in your App_Start folder. This is where all our css and js references will go.
Take a look at how I’ve set this up:
public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        var cssTransformer = new CssTransformer();
        var jsTransformer = new JsTransformer();
        var nullOrderer = new NullOrderer();

        var css = new Bundle("~/bundles/css")
            .Include("~/Content/site.less");
        css.Transforms.Add(cssTransformer);
        css.Orderer = nullOrderer;

        bundles.Add(css);
        
        var jquery = new Bundle("~/bundles/jquery")
            .Include("~/Scripts/jquery-1.*");
        jquery.Transforms.Add(jsTransformer);
        jquery.Orderer = nullOrderer;

        bundles.Add(jquery);
        
        // If you'd like to test the optimization locally,
        // you can use this line to force it.
        //BundleTable.EnableOptimizations = true;            
    }
}
A couple of things to note here:
  • The cssTransformer and jsTransformer variables tie in the BundleTransformer to the pipeline.
  • The nullOrderer variable forces the optimizer to reference the files in the order they are defined.
  • The string we pass to the Bundle constructor is a virtual path. Don’t use a real path otherwise you’ll run into some funky routing issues.
  • The BundleTable.EnableOptimizations = true; allows you to force the optimizations to render as they would in release mode.

Step 3: Reference the Bundles in your Layout View

Open up your _Layout.cshtml and add the following code to your head tag:
@Styles.Render("~/bundles/css")
This will render any of the stylesheets we included earlier. Note that we’re referencing the virtual path we gave to the StyleBundle class.
You can also add the javascript bundle to the bottom of the page in the same way:
@Scripts.Render("~/bundles/jquery")
That’s It!
Thanks to Andrey Taritsyn for giving me some pointers about the code I’ve posted. You should absolutely check out the rest of the Bundle Transformer Range for other useful modules including SASS, CoffeeScript, YUI, JSMin, WebGrease and much more
 
More details about less please click here

Ref:benjii.me




Monday, May 5, 2014

ASP.NET MVC’s Validation



Model Validation: 
Validations are used for ensure that the expected data is valid and correct so that we can change according to requirement.

Validate in action method: We can validate model in action method. We can check the values of properties of the model object and register any errors we find with the ModelState property.
We can check to see whether the model binder was able to assign a value to a property by using the ModelState.IsValidField method. We do this make sure that the model binder was able to parse the value the user submitted; so that can perform additional checks.

Example:

if (string.IsNullOrEmpty(model. Email))
{
      ModelState.AddModelError("Email", "Please enter your Email");
}

if (ModelState.IsValid)
{
      //send model for further processing
}

ValidationSummary: The validation summary displays the error messages that we registered with the ModelState in our action method. There are a number of overloaded versions of the ValidationSummary method.

Method
Description
Html.ValidationSummary()
Generates a summary for all validation errors.
Html.ValidationSummary(bool)
If the bool parameter is true, then only model-level errors are displayed. If the parameter is
false, then all errors are shown.
Html.ValidationSummary(string)
Displays a message before a summary of all the validation errors.
Html.ValidationSummary(bool,string)
Displays a message before the validation errors. If the bool parameter is true, only model-level errors will be shown.


ValidationMessage: The Html.ValidationMessageFor helper displays validation errors for a single model property.
@Html.ValidationMessageFor(t => t.Email)

Validation in the Model Binder: The default model binder performs validation as part of the binding process. The model binder performs some basic validation for each of the properties in the model object. If value has not been supplied or value that cannot be parsed into the model property type. DefaultModelBinder, provides us with some useful methods that we can override to add validation to a binder. Find detail in below table.

Method Name
Description
Default Implementation
OnModelUpdated
Called when the binder has tried to assign values to all of the properties in the model object. Model level validation.
Applies the validation rules defined by the model metadata and registers any errors with ModelState.
SetProperty
Called when the binder wants to apply a value to a specific property. Property level validation
Required or not valid message will show.

Data Annotations: The MVC Framework supports the use of metadata to express model validation rules. We can easily add validation to our application by including Data Annotations namespace and use attributes to our model classes. Data Annotations allow us to describe the rules we want applied to our model properties, and ASP.NET MVC will take care of enforcing them and displaying appropriate messages to our users. There is number of attribute classes which inherits validation attribute class, use to manage different types of validation.

Some of important build in data annotation attributes are:
  • Required – Indicates that the property is a required field
  • DisplayName – Defines the text we want used on form fields and validation messages
  • StringLength – Defines a maximum length for a string field
  • Range – Gives a maximum and minimum value for a numeric field
  • RegularExpression – Validate input value as per defined regular expression
  • Compare – Two property must have same value.


Custom validation class: We can also create custom validation attribute by deriving from the ValidationAttribute class and implementing our own validation logic. We can override the IsValid method of the base class, this method get called by binder while passing value provided by user as the parameter.

Example:
public override bool IsValid(object value)
        {           
               
                if (String.IsNullOrEmpty(Convert.ToString(value)))
                {
                    return false;
                }

                return true;
        }

 [IsEmailReq(ErrorMessage = "Email is Required")]
public string Email { get; set; }


Model Validation Attribute: We can also create a custom attribute at model level instead of property level. Model validator attribute will use only if property-level attributes does not register a validation error. We must apply a model validation attribute to the model class itself.

Example:
public class IsEmailReqAttribute: ValidationAttribute
    {
        public RegisterValidatorAttribute()
        {
            ErrorMessage = "Please enter valid email";
        }

        public override bool IsValid(object value)
        {
            RegisterModel model = value as  RegisterModel;

            if (model.Email.Contains("test") || model.Email.Contains("test.com"))
            {
                return false;
            }
            return true;
        }
    }

[IsEmailReq]
public class RegisterModel


Client-Side Validation: In web application user expect immediately validation, without having to submit data to the server. This is client site validation and usually we implement JavaScript for this. This allow user to correct data before sending to the server for further processing.
The MVC Framework supports unobtrusive client-side validation. The term unobtrusive means that validation rules are expressed using attributes added to the HTML elements that we generate. These are interpreted by a JavaScript library that is included as part of the MVC Framework, which uses the attribute values to configure the jQuery Validation library, which does the actual validation work. There are few advantages using this approach.

  • We do not have to include client-side validation logic into our views
  • If JavaScript disabled in browser then server side validation will fire in same manner.
  • Mitigate the effect of browser inconsistencies and behaviors.


Enable/Disable Client validation: Developer can enable and disable client side validation by setting in web.config. By default it’s enabled.

<appSettings>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
 </appSettings>

Both of these settings must be true for client-side validation to work. We can also set value programmatically like in global.asax page application start method.

protected void Application_Start()
{
HtmlHelper.ClientValidationEnabled = true;
HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
}

We can enable or disable client-side validation for individual views as well by setting above value in view page.

In addition to the configuration settings, we must references three specific JavaScript libraries.

<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

After all above setting client side validation will start to work based on applied metadata attributes in model properties such as Required, Range, Regular Expression and String Length.
Client side validation works faster and also perform validation on key stroke like key press or focus change.

In MVC Framework validation rules are expressed using HTML attributes. MVC client-side validation is that the same attributes we use to specify validation rules are applied at the client and at the server.  

Example:
Without validation attribute:
public string Email { get; set; }
Output:
<input id="Email" name="Email" value="" type="text">

With validation attribute:
[Required]
public string Email { get; set;
Output:
<input id="Email" name="Email" value="" type="text" data-val-required="The Email is required." data-val="true">

Note: The MVC client-validation features are built on top of the jQuery Validation library; developer can use the Validation library directly and ignore the MVC features if required. The MVC client-validation features hide the JavaScript, and they have the advantage of taking effect for both client- and server-side validation.

Example:

<script type="text/javascript">
$(document).ready(function ()
{
    $('form').validate({
    errorLabelContainer: '#validtionSummary',
    wrapper: 'li',
    rules: {
        Email: {
            required: true,
        }
    },
    messages: {
        Email: "Please enter your Email"
    }
    });
});
</script>


The jQuery Validation library supports some more complex validation rules like email, url, date, number, digits and credit card or we can create new rules.

Creating attributes for client-side validation: To enable client-side validation, we must implement the IClientValidatable in model attribute class. We can create custom validation attributes that work in the same way as the built-in ones and that trigger client- and server-side validation.

The interface defines one method, GetClientValidationRules, which returns an enumeration of
ModelClientValidationRule objects. Each ModelClientValidationRule object describes the client-side validation rule that we want to apply, the error message to display when the rule is broken, and any parameters that the rule needs to operate.

Example:
Example to create a new rule called checkboxmusttrue to ensure that a checkbox is checked.
Developer has to add custom jQuery validation rule to unobtrusive adaptor.

<script type="text/javascript">

    jQuery.validator.unobtrusive.adapters.add("checkboxmusttrue", function (options) {
        if (options.element.tagName.toUpperCase() == "INPUT" &&
options.element.type.toUpperCase() == "CHECKBOX") {
            options.rules["required"] = true;
            if (options.message) {
                options.messages["required"] = options.message;
            }
        }
    });
</script>

public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
    {
        public override bool IsValid(object value)
        {
            return value is bool && (bool)value;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            return new ModelClientValidationRule[] {    new ModelClientValidationRule {
            ValidationType = "checkboxmusttrue",
                    ErrorMessage = this.ErrorMessage
            }};
        }
    }




Source:MSDN and some other blogs.