Friday, 27 July 2012

ASP.NET Utilities


ASP.NET Utilities


ASP.NET Model


ASP.Net is a web development platform, which provides a programming model, a comprehensive software infrastructure and various services required to build up robust web application for PC, as well as mobile devices.
ASP.Net works on top of the HTTP protocol and uses the HTTP commands and policies to set a browser-to-server two-way communication and cooperation.
ASP.Net is a part of Microsoft .Net platform. ASP.Net applications are complied codes, written using the extensible and reusable components or objects present in .Net framework. These codes can use the entire hierarchy of classes in .Net framework.
The ASP.Net application codes could be written in any of the following languages:
  • C#
  • Visual Basic .Net
  • Jscript
  • J#

ASP.Net is used to produce interactive, data-driven web applications over the internet. It consists of a large number of controls like text boxes, buttons and labels for assembling, configuring and manipulating code to create HTML pages.

ASP.Net Web Forms Model


ASP.Net web forms extend the event-driven model of interaction to the web applications. The browser submits a web form to the web server and the server returns a full markup page or HTML page in response.
All client side user activities are forwarded to the server for stateful processing. The server processes the output of the client actions and triggers the reactions.
Now, HTTP is a stateless protocol. ASP.Net framework helps in storing the information regarding the state of the application, which consists of:
  • Page state
  • Session state
The page state is the state of the client, i.e., the content of various input fields in the web form.
The session state is the collective obtained from various pages the user visited and worked with, i.e., the overall session state.
The ASP.Net runtime carries the page state to and from the server across page requests while generating the ASP.Net runtime codes and incorporates the state of the server side components in hidden fields.

ASP.Net Component Model


The ASP.Net component model provides various building blocks of ASP.Net pages. Basically it is an object model, which describes:
  • Server side counterparts of almost all HTML elements or tags, like <form> and <input>.
  • Server controls, which help in developing complex user-interface for example the Calendar control or the Gridview control.

ASP.Net is a technology, which works on the .Net framework that contains all web-related functionalities. The .Net framework is made of an object-oriented hierarchy. An ASP.Net web application is made of pages. When a user requests an ASP.Net page, the IIS delegates the processing of the page to the ASP.Net runtime system.
The ASP.Net runtime transforms the .aspx page into an instance of a class, which inherits from the base class Page of the .Net framework. Therefore, each ASP.Net page is an object and all its components i.e., the server-side controls are also objects.

Components of .Net Framework 4


The various components the .Net framework 4 are:
  • Common Language Runtime or CLR
    It performs memory management, exception handling, debugging, security checking, thread execution, code execution, code safety, verification and compilation.Those codes which are directly managed by the CLR are called the managed code. When the managed code is compiled, the compiler converts the source code into a CPU independent intermediate language (IL) code. A Just in time compiler (JIT) compiles the IL code into native code, which is CPU specific.
  • .Net Framework Class Library
    It contains a huge library of reusable types . classes, interfaces, structures and enumerated values, which are collectively called types.
  • Common Language Specification
    It contains the specifications for the .Net supported languages and implementation of language integration.
  • Common Type System
    It provides guidelines for declaring, using and managing types at runtime, and cross-language communication.
  • Metadata and Assemblies
    Metadata is the binary information describing the program, which is either stored in a portable executable file (PE) or in the memory. Assembly is a logical unit consisting of the assembly manifest, type metadata, IL code and set of resources like image files etc.
  • Windows Forms
    This contains the graphical representation of any window displayed in the application.
  • ASP.Net and ASP.Net AJAX
    ASP.Net is the web development model and AJAX is an extension of ASP.Net for developing and implementing AJAX functionality. ASP.Net AJAX contains the components that allow the developer to update data on a website without a complete reload of the page.
  • ADO.Net
    It is the technology used for working with data and databases. It provides accesses to data sources like SQL server, OLE DB, XML etc. The ADO .Net allows connection to data sources for retrieving, manipulating and updating data.
  • Windows Workflow Foundation (WF)
    It helps in building workflow based applications in Windows. It contains activities, workflow runtime, workflow designer and a rules engine.
  • Windows Presentation Foundation
    It provides a separation between the user interface and the business logic. It helps in developing visually stunning interfaces using documents, media, two and three dimensional graphics, animations and more.
  • Windows Communication Foundation (WCF)
    It is the technology used for building and running connected systems.
  • Windows CardSpace
    It provides safety of accessing resources and sharing personal information on the internet.
  • LINQ
    It imparts data querying capabilities to .Net languages using a syntax which is similar to the tradition query language SQL.

Nullable Types In C#


Nullable Types

Nullable types represent value-type variables that can be assigned the value of null.
Nullable types are declared in one of two ways:
System.Nullable<t> variable
-or-
T? variable
T is the underlying type of the nullable type. T can be any value type including struct; it cannot be a reference type.
In many programming applications, where there is database interactions, variables can exist in an undefined state. For example, a field in a database may contain the values true or false, but it may also contain no value at all. Similarly, reference types can be set to null to indicate that they are not initialized.
The nullable type modifier enables C# to create value-type variables that indicate an undefined value.
Example - Nullable Types
using System;
public struct Prime
{
public int PrimeNum;
public Prime(int num)
{
PrimeNum = num;
Console.WriteLine(num);
}
}
class PrimeNumbers
{
static void Main(string [] args)
{
Prime? objPrime = new Prime?(new Prime(5));
}
}

System.Nullable<>


using System;
using System.Collections.Generic;
using System.Text;
namespace School
{
class nullType
{
static void Main(string[] args)
{
System.Nullable<int> numOne = 34;
System.Nullable<int> numTwo = null;
System.Nullable<int> res = numOne + numTwo;
if (res.HasValue == true)
Console.WriteLine(res);
else
Console.WriteLine("Result Null");
}
}
}

Converting Nullable Types. Implicit Conversion

using System;
class ImplicitConversion
{
static void Main (string [] args)
{
int? numOne = null;
if (numOne.HasValue == true)
{
Console.WriteLine("Value of numOne before conversion: " + numOne);
}
else
{
Console.WriteLine ("Value of numOne: null");
}
numOne = 20;
Console.WriteLine("Value of numOne after implicit conversion: " + numOne);
}
}

Converting Nullable Types : Explicity Conversion

using System;
class ExplicitConversion
{
static void Main (string [] args)
{
int? numOne = null;
int numTwo = 20;
int? resultOne = numOne + numTwo;
if (resultOne.HasValue == true)
{
Console.WriteLine("Value of numOne before conversion: " + resultOne);
}
else
{
Console.WriteLine ("Value of resultOne: null");
}
numOne = 10;
int result = (int) (numOne + numTwo);
Console.WriteLine("Value of result after explicit conversion: " + result);
}
}

Boxing Nullable Types

using System;
class Boxing
{
static void Main (string [] args)
{
int? number = null;
object objOne = number;
if (objOne != null)
{
Console.WriteLine("Value of object one : " + objOne);
}
else
{
Console.WriteLine ("Value of object one: null");
}
double? value = 10.26;
object objTwo = value;
if (objTwo != null)
{
Console.WriteLine("Value of object two: " + objTwo);
}
else
{
Console.WriteLine("Value of object two: null");
}
}
}



Asymmetric Accessor Accessibility


Accessors

The get and set portions of a property or indexer are called accessors. By default these accessors have the same visibility, or access level. However, it is sometimes useful to restrict access to one of these accessors. Typically, this involves restricting the accessibility of the set accessor, while keeping the get accessor publicly accessible. For example:
public string Name
{
get
{
return name;
}
protected set
{
name = value;
}
}
In this example, a property called Name defines a get and set accessor. The get accessor receives the accessibility level of the property itself, public in this case, while the set accessor is explicitly restricted by applying the protected access modifier to the accessor itself.


Properties And Indexers


PROPERTIES

Properties provide the opportunity to protect a field in a class by reading and writing to it through the property. C# properties enable this type of protection while also letting you access the property just like it was a field.
Another benefit of properties over fields is that you can change their internal implementation over time. With a public field, the underlying data type must always be the same because calling code depends on the field being the same. However, with a property, you can change the implementation. For example, if a customer has an ID that is originally stored as an int, you might have a requirements change that made you perform a validation to ensure that calling code could never set the ID to a negative value. If it was a field, you would never be able to do this, but a property allows you to make such a change without breaking code.


Defining property

using System;
class Employee
{
string _empName;
public string EmpName
{
get
{
return _empName;
}
set
{
_empName = value;
}
}
}
class SalaryDetails : Employee
{
static void Main(string [] args)
{
SalaryDetails obj = new SalaryDetails();
obj.EmpName = "Frank";
Console.WriteLine ("Name : " + obj.EmpName);
}
}


Defining several Properties

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Employee
{
string _empName;
int _empID;
float _salary;
public string EmpName
{
get
{
return _empName;
}
set
{
_empName = value;
}
}
public int EmpID
{
get
{
return _empID;
}
set
{
_empID = value;
}
}
public float Salary
{
get
{
return _salary;
}
set
{
_salary = value;
}
}
}
class SalaryDetails : Employee
{
static void Main(string[] args)
{
SalaryDetails obj = new SalaryDetails();
obj.EmpName = "Frank";
obj.EmpID = 10;
obj.Salary = 1000.25F;
Console.WriteLine("Name : " + obj.EmpName);
Console.WriteLine("ID : " + obj.EmpID);
Console.WriteLine("Salary : " + obj.Salary + "$");
}
}
}


ToString() property

using System;
public class Person
{
private string myName="N/A";
private int myAge = 0;
public string Name
{
get
{
return myName;
}
set
{
myName = value;
}
}
public int Age
{
get
{
return myAge;
}
set
{
myAge = value;
}
}
public override string ToString()
{
return "Name: " + Name + " Age: " + Age;
}
public static void Main ()
{
Person obj = new Person();
Console.WriteLine("Person Details: {0}", obj);
obj.Name = "Delhi";
obj.Age = 100;
Console.WriteLine("Person Details: {0}", obj);
obj.Age += 1;
Console.WriteLine("Person Details: {0}", obj);
}
}


Properties: Implementing Polymorphism

Example 1
using System;
class Car
{
string _carType;
public virtual string CarType
{
get
{
return _carType;
}
set
{
_carType = value;
}
}
}
class Ferrari : Car
{
public override string CarType
{
get
{
return base.CarType;
}
set
{
base.CarType = value;
}
}
static void Main(string [] args)
{
Car objCar = new Car();
objCar.CarType = "Utility Vehicle";

Ferrari objFerrari = new Ferrari();
objFerrari.CarType = "Sports Car";
Console.WriteLine("Car Type: " + objCar.CarType);
Console.WriteLine("Ferrari Car Type : " + objFerrari.CarType);
}
}


Example 2:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Car
{
string _carType; v public virtual string CarType
{
get
{
return _carType;
}
set
{
_carType = value;
}
}
}
class Ferrari : Car
{
string _carType;
public override string CarType
{
get
{
return base.CarType;
}
set
{
base.CarType = value;
Console.Write("Enter car Name: ");
_carType = Console.ReadLine();
}
}
static void Main(string[] args)
{
Car objCar = new Car();
objCar.CarType = "Utility Vehicle";
Ferrari objFerrari = new Ferrari();
objFerrari.CarType = "Sports Car";
Console.WriteLine("Car Type: " + objCar.CarType);
Console.WriteLine("Ferrari Car Type : " + objFerrari.CarType);
Console.WriteLine(objFerrari._carType);
}
}
}


Types of Properties

Read-Only Property

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Books
{
string _bookName;
long _bookID;
public Books(string name, int value)
{
_bookName = name;
_bookID = value;
}
public string BookName
{
get
{
return _bookName;
}
}
public long BookID
{
get
{
return _bookID;
}
}
public void show()
{
Console.WriteLine(BookID + " " + BookName );
}
}
class BookStore
{
static void Main(string[] args)
{
Books obj = new Books("Learn C# in 21 Days", 10015);
Console.WriteLine("Book Name: " + obj.BookName);
Console.WriteLine("Book ID: " + obj.BookID);
obj.show();
}
}
}


Write-Only Property

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Department
{
string _deptName;
int _deptID;
public string DeptName
{
set
{
_deptName = value;
}
}
public int DeptID
{
set
{
_deptID = value;
}
}
public void Display()
{
Console.WriteLine("Department Name: " + _deptName);
Console.WriteLine("Department ID: " + _deptID);
}
}
class Company
{
static void Main(string[] args)
{
Department obj = new Department();
obj.DeptID = 201;
obj.DeptName = "Sales";
obj.Display();
}
}
}


Read-Write Property

using System;
namespace ConsoleApplication5
{
class Product
{
string _productName;
int _productID;
float _price;
public Product(string name, int val)
{
_productName = name;
_productID = val;
}
public float Price
{
get
{
return _price;
}
set
{
if (value < 0) { _price = 0; } else { _price = value; } } } public void Display() { Console.WriteLine("Product Name: " + _productName); Console.WriteLine("Product ID: " + _productID); Console.WriteLine("Price: " + _price + "$"); } } class Goods { static void Main(string[] args) { Product obj = new Product("Hard Disk", 101); obj.Price = 345.25F; obj.Display(); } } }


Static Properties

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class University
{
private static string _department;
private static string _universityName;
public static string Department
{
get
{
return _department;
}
set
{
_department = value;
}
}
public static string UniversityName
{
get
{
return _universityName;
}
set
{
_universityName = value;
}
}
}
class Physics
{
static void Main(string[] args)
{
University.UniversityName = "University of MaryLand";
University.Department = "Physics";
Console.WriteLine("University Name: " + University.UniversityName);
Console.WriteLine("Department Name: " + University.Department);
}
}
}


Abstract properties

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication3
{
public abstract class Figure
{
public abstract float DimensionOne
{
set;
}
public abstract float DimensionTwo
{
set;
}
}
class Rectangle : Figure
{
float _dimensionOne;
float _dimensionTwo;
public override float DimensionOne
{
set
{
if (value <= 0) { _dimensionOne = 0; } else { _dimensionOne = value; } } } public override float DimensionTwo { set { if (value <= 0) { _dimensionTwo = 0; } else { _dimensionTwo = value; } } } float Area() { return _dimensionOne * _dimensionTwo; } static void Main(string[] args) { Rectangle obj = new Rectangle(); obj.DimensionOne = 4; obj.DimensionTwo = 8; Console.WriteLine("Area of Rectangle : " + obj.Area()); } } }


INDEXERS

Indexers are an elaboration of properties, and are used where you want to access some class property by index, in an array like manner. They are useful in cases where a class is a container for other objects.
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Salary
{
private float[] salary = new float[3];
public float this[int index]
{
get
{
return salary[index];
}
set
{
if (value < 0) { Console.WriteLine("Salary cannot be negetive."); return; } else { salary[index] = value; } } } static void Main(string[] args) { Salary obj = new Salary(); obj[0] = 1000F; obj[1] = 2000F; obj[2] = 3000F; Console.WriteLine("Salary Details"); for (int i = 0; i < 3; i++) { Console.WriteLine(obj[i] + "$"); } } } } Example 2 using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
public class IndexTest
{
double[] values;
public IndexTest()
{
values = new double[] { 1.1, 3.3, 5.5, 7.7, 9.9 };
}
public double this[int index]
{
get
{
if (index < 0 || index > values.Length)
throw new ArgumentOutOfRangeException();
return values[index];
}
set
{
values[index] = value;
}
}
}
public class test
{
public static int Main()
{
IndexTest it = new IndexTest();
Console.WriteLine("Index 1 is: " + it[4]);
return 0;
}
}
}


Indexer - Inheritance

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Numbers
{
private int[] num = new int[3];
public int this[int index]
{
get
{
return num[index];
}
set
{
num[index] = value;
}
}
}
class EvenNumbers : Numbers
{
public static void Main()
{
EvenNumbers obj = new EvenNumbers();
obj[0] = 0;
obj[1] = 2;
obj[2] = 4;
for (int i = 0; i < 3; i++) { Console.WriteLine(obj[i]); } } } }


Indexer - Polymorphism

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Student
{
string[] studName = new string[2];
public virtual string this[int index]
{
get
{
return studName[index];
}
set
{
studName[index] = value;
}
}
}
class Result : Student
{
string[] result = new string[2];
public override string this[int index]
{
get
{
return base[index];
}
set
{
base[index] = value;
}
}
public static void Main(string[] args)
{
Result objResult = new Result();
objResult[0] = "First";
objResult[1] = "Pass";
Student objStu = new Student();
objStu[0] = "Peter";
objStu[1] = "Patrick";
for (int i = 0; i < 2; i++) { Console.WriteLine(objStu[i] + "\t\t" + objResult[i] + "class"); } } } }


Multiple parameters in Indexers

using System;
class Account
{
string[,] accountDetails = new string[4, 2];
public string this[int pos, int column]
{
get
{
return (accountDetails[pos, column]);
}
set
{
accountDetails[pos, column] = value;
}
}
public static void Main(string[] args)
{
Account obj = new Account();
obj[0,0] = "aptech";
Console.WriteLine(obj[0, 0]);
}
}


Indexers in Interfaces

using System;
public interface IDetails
{
string this [int index ]
{
get;
set;
}
}
class Students : IDetails
{
string [] studentName = new string[3];
//int [] studentID = new int[3];
public string this [int index]
{
get
{
return studentName[index];
}
set
{
studentName[index] = value;
}
}
public static void Main(string [] args)
{
Students obj = new Students();
obj [0] = "James";
obj [1] = "Wilson";
obj [2] = "Patrick";
Console.WriteLine("Student Names:");
Console.WriteLine();
for(int i=0; i<3; i++) { Console.Write (obj[i] + " "); } } }

Common Type System (CTS)


Common Type System (CTS) In .NET

Common Type System (CTS) describes a set of types that can be used in different .Net languages in common . That is , the Common Type System (CTS) ensure that objects written in different .Net languages can interact with each other. For Communicating between programs written in any .NET complaint language, the types have to be compatible on the basic level.
These types can be Value Types or Reference Types . The Value Types are passed by values and stored in the stack. The Reference Types are passed by references and stored in the heap. Common Type System (CTS) provides base set of Data Types which is responsible for cross language integration. The Common Language Runtime (CLR) can load and execute the source code written in any .Net language, only if the type is described in the Common Type System (CTS) .Most of the members defined by types in the .NET Framework Class Library (FCL) are Common Language Specification (CLS) compliant Types.

Common Language Specification (CLS) In .NET


Common Language Specification (CLS)

Common Language Specification (CLS) is a set of basic language features that .Net Languages needed to develop Applications and Services , which are compatible with the .Net Framework. When there is a situation to communicate Objects written in different .Net Complaint languages , those objects must expose the features that are common to all the languages . Common Language Specification (CLS) ensures complete interoperability among applications, regardless of the language used to create the application.
Common Language Specification (CLS) defines a subset of Common Type System (CTS) . Common Type System (CTS) describes a set of types that can use different .Net languages have in common , which ensure that objects written in different languages can interact with each other. Most of the members defined by types in the .NET Framework Class Library (FCL) are Common Language Specification (CLS) compliant Types. Moreover Common Language Specification (CLS) are standardized by ECMA (European Computer Manufacturers Association).