Thursday, October 20, 2011

Key Object-Oriented Concepts in C#

Abstract
This paper is an overview of Object-Oriented concepts and how to implement them in Visual C#. We begin with an overview of Object-Oriented concepts in C# and then represent an detailed example in Visual C# that shows how to implement them.

Classes
In Visual C#, all code is contained in a class. Some members of classes are described in Table 1:
Member
Description
Example
Fields

Fields store the data a class needs to fulfill its design.
Fields are declared within the class block by specifying the access level of the field, followed by the type of the field, followed by the name of the field.

private double seconds;
Properties

Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields.
Properties can be used as though they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily while still providing the safety and flexibility of methods.
public double Hours
{
get { return seconds /
3600; }
set { seconds = value
* 3600; }
}
Methods

A method is a code block containing a series of statements.
public void AddGas(int gallons) { }

Events

An event is a way for a class to provide notifications when something of interest happens.
For example, a class that encapsulates a user interface control might define an event to occur when the user clicks on the control.
The control class does not care what happens when the button is clicked, but it does need to tell derived classes that the click event has occurred. The derived classes can then choose how to respond.


Table 1 – Some members of classes

Example: This example shows how to implement members of a class.
public class List
{
const int defaultCapacity = 4;
Constant
object[] items;
int count;
Fields
public List(): List(defaultCapacity) {}
public List(int capacity) {
items = new object[capacity];
}
Constructors
public int Count {
get { return count; }
}
public string Capacity {
get {
return items.Length;
}
set {
if (value < count) value = count;
if (value != items.Length) {
object[] newItems = new object[value];
Array.Copy(items, 0, newItems, 0, count);
items = newItems;
}
}
}
Properties
public object this[int index] {
get {
return items[index];
}
set {
items[index] = value;
OnListChange();
}
}
Indexer
public void Add(object item) {
if (count == Capacity) Capacity = count * 2;
items[count] = item;
count++;
OnChanged();
}
protected virtual void OnChanged() {
if (Changed != null) Changed(this, EventArgs.Empty);
}
public override bool Equals(object other) {
return Equals(this, other as List);
}
static bool Equals(List a, List b) {
if (a == null) return b == null;
if (b == null || a.count != b.count) return false;
for (int i = 0; i < a.count; i++) {
if (!object.Equals(a.items[i], b.items[i])) {
return false;
}
}
return true;
}
Methods
public event EventHandler Changed;
Event
public static bool operator ==(List a, List b) {
return Equals(a, b);
}
public static bool operator !=(List a, List b) {
return !Equals(a, b);
}
Operators
}

If you want to create methods or properties that can be called without first creating an object, declare those items as static. (Equivalent of a Visual Basic .NET module)
Visual C# uses six key concepts for working with classes. Table 2 describes these key concepts.

Concept
In Visual C#
Definition
» You define classes using the class keyword.
» All executable code is part of a class.

Access
» There are five levels of access to classes and their members:
  • public
  • internal
  • protected
  • protected internal
  • private
» For more information, refer to table 3

Inheritance
Classes can inherit members from base classes and override or overload members of the inherited class.

Constructors and destructors
» Classes have constructors and destructors that are called when an object based on the class is created or destructors.
» Constructor methods have the same name as their class.
» Destructor methods use the class name preceded by a tilde (~).

Delegates
» The delegates keyword provides a safe way to call methods by their address rather than by their name.
» This is the .NET equivalent of a callback.
» Delegates are commonly used with events and asynchronous procedures.

Abstract classes and interfaces
» You can create interfaces and abstract classes.
» Interfaces define the member names and member parameter lists for classes that use the interface.
» Abstract classes provide the members to be inherited by classes derived from them.
Table 2 – Key Object-Oriented Concepts




Creating Classes and Providing Access
In Visual C#, use the class keyword to define classes. Use on of the access keywords described in table 3 to define which other classes can use the members of the current class.

Visual C#
Available to
Public
ALL members in all classes and PROJECTS.
Internal
» All members in the current PROJECT.
» in Visual Basic: Friend
Protected
» All members in the current CLASS and in classes DERIVED from this member's class.
» Can be used only in member definitions, not for classes or modules definitions.

Protected internal
» All members in the current PROJECT and all members in classes derived from this member's class.
» Can be used only in member definitions, not for classes or modules definitions.
Private
Members of the current class only.

Table 3 – Levels of Access for Classes


Inheritance
Visual C# uses the keywords described in Table 4 for creating base classes and deriving new classes from them.

Visual Basic
Visual C#
Use to
Inherits
derivedclass : baseclass
Base on class on another, inheriting members from the base class.

Overridable
virtual
Declares that a member of the base class can be overriden in a derived class.

Overrides
override
Declares that a member of a derived class overrides the member of the same name in the base class.

Shadows
new
Declares that a member of a derived class hides the member of the same name in the base class.
MustInherit
abstract
Declares that a class provides a template for derived classes. This type of class is called an abstract class, and it can’t be instantiated.

MustOverride
abstract
Declares that a member of a class provides a template for derived members. This type of member is called an abstract member, and it can’t be invoked.

MyBase
base
Call a base class member from within the derived class.

Me
this
Call a member of the current instance of a class.

Interface
interface
Create an interface that defines the members a class must provide.

Implements
classname : interface
Use an interface definition in a class.

Table 4 – Overview of the Inheritance Keywords


Overriding, Overloading and Shadowing Members
A derived class inherits the members of its base class. A member's signature includes its name, parameter list, parameter types, and return type. If the derived class defines a member with the same signature, the derived member overrides the base member. If a derived class defines a member with the same name but a different parameter list, parameter type, or return type than the base member, the derived member either overloads or shadows the base member. A member overloads another member if the base member is still available. A member shadows another member if the derived member replaces the base member.


In the Abstract
» An abstract class is a class that provides a template for derived classes, and it can’t be instantiated.
» An abstract method is a virtual method with no implementation.
» An abstract method is declared with the abstract modifier and is permitted only in a class that is also declared abstract.
» An abstract method must be overridden in every non-abstract derived class.


Interface-to-Face
Interfaces are similar to abstract classes in that they both provide a template that you can use to create new classes. The difference is that interfaces don’t provide any implementation of class members, whereas abstract classes can implement members that then become common to all the classes derived from them.

When you implement a particular interface in a class, instances of that class can be used for any argument or variable declared as that interface.


Detailed Example
Now, we represent an example that shows how to implement following class diagram in Visual C#.

Example.jpg
Figure 1 – Class Diagram of Detailed Example

// (1): (virtual)
//      In Visual C#, members that can be overriden must be declared
//          as virtual.
// (2): (Sphere: Circle)
//      Sphere class inherits all of methods and properties defined //          in Circle.
// (3): (override)
//      Sphere overrides the methods for Area, because
//          sphere use a different formula for this calculation.
//      A virtual method can be overridden in a derived class.
// (4): (new)
//      Sphere shadows the Center method because
//          sphere have an additional coordinate (z)
//          and you wouldn't want users to accidentally set
//          xy-coordinates without setting a z-coordinate.
// (5): (base)
//      Notice that Sphere uses the base keyword to call
//          the base class's Center method within the shadowed 
//          method.

// Interface for all shapes.
public interface IFigure
{
    float Top
    {
        get;
        set;
    }
    float Left
    {
        get;
        set;
    }

    float Area();
    float Perimeter();
}
// To use the inteface, implement it in a class
public abstract class Shape : IFigure
{
    // Constructor
 public Shape()
 {
 }

    public abstract float Top
    {
        get;
        set;
    }
    public abstract float Left
    {
        get;
        set;
    }

    public abstract float Area();
    public abstract float Perimeter();
}
public class Circle : Shape
{
    float fxCenter, fyCenter, fRadius;
    // Constructor
    public Circle()
    {
        // Intialize internal variables.
        fxCenter = 0;
        fyCenter = 0;
        fRadius = 0;
    }

    public override float Top
    {
        get
        {
            return fxCenter - fRadius;
        }
        set
        {
            fxCenter = value + fRadius;
        }
    }
    public override float Left
    {
        get
        {
            return fyCenter - fRadius;
        }
        set
        {
            fyCenter = value + fRadius;
        }
    }
    public float Radius
    {
        get
        {
            return fRadius;
        }
        set
        {
            fRadius = value;
        }
    }

    public override float Area()
    {
        return (float)(System.Math.PI * Math.Pow((double)fRadius, 
                       2));
    }

    public override float Perimeter()
    {
        return 2 * fRadius * (float)System.Math.PI;
    }

    public virtual void Center(float X, float Y)    // (1)
    {
        fxCenter = X;
        fyCenter = Y;
    }
}
public class Sphere : Circle                        // (2)
{
    float fCenter;

    // Constructor
    public Sphere()
    {
        // Initialize internal variable.
        fCenter = 0;
    }
    public float Front
    {
        get
        {
            return fCenter - base.Radius;
        }
        set
        {
            fCenter = value + base.Radius;
        }
    }

    public override float Area()                    // (3)
    {
        return (float)(4 * Math.PI * Math.Pow((double)base.Radius, 
                       2));
    }

    public void Center(float X, float Y, float Z)
    {
        base.Center(X, Y);                          // (5)
        fCenter = Z;
    }

    public new void Center(float X, float Y)        // (4)
    {
        this.Center(X, Y, 0);
    }

    public float Volume()
    {
        return (float)((4 / 3) * System.Math.PI * 
                       Math.Pow((double)base.Radius, 3));
    }
}
public partial class _Default : System.Web.UI.Page 
{
    // Displays the shape info on the Web form.
    // Because the Shape abstract class in this example implements 
    //     the IFigure interface,
    //     all derived classes from Shape can be used as the 
    //     arguments of the type IFigure.
    private void ShowShapeInfo(IFigure Shape)
    {
        // Since Shape argument is IFigure, we know it has these 
               members.
        Response.Write(String.Format("Shape Top : {0} <br>", 
                       Shape.Top));
        Response.Write(String.Format("Shape Left: {0} <br>", 
                       Shape.Left));
        Response.Write(String.Format("Shape Area: {0} <br>", 
                       Shape.Area()));
        Response.Write(String.Format("Shape Primeter: {0} <br>", 
                       Shape.Perimeter()));
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        // Create a circle
        Circle MyCircle = new Circle();
        MyCircle.Radius = 2;
        MyCircle.Center(10, 2);
        // Create a sphere
        Sphere MySphere = new Sphere();
        MySphere.Radius = 10;
        MySphere.Center(10, 20, 25);
        // Show info about each shape.
        ShowShapeInfo(MyCircle);
        ShowShapeInfo(MySphere);
    }
}


OOPs with Real time Examples

Oops! What an excellent concept. Nowadays in software filed any latest language has implemented, it should be partially are fully supported this oops concept. OOPs, let c with real time examples. Six important factors are using this concept are,
  1. Class, 2.Objects, 3.Abstractions, 4.Encapsulation, 5.Polymorphism, and 6.Inheritance.
1. Car Vs Class
Car: Collection of several properties like staring, break, clutch, etc each things are used for particular purpose, all these properties are differ from each car like some car have power staring ,however we have called it’s a car.
Class: it’s a collection of functions and variables. The functions and variables are differing from each class. Each function is used for particular purpose however we have called it’s a class
2. Car Key Vs Object
Car Key: key is used for run the car. So many dummy keys can use for run a car.
Object: Object is used for run the class or invokes the class. So many objects can create for a single class.
3. Birds Vs Abstractions
Birds: we invented flight based on the mechanism of Birds. So flight is derived form the base of birds.
Abstraction: Abstraction is a way to remove the association of the behavior of an object with the actual details behind the scenes which implement that object's behavior. This 'abstraction' is usually accomplished through the use of base classes with virtual functions; each derived function provides the details that implement the behavior behind that abstraction.
4. Pen Vs Encapsulation
Pen: Ink is the important component in pen but it is hiding by some other material
Encapsulation: is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.
5. Crocodile Vs Polymorphism
Crocodile: live indifferently on land or in the water. In water it’s Moment very fast compare to land. An animal lives in different character in different place.
Polymorphism: a single function or single operator has different character in different place.
6. Human heredity Vs Inheritance
Human heredity:

Friday, October 14, 2011

Javascript---password strength meter

The html code

<form method="post" action="" id="user_registration" name="user_registration">

  <p><h1>Password strength metter</h1></p>

  <p> 

  <label for="user">Username</label>
<input type="text" name="user" id="user"/>

  </p>

  <p> 

  <label for="name">Name</label>
<input type="text" name="name" id="name"/>

  </p>

  <p> 

  <label for="surname">Surname</label>
<input type="text" name="surname" id="surname"/>

  </p>

  <p> 

  <label for="email">E-mail</label>
<input type="text" name="email" id="email"/>

  </p>

  <p> 

   <label for="pass">Password</label>
<input type="password" name="pass" id="pass" 
onkeyup="passwordStrength(this.value)" />

    

  </p>

  <p> 

  <label for="pass2">Confirm Password</label>
<input type="password" name="pass2" id="pass2"/>

  </p>

  <p>

   <label for="passwordStrength">Password strength</label>

   <div id="passwordDescription">Password not entered</div>

   <div id="passwordStrength" class="strength0"></div>

  </p>

  <p> 

  <input type="submit" name="submit" id="submit" value="Register">

  </p>

</form>
The csss code
#passwordStrength

{

 height:10px;

 display:block;

 float:left;

}



.strength0

{

 width:250px;

 background:#cccccc;

}



.strength1

{

 width:50px;

 background:#ff0000;

}



.strength2

{

 width:100px; 

 background:#ff5f5f;

}



.strength3

{

 width:150px;

 background:#56e500;

}



.strength4

{

 background:#4dcd00;

 width:200px;

}



.strength5

{

 background:#399800;

 width:250px;

}

And finally the javascript code
function passwordStrength(password)

{

 var desc = new Array();

 desc[0] = "Very Weak";

 desc[1] = "Weak";

 desc[2] = "Better";

 desc[3] = "Medium";

 desc[4] = "Strong";

 desc[5] = "Strongest";



 var score   = 0;



 //if password bigger than 6 give 1 point

 if (password.length > 6) score++;



 //if password has both lower and uppercase characters give 1 point 

 if ( ( password.match(/[a-z]/) ) && ( password.match(/[A-Z]/) ) ) score++;



 //if password has at least one number give 1 point

 if (password.match(/\d+/)) score++;



 //if password has at least one special caracther give 1 point

 if ( password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/) ) score++;



 //if password bigger than 12 give another 1 point

 if (password.length > 12) score++;



  document.getElementById("passwordDescription").innerHTML = desc[score];

  document.getElementById("passwordStrength").className = "strength" + score;

}