VS Shortcut

ctrl+U-> Make lower case
shift+ctrl+U->make upper case
ctrl+k+U->Uncomment
 ctrl+k+C->Comment

Javascript Validation using regexp

Name:
Alphabets, numbers and space(' ') no special characters min 3 and max 20 characters.
var ck_name = /^[A-Za-z0-9 ]{3,20}$/;

Email
Standard email address
var ck_email = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i

UserId
Supports alphabets and numbers no special characters except underscore('_') min 3 and max 20 characters.
var ck_username = /^[A-Za-z0-9_]{3,20}$/;

Password
Password supports special characters and here min length 6 max 20 charters.
var ck_password = /^[A-Za-z0-9!@#$%^&*()_]{6,20}$/;

 Script to validate the special characters

<script language="JavaScript 1.2" type="text/JavaScript">
<!--


function validate() {
if (document.form1.folder_id.value == "") {
alert ("Please enter your Event title");
document.form1.folder_id.focus();
return false;
}
var string = document.form1.folder_id.value;
if (!string) {
alert ("Event title missing !");
return false;
}
var iChars = "*|,\":<>[]{}`\';()@&$#%";
for (var i = 0; i < string.length; i++) {
if (iChars.indexOf(string.charAt(i)) != -1){
alert ("'Event title' contains illegal characters!");
document.form1.folder_id.focus();
return false;
}
else if (document.form1.numOfUpload.selectedIndex == 0) {
alert ("Please select number of files to upload!");
return false;
}
}
return true;
}

</script>



JavaScript Code:
You have to include this code within the tag HEAD of the page.

<script type="text/javascript">
var ck_name = /^[A-Za-z0-9 ]{3,20}$/;
var ck_email = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]
{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i 
var ck_username = /^[A-Za-z0-9_]{1,20}$/;
var ck_password =  /^[A-Za-z0-9!@#$%^&*()_]{6,20}$/;

function validate(form){
var name = form.name.value;
var email = form.email.value;
var username = form.username.value;
var password = form.password.value;
var gender = form.gender.value;
var errors = [];
 
 if (!ck_name.test(name)) {
  errors[errors.length] = "You valid Name .";
 }
 if (!ck_email.test(email)) {
  errors[errors.length] = "You must enter a valid email 
address.";
 }
 if (!ck_username.test(username)) {
  errors[errors.length] = "You valid UserName no special 
char .";
 }
 if (!ck_password.test(password)) {
  errors[errors.length] = "You must enter a valid Password ";
 }
 if (gender==0) {
  errors[errors.length] = "Select Gender";
 }
 if (errors.length > 0) {

  reportErrors(errors);
  return false;
 }
  return true;
}
function reportErrors(errors){
 var msg = "Please Enter Valide Data...\n";
 for (var i = 0; i<errors.length; i++) {
 var numError = i + 1;
  msg += "\n" + numError + ". " + errors[i];
}
 alert(msg);
}
</script>

HTML Code
You have to modify action="#"
<form method="post" action="#" onSubmit="return validate(this);" name="form">

</form> 

 For url

<html>
<head>
<title>Url validation using regex</title>
<script type="text/javascript">
    function validate() {
        var url = document.getElementById("url").value;
        var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
        if (pattern.test(url)) {
            alert("Url is valid");
            return true;
        } 
            alert("Url is not valid!");
            return false;

    }
</script>
</head>
<body>
<h2>Validating Url..</h2>
Url :<input type="text" name="url" id="url" />
<input type="submit" value="Check" onclick="validate();" />
</body>
</html>

url pattern is like HYPERLINK

"http://www.roseindia.net/hibernate/examples/criteria"

http://www.roseindia.net/hibernate/examples/criteria


In pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!-\/]))?/;

/../(forward slashes) is used to quote your regular expression.

() is used to group the content.

| is used for or condition

\/ backslash consider / as a literal .

\w+ for one or more alphanumeric value.

{0,1} shows the range of content having length between 0 to 1.

* matches the preceding character zero or more time.

[..] matches any letter enclosed with in.

+ shows that preceding character come 1 or more times.

. Shows that \ will treat . as a literal.

$ is used for ending the string.

test() method takes one argument and check that to the pattern. 

Trim in javascript

if (theForm.LastName.value.replace(/^\s+|\s+$/g, "") == "")
{
alert("Please enter a value for the \"LastName\" field.");
theForm.LastName.focus();
return (false);
}

Validate alphabet and numeric in javascript.

<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to display the third character of a string.</p>

<button onclick="alphanumeric()">Try it</button>

<script type="text/javascript">

function alphanumeric() 

var inputtxt="1Hello";
 var letterNumber = /^[0-9a-zA-Z]+$/; 
 if(letterNumber.test(inputtxt))  
  { 
   alert('OK');
  } 
else 
  {  
   alert("message");  
   return false;  
  } 




</script>

</body>
</html>

Shallow copy and Deep Copy

Shallow copy

A shallow copy in progress.
A shallow copy having been completed.
A shallow copy in progress.

A shallow copy having been completed.
One method of copying an object is the shallow copy. In this process, B is attached to the same memory block as A. This is otherwise known as address copy.
This results in a situation in which same data is shared between A and B, thus modifying the one will alter the other. The original memory block of B is now no longer referred to from anywhere. If the language does not have automatic garbage collection the original memory block of B has probably been leaked.
The advantage of shallow copies is that their execution speed is fast and does not depend on the size of the data.
Bitwise copies of objects which are not made up of a monolithic block are shallow copies.

Deep copy

A deep copy in progress.
A deep copy having been completed.
A deep copy in progress.

A deep copy having been completed.
An alternative is a deep copy. Here the data is actually copied over. The result is different from the result a shallow copy gives. The advantage is that A and B do not depend on each other but at the cost of a slower more expensive copy.

Data Annotation Validator Attributes

When you use the Data Annotations Model Binder, you use validator attributes to perform validation. The System.ComponentModel.DataAnnotations namespace includes the following validator attributes:
  • Range – Enables you to validate whether the value of a property falls between a specified range of values.
  • ReqularExpression – Enables you to validate whether the value of a property matches a specified regular expression pattern.
  • Required – Enables you to mark a property as required.
  • StringLength – Enables you to specify a maximum length for a string property.
  • Validation – The base class for all validator attributes.
If your validation needs are not satisfied by any of the standard validators then you always have the option of creating a custom validator attribute by inheriting a new validator attribute from the base Validation attribute.
The Product class in Listing 1 illustrates how to use these validator attributes. The Name, Description, and UnitPrice properties are marked as required. The Name property must have a string length that is less than 10 characters. Finally, the UnitPrice property must match a regular expression pattern that represents a currency amount.
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace MvcApplication1.Models
{
    
    public class Product
    {
        public int Id { get; set; }

        [Required]
        [StringLength(10)]
        public string Name { get; set; }

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

        [DisplayName("Price")]
        [Required]
        [RegularExpression(@"^\$?\d+(\.(\d{2}))?$")]
        public decimal UnitPrice { get; set; }
    }
}
 
 

Introduction

When you have domain entities in domain layer, usually you also have validation rules as a part of entities’ business rules. You will face the question where to specify the validation rules and how to verify the validation rules. This article will show you a way by using DataAnnotations library to specify and verify validation rules for domain entities.

Domain Entity

A domain entity is a class used to represent something in your problem domain. A typical domain entity looks like this:
public class Customer { public virtual string CustomerID { get; set; } public virtual string CompanyName { get; set; } public virtual string Address { get; set; } public virtual string City { get; set; } public virtual string PostalCode { get; set; } public virtual string Country { get; set; } public virtual string Phone { get; set; } } This domain entity is used to represent Customer in system by holding Customer related information. I assume when adding a new customer into the system, you must provide CustomerID and CompanyName, and the CompanyName must have maximum 10 characters. If you provided value for Country, then the value must be USA. If you provided value for Phone, then the phone number must have correct format. In summary, the Customer entity has following validation rules:
  1. CustomerID is required
  2. CompanyName is required
  3. CompanyName can have maximum 10 characters
  4. Country can only be USA when there is a value
  5. Phone must have format ###-###-#### (# means digit) when there is a value

DataAnnotations

DataAnnotations is a library in .NET Framework. It resides in assembly System.ComponentModel.DataAnnotations. The purpose of DataAnnotations is to custom domain entity class with attributes. Therefore, DataAnnotations contains validation attributes to enforce validation rules, display attributes to specify how data from the class or member is displayed, and data modeling attributes to specify the intended use of data members and the relationships between data classes. One example of validation attribute is RequiredAttribute that is used to specify that a value must be provided. One example of display attribute is DisplayAttribute that is used to specify localizable strings for data types and members that are used in the user interface. And, one example of data modeling attribute is KeyAttribute that is used to specify the property as unique identity for the entity. We will only show how to use validation attributes in here to verify validation rules for domain entity.

Specify Validation Rule for Domain Entity

Before we can verify validation rules of Customer entity, we need to put two built-in validation attributes of DataAnnotations, RequiredAttribute and StringLengthAttribute, on Customer class. The Customer class will be something like this:
public class Customer { [Required] public virtual string CustomerID { get; set; } [Required] [StringLength(15)] public virtual string CompanyName { get; set; } public virtual string Address { get; set; } public virtual string City { get; set; } public virtual string PostalCode { get; set; } public virtual string Country { get; set; } public virtual string Phone { get; set; } } Let’s take a look at RequiredAttribute and StringLengthAttribute in detail:
ValidationAttributes.gif RequiredAttribute and StringLengthAttribute all inherit from ValidationAttribute that is the base class of all validation attributes.
With the use of RequiredAttribute and StringLengthAttribute, we are only able to specify validation rules for the first three requirements, how about the last two requirements: Country can only be USA when there is a value and Phone must have format ###-###-#### (# means digit) when there is a value. The solution is to create custom validation attributes for them. We need to create two custom validation attributes here, one is for Country and another one is for Phone.

CountryAttribute for Country Validation

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class CountryAttribute: ValidationAttribute { public string AllowCountry { get; set; } public override bool IsValid(object value) { if (value == null) { return true; } if (value.ToString() != AllowCountry) { return false; } return true; } }

PhoneAttribute for Phone Validation

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class PhoneAttribute : RegexAttribute { public PhoneAttribute() : base(@"^[2-9]\d{2}-\d{3}-\d{4}$", RegexOptions.IgnoreCase) { } } The class diagram is like this:
CustomValidationAttributes.gif At the end, Customer class with all validation attributes on it will be like this:
public class Customer { [Required] public virtual string CustomerID { get; set; } [Required] [StringLength(15)] public virtual string CompanyName { get; set; } public virtual string Address { get; set; } public virtual string City { get; set; } public virtual string PostalCode { get; set; } [Country(AllowCountry="USA")] public virtual string Country { get; set; } [Phone] public virtual string Phone { get; set; } }

Verify Validation Rules for Domain Entity

After validation rules are specified on Customer entity, we can verify Customer against the rules in our application with DataAnnotations.Validator class.
[TestMethod] public void ValidateCustomer_Customer_NoError() { // Arrange Customer customer = new Customer(); customer.CustomerID = "aaa"; customer.CompanyName = "AAA company"; // Act var validationResult = ValidationHelper.ValidateEntity<customer>(customer); // Assert Assert.IsFalse(validationResult.HasError); } ValidationHelper is a helper class that wraps up the call to DataAnnotations.Validator.
public class EntityValidationResult { public IList<validationresult> Errors { get; private set; } public bool HasError { get { return Errors.Count > 0; } } public EntityValidationResult(IList<validationresult> errors = null) { Errors = errors ?? new List<validationresult>(); } } public class EntityValidator<t> where T : class { public EntityValidationResult Validate(T entity) { var validationResults = new List<validationresult>(); var vc = new ValidationContext(entity, null, null); var isValid = Validator.TryValidateObject (entity, vc, validationResults, true); return new EntityValidationResult(validationResults); } } public class ValidationHelper { public static EntityValidationResult ValidateEntity<t>(T entity) where T : class { return new EntityValidator<t>().Validate(entity); } } The line of code that does actual validation is:
var isValid = Validator.TryValidateObject(entity, vc, validationResults, true); Note: The last parameter, validateAllProperties, of TryValidateObject method is a Boolean type variable. You must pass in true to enable verification on all types of validation attributes, include the custom validation attributes we used above. If you pass in false, only RequiredAttribute used on entity will be verified. The name of this parameter is very misleading.
The validation process is like this:
ValidationSequence.gif

Summary

DataAnnotations library provides an easy way to specify and verify validation rules on domain entity. Also, it is opening for change by design, so developers can add their own validation attributes for their own situation. By specifying validation rules on domain entity directly allow upper layers have no worry of validation anymore.
 

Events

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

namespace EventGenerate
{
    using System.Collections;

    // A delegate type for hooking up change notifications.
    public delegate void ChangedEventHandler(object sender, EventArgs e);

    // A class that works just like ArrayList, but sends event notifications whenever the list changes.
     public class ListWithChangedEvent : ArrayList
    {
        // An event that clients can use to be notified whenever the elements of the list change.
         public event ChangedEventHandler Changed;

        // Invoke the Changed event; called whenever list changes
        protected virtual void OnChanged(EventArgs e)
        {
            if (Changed != null)
                Changed(this, e);
        }

        // Override some of the methods that can change the list;
        // invoke event after each
        public override int Add(object value)
        {
            int i = base.Add(value);
            OnChanged(EventArgs.Empty);
            return i;
        }

        public override void Clear()
        {
            base.Clear();
            OnChanged(EventArgs.Empty);
        }

        public override object this[int index]
        {
            set
            {
                base[index] = value;
                OnChanged(EventArgs.Empty);
            }
        }
    }
}

namespace TestEvents
{
    using EventGenerate;

    class EventListener
    {
        private ListWithChangedEvent List;

        public EventListener(ListWithChangedEvent list)
        {
            List = list;
            // Add "ListChanged" to the Changed event on "List".
            List.Changed += new ChangedEventHandler(ListChanged);
        }

        // This will be called whenever the list changes.
        private void ListChanged(object sender, EventArgs e)
        {
            Console.WriteLine("This is called when the event fires.");
        }

        public void Detach()
        {
            // Detach the event and delete the list
            List.Changed -= new ChangedEventHandler(ListChanged);
            List = null;
        }
    }

    class Test
    {
        // Test the ListWithChangedEvent class.
        public static void Main()
        {
            // Create a new list.
            ListWithChangedEvent list = new ListWithChangedEvent();

            // Create a class that listens to the list's change event.
            EventListener listener = new EventListener(list);

            // Add and remove items from the list.
            list.Add("item 1");
            list.Clear();
            listener.Detach();
            Console.Read();
        }
    }
}

Events

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

namespace EventSample
{
    using System;
    using System.ComponentModel;

    // Class that contains the data for
    // the alarm event. Derives from System.EventArgs.
    //
    public class AlarmEventArgs : EventArgs
    {
        private readonly bool snoozePressed;
        private readonly int nrings;

        //Constructor.
        //
        public AlarmEventArgs(bool snoozePressed, int nrings)
        {
            this.snoozePressed = snoozePressed;
            this.nrings = nrings;
        }

        // The NumRings property returns the number of rings
        // that the alarm clock has sounded when the alarm event
        // is generated.
        //
        public int NumRings
        {
            get { return nrings; }
        }

        // The SnoozePressed property indicates whether the snooze
        // button is pressed on the alarm when the alarm event is generated.
        //
        public bool SnoozePressed
        {
            get { return snoozePressed; }
        }

        // The AlarmText property that contains the wake-up message.
        //
        public string AlarmText
        {
            get
            {
                if (snoozePressed)
                {
                    return ("Wake Up!!! Snooze time is over.");
                }
                else
                {
                    return ("Wake Up!");
                }
            }
        }
    }

    // Delegate declaration.
    //
    public delegate void AlarmEventHandler(object sender, AlarmEventArgs e);

    // The Alarm class that raises the alarm event.
    //
    public class AlarmClock
    {
        private bool snoozePressed = false;
        private int nrings = 0;
        private bool stop = false;

        // The Stop property indicates whether the
        // alarm should be turned off.
        //
        public bool Stop
        {
            get { return stop; }
            set { stop = value; }
        }

        // The SnoozePressed property indicates whether the snooze
        // button is pressed on the alarm when the alarm event is generated.
        //
        public bool SnoozePressed
        {
            get { return snoozePressed; }
            set { snoozePressed = value; }
        }
        // The event member that is of type AlarmEventHandler.
        //
        public event AlarmEventHandler Alarm;

        // The protected OnAlarm method raises the event by invoking
        // the delegates. The sender is always this, the current instance
        // of the class.
        //
        protected virtual void OnAlarm(AlarmEventArgs e)
        {
            if (Alarm != null)
            {
                // Invokes the delegates.
                Alarm(this, e);
            }
        }

        // This alarm clock does not have
        // a user interface.
        // To simulate the alarm mechanism it has a loop
        // that raises the alarm event at every iteration
        // with a time delay of 300 milliseconds,
        // if snooze is not pressed. If snooze is pressed,
        // the time delay is 1000 milliseconds.
        //
        public void Start()
        {
            for (; ; )
            {
                nrings++;
                if (stop)
                {
                    break;
                }

                else if (snoozePressed)
                {
                    System.Threading.Thread.Sleep(1000);
                    {
                        AlarmEventArgs e = new AlarmEventArgs(snoozePressed,
                           nrings);
                        OnAlarm(e);
                    }
                }
                else
                {
                    System.Threading.Thread.Sleep(300);
                    AlarmEventArgs e = new AlarmEventArgs(snoozePressed,
                       nrings);
                    OnAlarm(e);
                }
            }
        }
    }

    // The WakeMeUp class that has a method AlarmRang that handles the
    // alarm event.
    //
    public class WakeMeUp
    {

        public void AlarmRang(object sender, AlarmEventArgs e)
        {

            Console.WriteLine(e.AlarmText + "\n");

            if (!(e.SnoozePressed))
            {
                if (e.NumRings % 10 == 0)
                {
                    Console.WriteLine(" Let alarm ring? Enter Y");
                    Console.WriteLine(" Press Snooze? Enter N");
                    Console.WriteLine(" Stop Alarm? Enter Q");
                    String input = Console.ReadLine();

                    if (input.Equals("Y") || input.Equals("y")) return;

                    else if (input.Equals("N") || input.Equals("n"))
                    {
                        ((AlarmClock)sender).SnoozePressed = true;
                        return;
                    }
                    else
                    {
                        ((AlarmClock)sender).Stop = true;
                        return;
                    }
                }
            }
            else
            {
                Console.WriteLine(" Let alarm ring? Enter Y");
                Console.WriteLine(" Stop Alarm? Enter Q");
                String input = Console.ReadLine();
                if (input.Equals("Y") || input.Equals("y")) return;
                else
                {
                    ((AlarmClock)sender).Stop = true;
                    return;
                }
            }
        }
    }



    // The driver class that hooks up the event handling method of
    // WakeMeUp to the alarm event of an Alarm object using a delegate.
    // In a forms-based application, the driver class is the
    // form.
    //
    public class AlarmDriver
    {
        public static void Main(string[] args)
        {
            // Instantiates the event receiver.
            WakeMeUp w = new WakeMeUp();

            // Instantiates the event source.
            AlarmClock clock = new AlarmClock();

            // Wires the AlarmRang method to the Alarm event.
            clock.Alarm += new AlarmEventHandler(w.AlarmRang);

            clock.Start();
        }
    }
}