Friday, 18 April 2014

How to create Custom Data Annotations using MVC 4 application with client validation

How to create Custom Data Annotations using MVC 4 application with client validation



Step 1 : create mvc application .

Step 2 : Add one entity class "Employee"

public class Employee
    {
        public int RollNumber { get; set; }

        public string StudentName { get; set; }

        public int Age { get; set; }

         public string Sem { get; set; }

        public string EmailAddress { get; set; }

        public int Year { get; set; }

    }

Step 3 : Create .cshtml file of Employee creation.

Step 4 : Add one class file of creation of CustomValidationAttribute

Step 5 : Paste below code in that file.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
using System.Web.Mvc;

namespace MVC_Custom_DataAnnotations
{
    public class CustomRangeAttribute : RangeAttribute, IClientValidatable
    {
        private double _Minimum;
        private double _Maximum;
        private string _message;
        public CustomRangeAttribute(double minimum, double maximum, string message)
            : base(minimum, maximum)
        {
            _Minimum = minimum;
            _Maximum = maximum;
            _message = message;
        }

        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return true;
            }
            double valueObject;
            Double.TryParse(Convert.ToString(value), out  valueObject);
            return _Minimum <= valueObject && valueObject <= _Maximum;
        }

        public override string FormatErrorMessage(string name)
        {
            return _message;
        }


        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();
            rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
            rule.ValidationParameters.Add("range", string.Format("{0}~{1}", Minimum, Maximum));
            rule.ValidationType = "customrange";
            yield return rule;
        }
    }

    public class CustomStringLengthAttribute : StringLengthAttribute, IClientValidatable
    {
        public int MaximumLength;
        public string message;
        public string KeyName;

        public CustomStringLengthAttribute(int maximumLength, string errormessage)
            : base(maximumLength)
        {
            MaximumLength = maximumLength;
            message = errormessage;
        }

        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return true;
            }
            int valueObject = Convert.ToString(value).Length;
            return valueObject <= MaximumLength;
        }
        public override string FormatErrorMessage(string name)
        {
            return message;
        }
       

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();
            rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
            rule.ValidationParameters.Add("maximumlength", MaximumLength);
            rule.ValidationType = "customstringlength";
            yield return rule;
        }
    }

    public class CustomRegularExpressionAttribute : RegularExpressionAttribute, IClientValidatable
    {
        private string Pattern;
        private string message;

        public CustomRegularExpressionAttribute(string pattern, string errorMessage)
            : base(pattern)
        {
            Pattern = pattern;
            message = errorMessage;
        }
        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return true;
            }

            Match match = Regex.Match(Convert.ToString(value), Pattern, RegexOptions.IgnoreCase);

            return match.Success;
        }

        public override string FormatErrorMessage(string name)
        {
            return message;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();
            rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
            rule.ValidationParameters.Add("pattern", Pattern);
            rule.ValidationType = "customregularexpression";
            yield return rule;
        }
    }
}

Step 6 : Now add attribute to Employee class object.

public class Employee
    {
        public int RollNumber { get; set; }

        public string StudentName { get; set; }

        [CustomRangeAttribute(1, 100, "Age between 1 to 100")]
        public int Age { get; set; }

        [CustomStringLengthAttribute(5, "Maximum char allowed in sem field is 5.")]
        [DataMember]
        public string Sem { get; set; }

        [CustomRegularExpressionAttribute("^[A-Za-z0-9_\\+-]+(\\.[A-Za-z0-9_\\+-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*\\.([A-Za-z]{2,4})$", "Please enter valid email address.")]
        public string EmailAddress { get; set; }

        [CustomRangeAttribute(1950, 2014, "Year between 1950 to 2014")]
        public int Year { get; set; }

    }

Step 8 : Add code for checking server side validation.

 [HttpPost]
        public ActionResult Create(Employee  emp)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return View(emp);
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

Step 9 : Run your application and try to produce the error using invalid value.

Step 10 : This way you can create custom validation for server side.

Watch video for visual explanation on this point.

https://www.youtube.com/watch?v=-t1EemDasMc&feature=youtu.be

Thursday, 14 November 2013

Find any string match in store procedure.

Find any string match in store procedure.




SELECT DISTINCT OBJECT_NAME(OBJECT_ID)
     ,object_definition(OBJECT_ID)
FROM sys.Procedures
WHERE object_definition(OBJECT_ID) LIKE '%' + '<<StringTextValue>>' + '%'

Find Store procedure, modified in specific range



Find Store procedure, modified in specific range


SELECT name as Store_Procedure_Name
FROM sys.Procedures
Where modify_Date >=  <<Datevalue>> AND modify_Date <=  <<Datevalue>>

Find column name match in tables


Find column name match in tables


SELECT sys.Tables.NAME AS TableName
     ,sys.columns.NAME AS ColumnName
FROM sys.columns
INNER JOIN sys.Tables ON sys.Tables.object_id = sys.columns.object_id
WHERE sys.columns.NAME LIKE '<<Column Name>>'

Monday, 14 October 2013

How to use resource sing in MVC 4 application.



How to use resource sing in MVC 4 application.



Step 1 : First create your MVC 4 Web application using Visual Studio 2010 | 2012

Step 2 : Right click on project node and Select Add  --> New Item -->  select "Resource File"
              and give file name and click on "Add Button".

Step 3 : Resource file will added to your project open that file and create labels 
             Like   Name = "lblProjectTitle"  value ="Demo"

Step 4 : To access resource file in your project please select access modifier as "Public"















Step 5 : Add resource parameter on your web page this way.

            @ResourceName.lblProjectTitle

Step 6 :  This way you can create your resource file and access in MVC.






 


Friday, 4 October 2013

How to create dynamic progress bar using Storyboard in Windows 8 Apps

How to create dynamic progress bar in Windows 8



Step 1 :  Create your windows 8 application using Visual Studio 2012 .

Step 2 : Add one UserControl page in windows 8 application name  "ProgressBarControl.xaml"

Step 3 : Open that page and paste below code in that file.

<UserControl x:Name="pageResources"
    x:Class="ProgressBarControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <UserControl.Resources >
        <Storyboard x:Key="FirstDot" Storyboard.TargetName="borderFirstDot" RepeatBehavior="Forever">
            <DoubleAnimationUsingKeyFrames
                Storyboard.TargetName="borderFirstDotMyAnimatedTranslateTransform" Storyboard.TargetProperty="X">
                <LinearDoubleKeyFrame Value="-40" KeyTime="0:0:0" />
                <LinearDoubleKeyFrame Value="{Binding FirstDotMiddle}" KeyTime="0:0:2" />
                <LinearDoubleKeyFrame Value="{Binding FirstDotMiddle}" KeyTime="0:0:2.40" />
                <LinearDoubleKeyFrame Value="{Binding MaxWidth}" KeyTime="0:0:5.0" />
                <LinearDoubleKeyFrame Value="{Binding MaxWidth}" KeyTime="0:0:5.50" />
            </DoubleAnimationUsingKeyFrames>
        </Storyboard>
        <Storyboard x:Key="SecondDot" Storyboard.TargetName="borderSecondDot" RepeatBehavior="Forever">
            <DoubleAnimationUsingKeyFrames
                Storyboard.TargetName="borderSecondDotMyAnimatedTranslateTransform" Storyboard.TargetProperty="X">
                <LinearDoubleKeyFrame Value="-60" KeyTime="0:0:0" />
                <LinearDoubleKeyFrame Value="{Binding SecondDotMiddle}" KeyTime="0:0:2.10" />
                <LinearDoubleKeyFrame Value="{Binding SecondDotMiddle}" KeyTime="0:0:2.50" />
                <LinearDoubleKeyFrame Value="{Binding MaxWidth}"  KeyTime="0:0:5.10" />
                <LinearDoubleKeyFrame Value="{Binding MaxWidth}"  KeyTime="0:0:5.50" />
            </DoubleAnimationUsingKeyFrames>
        </Storyboard>
        <Storyboard x:Key="ThirdDot" Storyboard.TargetName="borderThirdDot" RepeatBehavior="Forever">
            <DoubleAnimationUsingKeyFrames
                Storyboard.TargetName="borderThirdDotMyAnimatedTranslateTransform" Storyboard.TargetProperty="X">
                <LinearDoubleKeyFrame Value="-80" KeyTime="0:0:0" />
                <LinearDoubleKeyFrame Value="{Binding ThirdDotMiddle}" KeyTime="0:0:2.20" />
                <LinearDoubleKeyFrame Value="{Binding ThirdDotMiddle}" KeyTime="0:0:2.60" />
                <LinearDoubleKeyFrame Value="{Binding MaxWidth}"  KeyTime="0:0:5.20" />
                <LinearDoubleKeyFrame Value="{Binding MaxWidth}"  KeyTime="0:0:5.50" />
            </DoubleAnimationUsingKeyFrames>
        </Storyboard>
        <Storyboard x:Key="FourthDot" Storyboard.TargetName="borderFourthDot" RepeatBehavior="Forever">
            <DoubleAnimationUsingKeyFrames
                Storyboard.TargetName="borderFourthDotMyAnimatedTranslateTransform" Storyboard.TargetProperty="X">
                <LinearDoubleKeyFrame Value="-100" KeyTime="0:0:0" />
                <LinearDoubleKeyFrame Value="{Binding FourthDotMiddle}" KeyTime="0:0:2.30" />
                <LinearDoubleKeyFrame Value="{Binding FourthDotMiddle}" KeyTime="0:0:2.70" />
                <LinearDoubleKeyFrame Value="{Binding MaxWidth}"  KeyTime="0:0:5.30" />
                <LinearDoubleKeyFrame Value="{Binding MaxWidth}"  KeyTime="0:0:5.50" />
            </DoubleAnimationUsingKeyFrames>
        </Storyboard>
        <Storyboard x:Key="FifthDot" Storyboard.TargetName="borderFifthDot" RepeatBehavior="Forever" >
            <DoubleAnimationUsingKeyFrames
                Storyboard.TargetName="borderFifthDotMyAnimatedTranslateTransform" Storyboard.TargetProperty="X">
                <LinearDoubleKeyFrame Value="-120" KeyTime="0:0:0" />
                <LinearDoubleKeyFrame Value="{Binding FifthDotMiddle}" KeyTime="0:0:2.40" />
                <LinearDoubleKeyFrame Value="{Binding FifthDotMiddle}" KeyTime="0:0:2.80" />
                <LinearDoubleKeyFrame Value="{Binding MaxWidth}" KeyTime="0:0:5.40" />
                <LinearDoubleKeyFrame Value="{Binding MaxWidth}"  KeyTime="0:0:5.50" />

            </DoubleAnimationUsingKeyFrames>
        </Storyboard>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="#88000000"  HorizontalAlignment="Left" VerticalAlignment="Center" >
        <Border x:Name="borderFirstDot"   Padding="10" Height="42"  >
            <Border.RenderTransform>
                <TranslateTransform x:Name="borderFirstDotMyAnimatedTranslateTransform" X="-40" Y="0" />
            </Border.RenderTransform>
            <Button  Style="{StaticResource ButtonProgressBarStyle}" />
        </Border>
        <Border x:Name="borderSecondDot"   Padding="10" Height="42"  >
            <Border.RenderTransform>
                <TranslateTransform x:Name="borderSecondDotMyAnimatedTranslateTransform" X="-60" Y="0" />
            </Border.RenderTransform>
            <Button Style="{StaticResource ButtonProgressBarStyle}" />
        </Border>
        <Border x:Name="borderThirdDot" Padding="10" Height="42"  >
            <Border.RenderTransform>
                <TranslateTransform x:Name="borderThirdDotMyAnimatedTranslateTransform" X="-80" Y="0" />
            </Border.RenderTransform>
            <Button Style="{StaticResource ButtonProgressBarStyle}" />
        </Border>
        <Border x:Name="borderFourthDot"   Padding="10" Height="42"  >
            <Border.RenderTransform>
                <TranslateTransform x:Name="borderFourthDotMyAnimatedTranslateTransform" X="-100" Y="0" />
            </Border.RenderTransform>
            <Button Style="{StaticResource ButtonProgressBarStyle}" />
        </Border>
        <Border x:Name="borderFifthDot"   Padding="10" Height="42"  >
            <Border.RenderTransform>
                <TranslateTransform x:Name="borderFifthDotMyAnimatedTranslateTransform" X="-120" Y="0" />
            </Border.RenderTransform>
            <Button Style="{StaticResource ButtonProgressBarStyle}" />
        </Border>
    </Grid>
</UserControl>


Step 4 : Add this style in your application style file App -> Common Folder -> StandardStyles.xaml file

Note : Please provide any image to your style and paste that image in Assets folder with  "point.png" name

   <Style x:Key="ButtonProgressBarStyle" TargetType="Button">
        <Setter Property="BorderThickness" Value="0"/>
        <Setter Property="Height" Value="20"/>
        <Setter Property="Width" Value="20"/>
        <Setter Property="VerticalAlignment" Value="Top"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid Background="Transparent">
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup>
                                <VisualState x:Name="Normal">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background"  Storyboard.TargetName="ButtonBackground">
                                            <DiscreteObjectKeyFrame KeyTime="0">
                                                <DiscreteObjectKeyFrame.Value>
                                                    <ImageBrush ImageSource="/Assets/point.png" Stretch="Uniform" />
                                                </DiscreteObjectKeyFrame.Value>
                                            </DiscreteObjectKeyFrame>
                                        </ObjectAnimationUsingKeyFrames>

                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="MouseOver">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background"  Storyboard.TargetName="ButtonBackground">
                                            <DiscreteObjectKeyFrame KeyTime="0">
                                                <DiscreteObjectKeyFrame.Value>
                                                    <ImageBrush ImageSource="/Assets/point.png" Stretch="UniformToFill" />
                                                </DiscreteObjectKeyFrame.Value>
                                            </DiscreteObjectKeyFrame>
                                        </ObjectAnimationUsingKeyFrames>

                                    </Storyboard>
                                </VisualState>

                                <VisualState x:Name="Pressed">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background"  Storyboard.TargetName="ButtonBackground">
                                            <DiscreteObjectKeyFrame KeyTime="0">
                                                <DiscreteObjectKeyFrame.Value>
                                                    <ImageBrush ImageSource="/Assets/point.png" Stretch="UniformToFill" />
                                                </DiscreteObjectKeyFrame.Value>
                                            </DiscreteObjectKeyFrame>
                                        </ObjectAnimationUsingKeyFrames>

                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Disabled">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background"  Storyboard.TargetName="ButtonBackground">
                                            <DiscreteObjectKeyFrame KeyTime="0">
                                                <DiscreteObjectKeyFrame.Value>
                                                    <ImageBrush ImageSource="/Assets/point.png" Stretch="UniformToFill" />
                                                </DiscreteObjectKeyFrame.Value>
                                            </DiscreteObjectKeyFrame>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <Border x:Name="ButtonBackground" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="0" Background="Black">
                            <ContentControl x:Name="ContentContainer" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Padding="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                        </Border>

                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>




Step 5 : Add Code behind for  popup file

 public sealed partial class ProgressBarControl : UserControl
    {
        public ProgressBarControl()
        {
            this.InitializeComponent();
            double Height = Window.Current.CoreWindow.Bounds.Height;
            double Width = Window.Current.CoreWindow.Bounds.Width;

            LayoutRoot.Height = Height;
            LayoutRoot.Width = Width;

            this.DataContext = new WindowBound
            {
                MaxWidth = Width,
                FirstDotMiddle = Width / 2,
                SecondDotMiddle = (Width / 2) - 20,
                ThirdDotMiddle = (Width / 2) - 40,
                FourthDotMiddle = (Width / 2) - 60,
                FifthDotMiddle = (Width / 2) - 80
            };

            ((Storyboard)this.Resources["FirstDot"]).Begin();
            ((Storyboard)this.Resources["SecondDot"]).Begin();
            ((Storyboard)this.Resources["ThirdDot"]).Begin();
            ((Storyboard)this.Resources["FourthDot"]).Begin();
            ((Storyboard)this.Resources["FifthDot"]).Begin();
        }
    }

    public class WindowBound
    {
        public double MaxWidth { get; set; }
        public double FirstDotMiddle { get; set; }
        public double SecondDotMiddle { get; set; }
        public double ThirdDotMiddle { get; set; }
        public double FourthDotMiddle { get; set; }
        public double FifthDotMiddle { get; set; }
    }


Step 6 : Add one class which is allow to enable and disable progress bar popop pag.

public static class ProgressBar
    {
        private static readonly Popup Defaultpopup = new Popup();

        /// <summary>
        /// custom method to show the progress bar with formatiing
        /// </summary>
        public static void EnableProgress()
        {
            Defaultpopup.VerticalOffset = 0;
            var control = new ProgressBarControl();
            Defaultpopup.Child = control;
            Defaultpopup.HorizontalAlignment = HorizontalAlignment.Left;
            Defaultpopup.VerticalAlignment = VerticalAlignment.Top;
            Defaultpopup.IsOpen = true;
        }

        /// <summary>
        /// custom method to hide the progress bar with formatiing
        /// </summary>
        public static void DisableProgress()
        {
            Defaultpopup.IsOpen = false;
        }
        /// <summary>
        /// custom method to show the progress bar with formatiing in async methods
        /// </summary>
        /// <returns></returns>
        public async static Task EnableProgressAsync()
        {
            Defaultpopup.VerticalOffset = 0;
            var control = new ProgressBarControl();
            Defaultpopup.Child = control;
            Defaultpopup.HorizontalAlignment = HorizontalAlignment.Left;
            Defaultpopup.VerticalAlignment = VerticalAlignment.Top;
            Defaultpopup.IsOpen = true;

            await Task.Delay(100);
        }
        /// <summary>
        ///  custom method to hide the progress bar with formatiing in async methods
        /// </summary>
        /// <returns></returns>
        public async static Task DisableProgressAsync()
        {           
            Defaultpopup.IsOpen = false;
            await Task.Delay(10);
        }
    }
}

Step 7 : Call the static class function to enable and disable progress bar in your application.

// enable progress bar using static class coding
ProgressBar.EnableProgress()  ;

or

ProgressBar.EnableProgressAsync()   // When you want to enable progress bar in Async method

// your code here

// disable your progress bar using static class coding
ProgressBar.DisbleProgress()  ;

or

ProgressBarDisbleProgressAsync()   // When you want to disable progress bar in Async method


Step 8 : This way you can create and use dynamic progress bar using Storyboard layout .