Run time Polymorphism
In runtime polymorphism ... the code is called at run time according to need
or given conditions.
suppose there r two methods namely Add() one in super class and other is in
sub class.both have the same name and same parameters.
so we have to choose that which method from them shld called at run time
i.e. of super class or of sub class.by polymorphism we do that.
ex:-
class A
{
int add(){//code of the method}
//some other code
}
class B extends A
{
int add(){//code of the method}
//some other code
}
class AB
{
public static void main(String s[])
{
A ob1;
ob1=new A();
int i=ob1.add();//will call the method of super class.
ob1=new B();// sub class's reference can be assigned to super class address
but not vice versa.to do that we have to type cast the reference of the sub
class in reference of the super class.
int j=ob1.add();//will call the method of sub class
}
}
What is run time polymorpism and complie time
polymmorpism
Overloading is compile time polymorphism because compiler checkes the method
sigantures while compiling itself.(i. e: Method names Argument types argument
creation order etc...)
Overriding is run time polymorphism.
compile time polymorphism -- method overloding
run time time polymorphism -- method overriding
Overloading is compile time polymorphism also called early binding.
Overriding is runtime polymorphism also called late binding.
compile time polymorpism also known as staic poly
run time polymorpism also known as dynamic polymorpism
example for static poly is method overloading
example for dynamic poly is method overriding
static poly is linking method call at the time of compilation time
dynamic poly is linking method call at the time of runing time
What is the difference between a while statement and a do statement
A while statement checks at the beginning of a loop to
see whether the next loop iteration should occur. A do statement checks at the
end of a loop to see whether the next iteration of a loop should occur.
Difference between Arraylist and Generic
List
Arraylist –
Arraylist accept values as object
So We can give any type of data in to that.
Here in this eg: an arraylist object accepting
values like String,int,decimal, char and a custom object
ArrayList arr = new ArrayList();
arr.Add("Sabu");
arr.Add(234);
arr.Add(45.236);
arr.Add(emp);
arr.Add('s');
This process is known as boxing
Geniric type :-
Main advantage of Generic List is we can specify the type of data
List<int> intLst = new List<int>();
intLst.Add(12);
Here List accepting values as int only
List<Employee> empLst = new List<Employee>();
empLst.Add(new Employee("1", "Sabu"));
Here List accepting Employee Objects only
è If
constructor is private then we can not create the object and inherit of that
class.
-> Sealed can not be used for virtual, Abstract and static classes.
Non - Generic collection class - which collection can hold
the different type of data.
Generic collection class - which collection can hold the
same type of data.
ASP.NET provides multiple simple
solutions to this problems like:
1- Viewstate
2- Session Variables
3- Application Variables
4- Cache
5- Cookies
Now the question arises that when to use what?
1- Viewstate
Viewstate is a hidden fields in an ASP.NET page, contains state of those
controls on a page whose “EnableViewstate” property is “true”.
You can also explicitly add values in it, on an ASP.NET page like:
Viewstate.Add( “TotalStudents”, “87″ );
Viewstate should be used when you want to save a value between diferent
roundtrips of a single page as viewstate of a page is not accessible by another
page.
Because Viewstate renders with the page, it consumes bandwith, so be careful to
use it in applications to be run on low bandwith.
2- Session Variable
Session variables are usually the most commonly used.
When a user visits a site, it’s sessions starts and when the user become idle
or leave the site, the session ends.
Session variables should be used to save and retrive user specefic information
required on multiple pages.
Session variables consumes server memory, so if your may have a huge amount
visiters, use session very carefully and instead of put large values in it try
to put IDs and references
3- Application variables
Application variables are shared variables among all users of a web
application
Application variables behave like static variables and they are substitute of
static variables as static variables are stateless in web applications
Only shared values should be persisted in Application variables, and as soon as
they are not in use they should be removed explicitly.
4- Cache
Cache is probably the least used state feature of ASP.NET.
Cache is basically a resource specific state persistence feature, means unlike
session it stick with resource instead of user, for instance: pages, controls
etc.
Cache should be used or frequently used pages, controls, and data structures
Data cache can be used to cache frequently used list of values e.g. list of
products
6- Cookies
Cookies are some values saved in browsers for a particular website o
publicly accessible
The purpose of cookies is to help websites to identify visitors and retrieve
their saved preferences
Cookies are also used to facilitate auto login by persisting user id in a
cookie save in user’s browser
Because cookies have been saved at client side, they do not create performance
issues but may create security issues as they can be hacked from browser
Finally remember the following points on your finger-tips:
1- Viewstate is bandwidth hungry
2- Session variables are memory hungry as per number of users
3- Applications variables are shared
4- Cache is memory hungry as per number of resources
5- Cookies are the least secure
What is the intrinsic difference between
COOKIES AND CACHE?
cookies
are small bits of files that store your session, and other small data, its
pretty much like a database in a sense...
while
a cache is temporary storage for files used by a program(typically a browser)
to display items.... and to get a quick access to pre-parsed files.....
your browser has to store the webpage, and all pictures, video flash and those
things on the cache so that it could display it
while cookies, store only text based data about your browsing stuff.. like
passwords, number of pages visited, session number, and so on.....
Design Pattern :-
Design Pattern is a re-usable, high quality solution to a given requirement, task or recurring problem. it provides a framework for how to solve a problem.
Design Patterns are categorized into 3 types:
Creational Patterns
Structural Patterns
Behavioral Patterns
Creational Patterns
Creates an
instance of several families of classes
Separates
object construction from its representation
Creates an
instance of several derived classes
A fully
initialized instance to be copied or cloned
A class of
which only a single instance can exist
Structural
Patterns
Match
interfaces of different classes
Separates
an object’s interface from its implementation
A tree
structure of simple and composite objects
Add
responsibilities to objects dynamically
A single
class that represents an entire subsystem
A
fine-grained instance used for efficient sharing
An object
representing another object
Behavioral
Patterns
A way of
passing a request between a chain of objects
Encapsulate
a command request as an object
A way to
include language elements in a program
Sequentially
access the elements of a collection
Defines
simplified communication between classes
Capture and
restore an object's internal state
A way of
notifying change to a number of classes
Alter an
object's behavior when its state changes
Encapsulates
an algorithm inside a class
Defer the
exact steps of an algorithm to a subclass
Defines a
new operation to a class without change
MVC :-
Design
patterns can help solve complex design problems if they are properly used. The
main advantage of using the Model-View-Control (MVC) pattern is decoupling the
business and the presentation layers.
The View pulls information from the Model and renders that information in
a way the user will understand.
The Controller interprets actions by the user, usually mouse and keyboard
events, and sends the information to the model or the view.
The model knows nothing about the view or the controller other than that
they exist. The view and the controller know as much as possible about the
model. The advantage to this type of architecture is that the view and the
controller may be changed without affecting the the model
VIEW:
View is the
graphical data presentation (outputting) irrespective of the real data
processing. View is the responsible for look and feel, some custom formatting,
sorting etc. View is completely isolated from actual complex data operations.
For example, Online product catalog view is completely separated from database
connection, query, tables etc. It simply gets final row-data from the model and
puts some cosmetics and formatting before displaying it in browser. View
provides interface to interact with the system. The beauty of MVC approach is
that it supports any kind of view, which is challenging in todays distributed
and multi-platform environment.
A MVC model can have multiple views, which are controlled by controller. View
interface can be of WEB-FORMS, HTML, XML/XSLT, XTML, and WML or can be Windows
forms etc.
MODEL:
Model is
responsible for actual data processing, like database connection, querying
database, implementing business rules etc. It feeds data to the view without
worrying about the actual formatting and look and feel. Data provided by Model
is display-neutral so it can be interfaced with as many views without code
redundancy; this eases your code maintenance and reduces bugs and allows code
-reuse at good extent. Model responds to the request made by controllers and
notifies the registered views to update their display with new data.
CONTROLLER:
Controller is
responsible for Notice of action. Controller responds to the mouse or keyboard
input to command model and view to change. Controllers are associated with
views. User interaction triggers the events to change the model, which in turn
calls some methods of model to update its state to notify other registered
views to refresh their display.
About
Collections
We can define a collection as a set
or group of related items or records that can be referred to as a unit. A
collection is a kind of data structure; that is a way of storing data in a
computer to be manipulated and used in the most efficient way. starts from the
base types data structures like primitive types (characters, integers,...),
passing by the composite types like (unions), we can finally reach the linear
types data structures like (arrays, linked lists, stacks, queues, hash tables,
...) which are the subject of our tutorial.
Generic
and Non-Generic Collections
In the .Net Framework 1.x most of
the collection classes store a data of type "System.Object", so you
can store any types of data in the collection object or many types in the same
collection object. This makes the addition of new items very easy, but when you
need to extract a stored data from the collection you will first need to cast
it back to its original data type. This cast had a performance impact
especially when you are going to deal with the stored data repeatedly. It slows
down your code plus making it less readable.
Dim List As New System.Collections.ArrayList
List.Add("ABab")
List.Add(123)
List.Add(10.3)
In the .Net Framework 2.0 the notion
of generic is introduced to avoid the problem of casting as a source of
performance drain and to allow the compiler to catch any try to store a
different type of data in the specified collection at design time.
Dim List As New System.Collections.Generic.List(Of String)
List.Add("Aa")
List.Add("Bb")
List.Add("Cc")
It is recommended to use generic
collections. The only reason you may need to use non-generic collections is for
legacy purposes or if you need your code to work with older versions of the
.Net Framework. If you need to store different types of data in a collection
you can still use generic collections, all what you need is to find a common
base between the stored data types. In the worst case you can use the
System.Object as the generic type parameter.
Dim List As New System.Collections.Generic.List(Of System.Object)
Types
of Collections in .NET
There are many types of collections
in the .Net Framework 2.0. The most general types of them are under the
"System.Collections" namespace. All of them have the following basic
methods and properties to manipulate the stored data. "Add" to add a
new element, "Remove" to remove an existing element, and
"Count" to get the total number of elements stored in a collection.
Non-Generic
Collections
Found under the
"System.Collections" namespace.
ArrayList: an array of contiguous indexed elements whose size can be
increased dynamically at run time as required. You can use this data structure
to store any types of data like integers, strings, structures, objects, .....
BitArray: an array of contiguous bit values (zeros and ones). Its
size must be determined at design time.
SortedList: represents a list of key/value pair elements, sorted by
keys and can be accessed by key and by index.
Stack: represents the data structure of last-in-first-out (LIFO).
Queue: represents the data structure of first-in-first-out (FIFO).
HashTable: represents a collection of key/value pair elements stored
based on the hash code of the key.
Generic
Collections
Found under the
"System.Collections.Generic" namespace.
LinkedList: represents a doubly linked list data structure of a
specified data type.
Dictionary: represents a collection of keys and values.
List: the generic counterpart of the ArrayList collection.
Queue: the generic counterpart of the non-generic Queue
collection.
Stack: the generic counterpart of the non-generic Stack
collection.
When
to Decide to Use a Collection?
Sometimes the answer is obvious,
sometimes it is not. A collection is used to tie certain items that have a
similar nature together in one set and refer to them as one group of data. As
an example, when you need to store some data about your customers, you can
obviously use a collection for this purpose. As a guideline you should use a
collection when you have more than one item that serve similar purposes and all
have the same importance, when the number of items are unknown at design time,
when you need to sort items, when you need to iterate through items, or when
you need to expose the items to a consumer that expects collection type.
Some
performance issues when working with collectins
The main purpose of collections is
to deal with a large number of items, and as the number of items increased the
performance of your application will be affected. To reduce the effect of the
number of items on your application you have to choose the right kind of
collection you will use. This depends on the usage patterns that are expected
from your collection. You have to decide whether you will insert all the items
in the collection only on initialization of your application, or you will do
that through out the life time of the application. How many times will you need
to iterate through the items of the collection. Will you need to insert new
items at the middle, or just add the new ones to the end of the collection. Is
it important to store your items in order or not, and so on. You have to decide
what is the key operation you need; is it iteration?, insertion, lookup, or
saving data in order. You can choose the right collection depending on the
usage pattern of data.
For example when your main concern
is lookups and you don't mind about the order of items, your first choice
should be System.Collections.Generic.Dictionary. that has a very fast lookups
plus quick additions and removals. The mentioned three operations operate
quickly even if the collection contains millions of items.
Dim Dic As New System.Collections.Generic.Dictionary_
(Of Integer,
String)
Dic.Add(12, "Aa")
Dic.Add(20, "Bb")
Dic.Add(100, "Cc")
Dim s As String = Dic.Item(20)
Dic.Remove(100)
If your usage is mostly addition and
a few deletions, and if it is important for the logic of your program to keep
items in order you will need to use the System.Collections.Generic.List
collection. In this situation lookup will be slow because the need to traverse
the entire list items to get the required one. Inserting items at the middle of
the collection or removing existing items will take a valuable amount of time too,
but adding items at the end will be very quick.
Dim L As New System.Collections.Generic.List(Of String)
L.Add("Aa")
L.Add("Bb")
L.Add("Dd")
L.Insert(2, "Cc")
L.Remove("Bb")
Serialization
Serialization
is the process of converting complex objects into stream of bytes for storage.
Deserialization is its reverse process, that is unpacking stream of bytes to
their original form.
The namespace which is used to read and write files is System.IO. For
Serialization we are going to look at the System.Runtime.Serialization namespace. The ISerializable interface
allows you to make any class Serializable.
Binary Serialization
Binary
serialization uses binary encoding to produce compact serialization for uses
such as storage or socket-based network streams.
XML Serialization
XML
serialization serializes the public fields and properties of an object, or the
parameters and return values of methods, into an XML stream that conforms to a
specific XML Schema definition language (XSD) document. XML serialization
results in strongly typed classes with public properties and fields that are
converted to XML. System.Xml.Serialization contains the classes
necessary for serializing and deserializing XML.
You
can apply attributes to classes and class members in order to control the way
the XmlSerializer serializes or deserializes an
instance of the class.
SOAP Serialization
XML
serialization can also be used to serialize objects into XML streams that
conform to the SOAP specification. SOAP is a protocol based on XML, designed
specifically to transport procedure calls using XML. As with regular XML
serialization, attributes can be used to control the literal-style SOAP
messages generated by an XML Web service
Serialize Example
For
serializing, lets open a stream object and give a sample file name EmployeeInfo.osl.
Note, the demo exe file has this same name. So when you run ObjSerial.exe, the
EmployeeInfo.osl file will be created under the folder where you copied the exe
file. Add the following code to our ObjSerial class. Once a stream is open we create
a BinaryFormatter and use the Serialize method to
serialize our object to the stream. What Serialize method would do? It converts our object
into binary format and streams it in.
Serialize
// Open a file and serialize the object into it in
binary format.
// EmployeeInfo.osl is the file that we are
creating.
// Note:- you can give any extension you want for
your file
// If you use custom extensions, then the user will
now
// that the
file is associated with your program.
Stream stream =
File.Open("EmployeeInfo.osl", FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter();
Console.WriteLine("Writing Employee
Information");
bformatter.Serialize(stream, mp);
stream.Close();
Deserialize
Now
we read the created file and cast the return value to our Employee class
for further usage. For reading we again create a BinaryFormatter to read the object in binary
form. We then use the Deserialize method which
converts the stream of bytes to an Object object. This object can then be easily
casted to our |
//Clear mp for further usage.
mp = null;
//Open the file written above and read values from
it.
stream = File.Open("EmployeeInfo.osl",
FileMode.Open);
bformatter = new BinaryFormatter();
Console.WriteLine("Reading Employee
Information");
mp = (Employee)bformatter.Deserialize(stream);
stream.Close();
Console.WriteLine("Employee Id:
{0}",mp.EmpId.ToString());
Console.WriteLine("Employee Name:
{0}",mp.EmpName);
Reflection
Reflection
provides objects (of type Type) that encapsulate assemblies, modules and
types. You can use reflection to dynamically create an instance of a type, bind
the type to an existing object, or get the type from an existing object and
invoke its methods or access its fields and properties. If you are using
attributes in your code, Reflection enables you to access them. For more
information, see Attributes.
Here's
a simple example of Reflection using the static method GetType -
inherited by all types from the Object base class - to obtain the type
of a variable:
//Using GetType to obtain type information:
int i = 42;
System.Type type = i.GetType();
System.Console.WriteLine(type);
The
output is:
System.Int32
In
this example, Reflection is used to obtain the full name of a loaded assembly:
// Using Reflection to get information from an
Assembly:
System.Reflection.Assembly o =
System.Reflection.Assembly.Load("mscorlib.dll");
System.Console.WriteLine(o.GetName());
The
output is:
mscorlib,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Reflection
Overview
Reflection
is useful in the following situations:
·
When
you need to access attributes in your program's metadata. See the topic Accessing Attributes With Reflection.
·
For
examining and instantiating types in an assembly.
·
For
building new types at runtime. Use classes in System.Reflection.Emit.
·
For
performing late binding, accessing methods on types created at run time. See
the topic Dynamically Loading and Using Types.
What is dll hell problem in .NET and how it
will solve?
Ans: Dll hell, is kind of conflict that occurred previously, due
to the lack of version supportability of dll for (within) an application
.NET Framework provides operating
system with a global assembly cache. This cache is a repository for all the
.net components that are shared globally on a particular machine. When a .net
component installed onto the machine, the global assembly cache looks at its
version, its public key and its language information and creates a strong name
for the component. The component is then registered in the repository and
indexed by its strong name, so there is no confusion between the different
versions of same component, or DLL
What is the cross page
post backing?
Asp.Net 2.0 fixed this with built-in
features that allowed us to easily send information from one page to another.
Method -1
Button control has property PostBackUrl that can be set to URL of any
page in our ASP.Net WebSite where we want to transfer all form values to.
Along with that Asp.Net 2.0 Page class has a property PreviousPage that
allows us to get reference to the Page object that initiated the postback (in
other words to get the actual reference to the Page object of the aspx page on
which user clicked the Submit button on a HTML form).
So for example lets create two sample pages in our Web Application:
Run time Polymorphism
In runtime polymorphism ... the code is called at run time according to need or given conditions.
suppose there r two methods namely Add() one in super class and other is in sub class.both have the same name and same parameters.
so we have to choose that which method from them shld called at run time i.e. of super class or of sub class.by polymorphism we do that.
ex:-
class A
{
int add(){//code of the method}
//some other code
}
class B extends A
{
int add(){//code of the method}
//some other code
}
class AB
{
public static void main(String s[])
{
A ob1;
ob1=new A();
int i=ob1.add();//will call the method of super class.
ob1=new B();// sub class's reference can be assigned to super class address but not vice versa.to do that we have to type cast the reference of the sub class in reference of the super class.
int j=ob1.add();//will call the method of sub class
}
}
What is run time polymorpism and complie time polymmorpism
Overloading is compile time polymorphism because compiler checkes the method sigantures while compiling itself.(i. e: Method names Argument types argument creation order etc...)
Overriding is run time polymorphism.
compile time polymorphism -- method overloding
run time time polymorphism -- method overriding
Overloading is compile time polymorphism also called early binding.
Overriding is runtime polymorphism also called late binding.
compile time polymorpism also known as staic poly
run time polymorpism also known as dynamic polymorpism
example for static poly is method overloading
example for dynamic poly is method overriding
static poly is linking method call at the time of compilation time
dynamic poly is linking method call at the time of runing time
What is the difference between a while statement and a do statement
A while statement checks at the beginning of a loop to
see whether the next loop iteration should occur. A do statement checks at the
end of a loop to see whether the next iteration of a loop should occur.
Difference between Arraylist and Generic List
Arraylist –
Arraylist accept values as object
So We can give any type of data in to that.
Here in this eg: an arraylist object accepting
values like String,int,decimal, char and a custom object
ArrayList arr = new ArrayList();
arr.Add("Sabu");
arr.Add(234);
arr.Add(45.236);
arr.Add(emp);
arr.Add('s');
This process is known as boxing
Geniric type :-
Main advantage of Generic List is we can specify the type of data
List<int> intLst = new List<int>();
intLst.Add(12);
Here List accepting values as int only
List<Employee> empLst = new List<Employee>();
empLst.Add(new Employee("1", "Sabu"));
Here List accepting Employee Objects only
è If
constructor is private then we can not create the object and inherit of that
class.
-> Sealed can not be used for virtual, Abstract and static classes.
Non - Generic collection class - which collection can hold
the different type of data.Generic collection class - which collection can hold the same type of data.
ASP.NET provides multiple simple solutions to this problems like:
1- Viewstate
2- Session Variables
3- Application Variables
4- Cache
5- Cookies
Now the question arises that when to use what?
1- Viewstate
Viewstate is a hidden fields in an ASP.NET page, contains state of those controls on a page whose “EnableViewstate” property is “true”.
You can also explicitly add values in it, on an ASP.NET page like:
Viewstate.Add( “TotalStudents”, “87″ );
Viewstate should be used when you want to save a value between diferent roundtrips of a single page as viewstate of a page is not accessible by another page.
Because Viewstate renders with the page, it consumes bandwith, so be careful to use it in applications to be run on low bandwith.
2- Session Variable
Session variables are usually the most commonly used.
When a user visits a site, it’s sessions starts and when the user become idle or leave the site, the session ends.
Session variables should be used to save and retrive user specefic information required on multiple pages.
Session variables consumes server memory, so if your may have a huge amount visiters, use session very carefully and instead of put large values in it try to put IDs and references
3- Application variables
Application variables are shared variables among all users of a web application
Application variables behave like static variables and they are substitute of static variables as static variables are stateless in web applications
Only shared values should be persisted in Application variables, and as soon as they are not in use they should be removed explicitly.
4- Cache
Cache is probably the least used state feature of ASP.NET.
Cache is basically a resource specific state persistence feature, means unlike session it stick with resource instead of user, for instance: pages, controls etc.
Cache should be used or frequently used pages, controls, and data structures
Data cache can be used to cache frequently used list of values e.g. list of products
6- Cookies
Cookies are some values saved in browsers for a particular website o publicly accessible
The purpose of cookies is to help websites to identify visitors and retrieve their saved preferences
Cookies are also used to facilitate auto login by persisting user id in a cookie save in user’s browser
Because cookies have been saved at client side, they do not create performance issues but may create security issues as they can be hacked from browser
Finally remember the following points on your finger-tips:
1- Viewstate is bandwidth hungry
2- Session variables are memory hungry as per number of users
3- Applications variables are shared
4- Cache is memory hungry as per number of resources
5- Cookies are the least secure
What is the intrinsic difference between COOKIES AND CACHE?
cookies are small bits of files that store your session, and other small data, its pretty much like a database in a sense...
while
a cache is temporary storage for files used by a program(typically a browser)
to display items.... and to get a quick access to pre-parsed files.....
your browser has to store the webpage, and all pictures, video flash and those
things on the cache so that it could display it
while cookies, store only text based data about your browsing stuff.. like
passwords, number of pages visited, session number, and so on.....
Design Pattern :-
Design Pattern is a re-usable, high quality solution to a given requirement, task or recurring problem. it provides a framework for how to solve a problem.
Design Patterns are categorized into 3 types: Creational Patterns Structural Patterns Behavioral Patterns
Creational Patterns
|
|
Creates an
instance of several families of classes
|
|
Separates
object construction from its representation
|
|
Creates an
instance of several derived classes
|
|
A fully
initialized instance to be copied or cloned
|
|
A class of
which only a single instance can exist
|
Structural
Patterns
|
|
Match
interfaces of different classes
|
|
Separates
an object’s interface from its implementation
|
|
A tree
structure of simple and composite objects
|
|
Add
responsibilities to objects dynamically
|
|
A single
class that represents an entire subsystem
|
|
A
fine-grained instance used for efficient sharing
|
|
An object
representing another object
|
Behavioral
Patterns
|
|
A way of
passing a request between a chain of objects
|
|
Encapsulate
a command request as an object
|
|
A way to
include language elements in a program
|
|
Sequentially
access the elements of a collection
|
|
Defines
simplified communication between classes
|
|
Capture and
restore an object's internal state
|
|
A way of
notifying change to a number of classes
|
|
Alter an
object's behavior when its state changes
|
|
Encapsulates
an algorithm inside a class
|
|
Defer the
exact steps of an algorithm to a subclass
|
|
Defines a
new operation to a class without change
|
MVC :-
Design patterns can help solve complex design problems if they are properly used. The main advantage of using the Model-View-Control (MVC) pattern is decoupling the business and the presentation layers.
The View pulls information from the Model and renders that information in a way the user will understand.
The Controller interprets actions by the user, usually mouse and keyboard events, and sends the information to the model or the view.
The model knows nothing about the view or the controller other than that they exist. The view and the controller know as much as possible about the model. The advantage to this type of architecture is that the view and the controller may be changed without affecting the the model
VIEW:
View is the
graphical data presentation (outputting) irrespective of the real data
processing. View is the responsible for look and feel, some custom formatting,
sorting etc. View is completely isolated from actual complex data operations.
For example, Online product catalog view is completely separated from database
connection, query, tables etc. It simply gets final row-data from the model and
puts some cosmetics and formatting before displaying it in browser. View
provides interface to interact with the system. The beauty of MVC approach is
that it supports any kind of view, which is challenging in todays distributed
and multi-platform environment.
A MVC model can have multiple views, which are controlled by controller. View interface can be of WEB-FORMS, HTML, XML/XSLT, XTML, and WML or can be Windows forms etc.
MODEL:
A MVC model can have multiple views, which are controlled by controller. View interface can be of WEB-FORMS, HTML, XML/XSLT, XTML, and WML or can be Windows forms etc.
MODEL:
Model is
responsible for actual data processing, like database connection, querying
database, implementing business rules etc. It feeds data to the view without
worrying about the actual formatting and look and feel. Data provided by Model
is display-neutral so it can be interfaced with as many views without code
redundancy; this eases your code maintenance and reduces bugs and allows code
-reuse at good extent. Model responds to the request made by controllers and
notifies the registered views to update their display with new data.
CONTROLLER:
CONTROLLER:
Controller is
responsible for Notice of action. Controller responds to the mouse or keyboard
input to command model and view to change. Controllers are associated with
views. User interaction triggers the events to change the model, which in turn
calls some methods of model to update its state to notify other registered
views to refresh their display.
About
Collections
We can define a collection as a set
or group of related items or records that can be referred to as a unit. A
collection is a kind of data structure; that is a way of storing data in a
computer to be manipulated and used in the most efficient way. starts from the
base types data structures like primitive types (characters, integers,...),
passing by the composite types like (unions), we can finally reach the linear
types data structures like (arrays, linked lists, stacks, queues, hash tables,
...) which are the subject of our tutorial.
Generic
and Non-Generic Collections
In the .Net Framework 1.x most of
the collection classes store a data of type "System.Object", so you
can store any types of data in the collection object or many types in the same
collection object. This makes the addition of new items very easy, but when you
need to extract a stored data from the collection you will first need to cast
it back to its original data type. This cast had a performance impact
especially when you are going to deal with the stored data repeatedly. It slows
down your code plus making it less readable.
Dim List As New System.Collections.ArrayList
List.Add("ABab")
List.Add(123)
List.Add(10.3)
List.Add("ABab")
List.Add(123)
List.Add(10.3)
In the .Net Framework 2.0 the notion
of generic is introduced to avoid the problem of casting as a source of
performance drain and to allow the compiler to catch any try to store a
different type of data in the specified collection at design time.
Dim List As New System.Collections.Generic.List(Of String)
List.Add("Aa")
List.Add("Bb")
List.Add("Cc")
List.Add("Aa")
List.Add("Bb")
List.Add("Cc")
It is recommended to use generic
collections. The only reason you may need to use non-generic collections is for
legacy purposes or if you need your code to work with older versions of the
.Net Framework. If you need to store different types of data in a collection
you can still use generic collections, all what you need is to find a common
base between the stored data types. In the worst case you can use the
System.Object as the generic type parameter.
Dim List As New System.Collections.Generic.List(Of System.Object)
Types
of Collections in .NET
There are many types of collections
in the .Net Framework 2.0. The most general types of them are under the
"System.Collections" namespace. All of them have the following basic
methods and properties to manipulate the stored data. "Add" to add a
new element, "Remove" to remove an existing element, and
"Count" to get the total number of elements stored in a collection.
Non-Generic
Collections
Found under the
"System.Collections" namespace.
ArrayList: an array of contiguous indexed elements whose size can be
increased dynamically at run time as required. You can use this data structure
to store any types of data like integers, strings, structures, objects, .....
BitArray: an array of contiguous bit values (zeros and ones). Its
size must be determined at design time.
SortedList: represents a list of key/value pair elements, sorted by
keys and can be accessed by key and by index.
Stack: represents the data structure of last-in-first-out (LIFO).
Queue: represents the data structure of first-in-first-out (FIFO).
HashTable: represents a collection of key/value pair elements stored
based on the hash code of the key.
Generic
Collections
Found under the
"System.Collections.Generic" namespace.
LinkedList: represents a doubly linked list data structure of a
specified data type.
Dictionary: represents a collection of keys and values.
List: the generic counterpart of the ArrayList collection.
Queue: the generic counterpart of the non-generic Queue
collection.
Stack: the generic counterpart of the non-generic Stack
collection.
When
to Decide to Use a Collection?
Sometimes the answer is obvious,
sometimes it is not. A collection is used to tie certain items that have a
similar nature together in one set and refer to them as one group of data. As
an example, when you need to store some data about your customers, you can
obviously use a collection for this purpose. As a guideline you should use a
collection when you have more than one item that serve similar purposes and all
have the same importance, when the number of items are unknown at design time,
when you need to sort items, when you need to iterate through items, or when
you need to expose the items to a consumer that expects collection type.
Some
performance issues when working with collectins
The main purpose of collections is
to deal with a large number of items, and as the number of items increased the
performance of your application will be affected. To reduce the effect of the
number of items on your application you have to choose the right kind of
collection you will use. This depends on the usage patterns that are expected
from your collection. You have to decide whether you will insert all the items
in the collection only on initialization of your application, or you will do
that through out the life time of the application. How many times will you need
to iterate through the items of the collection. Will you need to insert new
items at the middle, or just add the new ones to the end of the collection. Is
it important to store your items in order or not, and so on. You have to decide
what is the key operation you need; is it iteration?, insertion, lookup, or
saving data in order. You can choose the right collection depending on the
usage pattern of data.
For example when your main concern
is lookups and you don't mind about the order of items, your first choice
should be System.Collections.Generic.Dictionary. that has a very fast lookups
plus quick additions and removals. The mentioned three operations operate
quickly even if the collection contains millions of items.
Dim Dic As New System.Collections.Generic.Dictionary_
(Of Integer, String)
Dic.Add(12, "Aa")
Dic.Add(20, "Bb")
Dic.Add(100, "Cc")
Dim s As String = Dic.Item(20)
Dic.Remove(100)
(Of Integer, String)
Dic.Add(12, "Aa")
Dic.Add(20, "Bb")
Dic.Add(100, "Cc")
Dim s As String = Dic.Item(20)
Dic.Remove(100)
If your usage is mostly addition and
a few deletions, and if it is important for the logic of your program to keep
items in order you will need to use the System.Collections.Generic.List
collection. In this situation lookup will be slow because the need to traverse
the entire list items to get the required one. Inserting items at the middle of
the collection or removing existing items will take a valuable amount of time too,
but adding items at the end will be very quick.
Dim L As New System.Collections.Generic.List(Of String)
L.Add("Aa")
L.Add("Bb")
L.Add("Dd")
L.Insert(2, "Cc")
L.Remove("Bb")
L.Add("Aa")
L.Add("Bb")
L.Add("Dd")
L.Insert(2, "Cc")
L.Remove("Bb")
Serialization
Serialization
is the process of converting complex objects into stream of bytes for storage.
Deserialization is its reverse process, that is unpacking stream of bytes to
their original form.
The namespace which is used to read and write files is System.IO. For
Serialization we are going to look at the System.Runtime.Serialization namespace. The ISerializable interface
allows you to make any class Serializable.
Binary Serialization
Binary
serialization uses binary encoding to produce compact serialization for uses
such as storage or socket-based network streams.
XML Serialization
XML
serialization serializes the public fields and properties of an object, or the
parameters and return values of methods, into an XML stream that conforms to a
specific XML Schema definition language (XSD) document. XML serialization
results in strongly typed classes with public properties and fields that are
converted to XML. System.Xml.Serialization contains the classes
necessary for serializing and deserializing XML.
You
can apply attributes to classes and class members in order to control the way
the XmlSerializer serializes or deserializes an
instance of the class.
SOAP Serialization
XML
serialization can also be used to serialize objects into XML streams that
conform to the SOAP specification. SOAP is a protocol based on XML, designed
specifically to transport procedure calls using XML. As with regular XML
serialization, attributes can be used to control the literal-style SOAP
messages generated by an XML Web service
Serialize Example
For
serializing, lets open a stream object and give a sample file name EmployeeInfo.osl.
Note, the demo exe file has this same name. So when you run ObjSerial.exe, the
EmployeeInfo.osl file will be created under the folder where you copied the exe
file. Add the following code to our ObjSerial class. Once a stream is open we create
a BinaryFormatter and use the Serialize method to
serialize our object to the stream. What Serialize method would do? It converts our object
into binary format and streams it in.
Serialize
// Open a file and serialize the object into it in binary format.
Serialize
// Open a file and serialize the object into it in binary format.
// EmployeeInfo.osl is the file that we are
creating.
// Note:- you can give any extension you want for
your file
// If you use custom extensions, then the user will
now
// that the
file is associated with your program.
Stream stream =
File.Open("EmployeeInfo.osl", FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter();
Console.WriteLine("Writing Employee
Information");
bformatter.Serialize(stream, mp);
stream.Close();
Deserialize
Now
we read the created file and cast the return value to our Employee class
for further usage. For reading we again create a BinaryFormatter to read the object in binary
form. We then use the Deserialize method which
converts the stream of bytes to an Object object. This object can then be easily
casted to our |
//Clear mp for further usage.
mp = null;
//Open the file written above and read values from
it.
stream = File.Open("EmployeeInfo.osl",
FileMode.Open);
bformatter = new BinaryFormatter();
Console.WriteLine("Reading Employee
Information");
mp = (Employee)bformatter.Deserialize(stream);
stream.Close();
Console.WriteLine("Employee Id:
{0}",mp.EmpId.ToString());
Console.WriteLine("Employee Name:
{0}",mp.EmpName);
Reflection
Reflection
provides objects (of type Type) that encapsulate assemblies, modules and
types. You can use reflection to dynamically create an instance of a type, bind
the type to an existing object, or get the type from an existing object and
invoke its methods or access its fields and properties. If you are using
attributes in your code, Reflection enables you to access them. For more
information, see Attributes.
Here's
a simple example of Reflection using the static method GetType -
inherited by all types from the Object base class - to obtain the type
of a variable:
//Using GetType to obtain type information:
int i = 42;
System.Type type = i.GetType();
System.Console.WriteLine(type);
The
output is:
System.Int32
In
this example, Reflection is used to obtain the full name of a loaded assembly:
// Using Reflection to get information from an
Assembly:
System.Reflection.Assembly o =
System.Reflection.Assembly.Load("mscorlib.dll");
System.Console.WriteLine(o.GetName());
The
output is:
mscorlib,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Reflection
Overview
Reflection
is useful in the following situations:
·
When
you need to access attributes in your program's metadata. See the topic Accessing Attributes With Reflection.
·
For
examining and instantiating types in an assembly.
·
For
building new types at runtime. Use classes in System.Reflection.Emit.
·
For
performing late binding, accessing methods on types created at run time. See
the topic Dynamically Loading and Using Types.
What is dll hell problem in .NET and how it will solve?
Ans: Dll hell, is kind of conflict that occurred previously, due
to the lack of version supportability of dll for (within) an application
.NET Framework provides operating
system with a global assembly cache. This cache is a repository for all the
.net components that are shared globally on a particular machine. When a .net
component installed onto the machine, the global assembly cache looks at its
version, its public key and its language information and creates a strong name
for the component. The component is then registered in the repository and
indexed by its strong name, so there is no confusion between the different
versions of same component, or DLL
What is the cross page post backing?
Along with that Asp.Net 2.0 Page class has a property PreviousPage that allows us to get reference to the Page object that initiated the postback (in other words to get the actual reference to the Page object of the aspx page on which user clicked the Submit button on a HTML form).
So for example lets create two sample pages in our Web Application:
- SourcePage.aspx
- DestinationPage.aspx
In SoucePage in Html form we will
put two TextBox controls (one for First Name and one for Last Name) and one
Button component and set its PostBackUrl property to
"~/DestinationPage.aspx".
SourcePage.aspx:
<form id="form1" runat="server">
<div>
First Name: <asp:TextBox ID="FirstName" runat="server"></asp:TextBox><br />
Last Name: <asp:TextBox ID="LastName" runat="server"></asp:TextBox><br /><br />
<asp:Button ID="Button1" runat="server" Text="Submit To Destination Page" PostBackUrl="~/CrossPagePostbacks/DestinationPage.aspx" />
</div>
</form>
When our user clicks the Submit button, all the values from the HTML Form on
SourcePage.aspx will be transfered to the DestinationPage.aspx and we will also
be able to get reference to the SourcePage.aspx in our DestinationPage with the
PreviousPage property like this:
So in our DestinationPage.aspx.cs code-behind we can easily access two TextBox
controls on SourcePage.aspx and show them in two label controls like this:
protected void Page_Load(object sender, EventArgs e)
{
// first check if we had
a cross page postback
if ( (PreviousPage != null) && (PreviousPage.IsCrossPagePostBack) )
{
Page previousPage =
PreviousPage;
TextBox firstName = (TextBox)previousPage.FindControl("FirstName");
TextBox lastName = (TextBox)previousPage.FindControl("LastName");
// we can now use the values from TextBoxes and display them in
two Label controls..
labelFirstName.Text = firstName.Text;
labelLastName.Text = lastName.Text;
}
}
You probably noticed that we first checked if PreviousPage property of
current page (DestinationPage.aspx) is NOT NULL, this is done to avoid
running our code in case that user opens our DestinationPage.aspx directly,
without running a cross page postback.
Also here we checked the another PreviousPage property called IsCrossPagePostBack
to see if we really had a CrossPagePostback.
(If Server.Transfer is used to redirect to this page, IsCrossPagePostBack
property will be set to FALSE.
TIP: We can be completely sure that we have
a real CrossPagePostback ONLY IF:
- Page.PreviousPage is
NOT NULL,
- PreviousPage.IsCrossPagePostback is true
This important to check to avoid
errors in code.
Now this is very useful and i'm sure you are eager to use this in your next
project. But wait, we are not over yet!
Finding the controls on PreviousPage with FindControl method and type-casting
them from object to their real type is a little messy.
It feels like there must be a better solution for this!
Method - 2
And here it is: We can use the <%@ PreviousPageType %> directive
in the header of our DestinationPage.aspx like this
<%@ PreviousPageType VirtualPath="~/SourcePage.aspx" %>
to declare our previous page type,
and then we can access Public properties of the PreviousPage without
typecasting.
Now all we need to do is to create some public properties on our
SourcePage.aspx.cs to expose data/Controls we want to the destionation page:
public partial class SourcePage : System.Web.UI.Page
{
public string FormFirstName
{
get { return FirstName.Text; }
}
public string FormLastName
{
get { return LastName.Text; }
}
}
And then we can change the Page_Load code in our DestinationPage.aspx to much
cleaner code like this:
protected void Page_Load(object sender, EventArgs e)
{
// first check if we had
a cross page postback
if ( (PreviousPage != null) && (PreviousPage.IsCrossPagePostBack) )
{
SourcePage prevPage =
PreviousPage;
// we can now use the values from textboxes and display them in
two Label controls..
labelFirstName.Text =
prevPage.FormFirstName;
labelLastName.Text =
prevPage.FormLastName;
}
}
SourcePage.aspx:
When our user clicks the Submit button, all the values from the HTML Form on SourcePage.aspx will be transfered to the DestinationPage.aspx and we will also be able to get reference to the SourcePage.aspx in our DestinationPage with the PreviousPage property like this:
So in our DestinationPage.aspx.cs code-behind we can easily access two TextBox controls on SourcePage.aspx and show them in two label controls like this:
You probably noticed that we first checked if PreviousPage property of current page (DestinationPage.aspx) is NOT NULL, this is done to avoid running our code in case that user opens our DestinationPage.aspx directly, without running a cross page postback.
Also here we checked the another PreviousPage property called IsCrossPagePostBack to see if we really had a CrossPagePostback.
(If Server.Transfer is used to redirect to this page, IsCrossPagePostBack property will be set to FALSE.
TIP: We can be completely sure that we have a real CrossPagePostback ONLY IF:
Now this is very useful and i'm sure you are eager to use this in your next project. But wait, we are not over yet!
Finding the controls on PreviousPage with FindControl method and type-casting them from object to their real type is a little messy.
It feels like there must be a better solution for this!
And here it is: We can use the <%@ PreviousPageType %> directive in the header of our DestinationPage.aspx like this
Now all we need to do is to create some public properties on our SourcePage.aspx.cs to expose data/Controls we want to the destionation page:
And then we can change the Page_Load code in our DestinationPage.aspx to much cleaner code like this:
Q43. What are Partial Classes in Asp.Net 2.0?
Ans. In .NET 2.0, a class definition may be split into multiple physical files
but partial classes do not make any difference to the compiler as during
compile time, the compiler groups all the partial classes and treats them as a
single class.
Q46. What is Boxing and Unboxing?
Ans. Boxing is the process where any value type can be implicitly converted to
a reference type object while Unboxing is the opposite of boxing process where
the reference type is converted to a value type. Q47. What is Code Access security? What is CAS in .NET?
very informative blog and useful article thank you for sharing with us , keep
ReplyDeleteposting
Dot NET Online Course Hyderabad