Pre Preparation Dot Net Interview Spot
Now we’ll have a close look to above terminologies one by one. We will start from IL code.
static void main()
ASP.NET allows us
to save values using application state. A global storage mechanism that is
accessible from all pages in the Web application. Application state is stored
in the Application key/value dictionary. This information will also be
available to all the users of the website. In case we need user specific
information, then we better use
The HTTP Pipeline handles all processes involved in converting all of the application code into HTML to be interpreted by the browser.
The first class initiated is called HttpRuntime. This class finds a free HttpApplication object to start processing the request. The HttpApplication object then runs the appropriate handler assigned in the web.config and machine.config files for the requested extension.
The extension .aspx can be handled by the HandlerClass or HandlerFactory class. The HttpApplication objects starts the IHttpHandler interface which begins processing the application code by calling the processRequest() method.
The processRequest() method then calls the FrameworkInitialize() method which begins building the control trees for the requested page.
(You can see the Control tree of any aspx page by giving Trace="true" in Page Directive)
Request(.aspx) --> IIS --> HTTPPipeLine --> HttpRuntime -->HttpApplication -->Handler(HandlerClass/HandlerFactory) --> Process Application by processRequest() -->
FrameworkInitialize()
Now the processRequest() method cycles through the page’s life cycle in the order listed below.
Following are the page life cycle events:
Short Forms:
PreIn->In->Incomp
LoadVstate->LoadPostData
PreLoad->Load->Loadcomplete
PreRender->PreRendComplete->SaveStatecomplete
UnLoad
Now Let Us Come to Programming Stuff- How to Handle Above Events:
Below is the Code where I handled each event Try and Enjoy...
StringBuilder sb = new StringBuilder();
protected void Page_PreInit(object o, EventArgs e)
{
sb.Append("<b>Page Pre_Init</b> - Occurs at the begining of the Page Initialization <br />");
}
protected void Page_Init(object sender, EventArgs e)
{
sb.Append("<b>Page Init </b>- Occurs when the Server Control is Initialized. It is the first step in the ASP.NET Page Life Cycle <br />");
}
public void Page_InitComplete(object sender, EventArgs e)
{
sb.Append("<b>Page Init Complete </b>- Occurs when the Page Initialization is Complete <br />");
}
public void Page_PreLoad(object sender, EventArgs e)
{
sb.Append("<b>Page Pre Load </b>- Occurs before the Load Event <br />");
}
protected void Page_Load(object sender, EventArgs e)
{
sb.Append("<b>Page Load </b>- Occurs when the Server Control is Loaded in the Page Object <br />");
}
void Page_LoadComplete(object sender, EventArgs e)
{
sb.Append("<b>Page Load Complete </b>- Occurs at the end of Load Stage of the Page Life Cycle. <br />");
}
void Page_PreRender(object sender, EventArgs e)
{
sb.Append("<b>Page Pre Render </b>- Occurs after the Server Controls is Loaded in the Page but before the Rendering</div> <br />");
}
void Page_PreRenderComplete(object sender, EventArgs e)
{
sb.Append("<b>Page Pre Render Complete </b>- Occurs before the Page Content is Rendered <br />");
Response.Write(sb.ToString());
}
/// This is the event when the page is unloaded from the server memory and ready to be returned to the client,
/// Here the response is not available, so you cannot modify the Response
void Page_Unload(object sender, EventArgs e)
{
}
Lists
Lists allow duplicate items, can be accessed by index, and support linear traversal.
Hashes
Hashes are look-ups in which you give each item in a list a "key" which will be used to retrieve it later. Think of a hash like a table index where you can ask questions like "I'm going to find this object by this string value. Duplicate keys are not allowed.
Queues
Queues controls how items in a list are accessed. You typically push/pop records from a queue in a particular direction (from either the front or back). Not used for random access in the middle.
In the below code, the derived class constructor - 'PartyAccount' receives the values first and which are then passed to the base class constructor.
Example2:
using System;
using System.Collections.Generic;
namespace NS_HRapplication
{
//declare a base Class...
class CL_employees
{
public void FN_displaySalary()
{
Console.WriteLine("Salary is 1000 euro...");
}
}
//create a derived Class and inherit base Class...
class CL_tehnicians : CL_employees
{
public void FN_displaySalary()
{
//we assume that managers are getting paid 1000 euro extra
than base employee salary...
base.FN_displaySalary();
}
}
class CL_x
{
static void Main(string [] args)
{
//create a technician instance-object
CL_tehnicians o_aTechnician = new CL_tehnicians();
//display salary...
o_aTechnician.FN_displaySalary();
Output:
Salary is 1000 euro..
Note : The 'MyBase' keyword in vb.net is the counterpart for the 'base' keyword in c#.
if you have worked on c# & vb.net then I would suggest you to refresh the differences between them,
clear differences has been explained very nice here
After a deep analysis
I have gathered very important basic interview point of & developer basic
understanding point of stuff for .NET. Just go step by step and later you can
prepare for other things but according to me without having below concepts
there will be no escape.
Below I have covered
.NET basics, OOP’s, State Management, Life Cycle, Constructor& Destructors,
Interfaces, Abstract Classes Differences, Real Time Usage, Programming
Examples,Collections,Datastructure,.NET Framework version difference,base keyword & more.
.Net
framework:
It is a software framework developed by
Microsoft that runs under Microsoft Windows. It includes large library and
provides language interoperability (i.e. each language code can be written in
another languages) across several programming languages.
Class Library and CLR(common language
run time) constitute the .NET framework.
BCL & FCL Explanation & Difference:
The Base Class Library (BCL)
is literally that, a subset of FCL or the core set of classes that
serve as the basic API of the Common Language Runtime. The classes inmscorlib.dll and
some of the classes in System.dll andSystem.core.dll are
considered to be a part of the BCL.
It includes the
classes in namespaces like
System ,System.Diagnostics
System.Globalization
System.Resources
System.Text
System.Runtime.Serialization
System.Data etc.
The Framework Class Library (FCL) is a superset of the BCL classes
and refers to the entire class library that ships with .NET Framework. It includes an expanded set of libraries, including Windows Forms,ADO.net, ASP.net, Language Integrated Query,
Windows Presentation Foundation (WPF), Windows Communication Foundation
(WCF) among others.
Brief Introduction to IL code, CLR, CTS, CLS and JIT In .NET:
Before explaining
these terminologies, I would like to explain how .NET code gets compiled.
The developer writes source code in any .NET language i.e. it may VB.NET or C#
or VC+++.NET, etc. The source code is compiled to Intermediate code known
as IL code by the respective compilers for example for C# it is csc.exe
compiler, for VB.NET it is vbc.exe compiler, etc. This half compiled code
is then given to JIT(just in time compiler) by CLR which converts IL code to
machine specific instructions which then gets executed. In this way a .NET code
gets compiled. For better understanding have a look to following diagram :
Now we’ll have a close look to above terminologies one by one. We will start from IL code.
·
IL Code: The word IL Code stands for
Intermediate Language Code. It is a CPU independent partially compiled code.
When we develop our .NET application, we don’t know in what kind of
environment our code will run i.e. on which operating system it will be finally
hosted, what will be the CPU configuration, etc. So for this purpose we have IL
code which is compiled according to machine configuration. IL code is given by
Language compiler which is different for different languages for example
csc.exe compiler for C#, vbc.exe compiler for VB.NET, etc.
·
CLR: CLR stands for Common Language Runtime. It is the heart
of our .NET Framework. CLR performs following tasks :
1. Garbage Collection: When we run our .NET application, many
objects are created. Garbage collection is a background process which deletes
the objects which are not in use by the application and frees memory.
2. Code Access Security (CAS) and Code Verification
(CV): CLR checks the
whether the code has access rights and it is safe and authenticated to be used.
3. IL to Native Translation: The main task of CLR is to provide IL
code to JIT to ensure that code is fully compiled as per machine specification.
·
CTS: CTS stands for Common Types System. In .NET we have
various languages like C#, VB.NET, etc. There may be many situations where we
want code written in one language to be used in another. In order to ensure
that we have a smooth communication between different languages, we have CTS.
CTS ensure that data types defined in two different languages get compiled to a
common data type so that code written in one language can be used by another.
Common Type System (CTS)
It describes set of data types that can be used in different .Net languages in common. (i.e), CTS ensures 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.
The common type system supports two general categories of types:
Value types:
Value types directly contain their data, and instances of value types are either allocated on the stack or allocated inline in a structure. Value types can be built-in (implemented by the runtime), user-defined, or enumerations.
It describes set of data types that can be used in different .Net languages in common. (i.e), CTS ensures 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.
The common type system supports two general categories of types:
Value types:
Value types directly contain their data, and instances of value types are either allocated on the stack or allocated inline in a structure. Value types can be built-in (implemented by the runtime), user-defined, or enumerations.
Ex: Boolean, char, Enumerations,
since their underlying type is always SByte, Short, Integer, Long, Byte,
UShort, UInteger, or ULong
Reference types:
Reference types store a reference to the value's memory address, and are allocated on the heap. Reference types can be self-describing types, pointer types, or interface types. The type of a reference type can be determined from values of self-describing types. Self-describing types are further split into arrays and class types. The class types are user-defined classes, boxed value types, and delegates.
Reference types:
Reference types store a reference to the value's memory address, and are allocated on the heap. Reference types can be self-describing types, pointer types, or interface types. The type of a reference type can be determined from values of self-describing types. Self-describing types are further split into arrays and class types. The class types are user-defined classes, boxed value types, and delegates.
Ex: String, arrays,
Class types (such as Form), Delegates
·
CLS: CLS stands for Common Language Specifications. It is a
subset of CTS. CLS is a set of rules or guidelines which if followed ensures
that code written in one .NET language can be used by another .NET language.
For example one rule is that we cannot have member functions with same name
with case difference only i.e. we should not have add() and Add(). This may
work in C# because it is case-sensitive but if try to use that C# code in VB.NET
it is not possible because VB.NET is not case-sensitive.
·
JIT: JIT stands for Just In Timer Compiler. It is the
internal compiler of .NET which takes IL code from CLR and executes it to
machine specific instructions.
Assemblies
in .NET
An assembly is a "unit of deployment"
for .NET, it can be either .exe or .dll. Assemblies are the building
blocks of .NET Framework applications. In other words, you can say that an
assembly is a set of one or more modules and classes compiled in MSIL, and
metadata that describes the assembly itself, as well as the functionalities of
the assembly classes.
The
following are the two types of assemblies:
- Private Assembly - Refers to the assembly that is used by a single application. Private assemblies are kept in a local folder in which the client application has been installed.
- Public or Shared Assembly - Refers to the assembly that is allowed to be shared by multiple applications. A shared assembly must reside in Global Assembly Cache (GAC) with a strong name assigned to it.
For example, imagine that you have created a DLL containing
information about your business logic. This DLL can be used by your client
application. In order to run the client application, the DLL must be included
in the same folder in which the client application has been installed. This
makes the assembly private to your application. Now suppose that the DLL needs
to be reused in different applications. Therefore, instead of copying the DLL
in every client application folder, it can be placed in the global assembly cache
using the GAC tool. These assemblies are called shared assemblies.
Here you
must know how to put assembly in GAC, look here
The another assembly is Satellite assemble è
Satellite Assembly: A definition from MSDN says something
like this: "A .NET Framework assembly containing resources specific to a
given language. Using satellite assemblies, you can place the resources for
different languages in different assemblies, and the correct assembly is loaded
into memory only if the user elects to view the application in that
language."
This means that you develop your application in a default language
and add flexibility to react with change in the locale. Say, for example, you
developed your application in an en-US locale. Now, your application has
multilingual support. When you deploy your code in, say, India, you want to
show labels, messages shown in the national language which is other than
English.
Satellite assemblies give this flexibility. You create any simple
text file with translated strings, create resources, and put them into the
bin\debug folder. That's it. The next time, your code will read the
CurrentCulture property of the current thread and accordingly load the
appropriate resource.
Also glance on Ngen.exe è
The Native Image Generator (Ngen.exe)
is a tool that creates a native image from an assembly and stores that image to
native image cache on the computer. Whenever, an assembly is run, this native
image is automatically used to compile the original assembly. In this way, this
tool improves the performance of the managed application by loading and
executing an assembly faster.
OOP’s Main concepts:
Any how will
expose main points below è
Class:
A class is simply
a representation of a type of object. It
is the blueprint/ plan/ template that describe the details of an object.
Object:
In OOPs terms an object is an
instance of a class, object doses related activities defined by class.
Encapsulation:
Encapsulation
is a process of binding the data members and member functions into a single
unit. It mainly refers to an object's ability to hide data and
behavior that are not necessary to its user.
Abstraction:
Abstraction is a process of hiding the implementation details
and displaying the essential features.
We use access specifiers to achieve Abstraction.
Public -- Accessible outside the class through object reference.
Private -- Accessible inside the class only
through member functions.
Protected -- Just like private but Accessible
in derived classes also through member
functions.
Internal -- Visible inside the assembly.
Accessible through objects.
Protected Internal -- Visible inside the assembly
through objects and in derived classes outside the assembly through member
functions.
Ex: Let us take my bike which hides its engine, fuel, internal
structure but it exposes color, tiers etc.
Simple Example explains Encapsulation & Abstraction:
public class Bike
{
private
string
_color
=
"Red”;
public string {get; set;}
private void Engine()
{
Console.WriteLine(“ABC
Engine”);
}
//here color is exposed to
outside world but not engine
}
static void main()
{
----
----
Bike objBike = new Bike()
ObjBike. è in intellisence you will see only color not Engine
In this way
abstraction is achieved.
}
//
private access specifier which we have used for Engine is implementing
Encapsulation, Encapsulation used in Abstraction to hide unwanted date, that’s
why
Encapsulation, in the context of
C#, refers to an object's ability to hide data and behavior that are not
necessary to its user.
Difference
between Abstraction and Encapsulation:
Abstraction is a process. It is the act of identifying the relevant qualities and behaviors an object should possess. Encapsulation is the mechanism by which the abstraction is implemented.
Abstraction is a process. It is the act of identifying the relevant qualities and behaviors an object should possess. Encapsulation is the mechanism by which the abstraction is implemented.
Abstraction
|
Encapsulation
|
Abstraction solves the problem in the design level.
|
Encapsulation solves the problem in the implementation level.
|
Abstraction is used for hiding the unwanted data and giving
only relevant data.
|
Encapsulation is hiding the code and data into a single unit
to protect the data from outer world.
|
Abstraction is set focus on the object instead of how it does
it.
|
Encapsulation means hiding the internal details or mechanics
of how an object does something.
|
Abstraction is outer layout in terms of design.
For Example: - Outer Look of a iPhone, like it has a display screen. |
Encapsulation is inner layout in terms of implementation.
For Example: - Inner Implementation detail of a iPhone, how Display Screen are connect with each other using circuits |
Inheritance:
Inheritance is a process of deriving the new class from already
existing class.
Types:
Inheritance can be classified to 5 types.
1. Single Inheritance
2. Hierarchical Inheritance
- Multi Level Inheritance
- Hybrid Inheritance
- Multiple Inheritance
1. Single
Inheritance
2. Hierarchical Inheritance
3. Multi Level Inheritance
4. Hybrid Inheritance
5. Multiple Inheritance (C#.NET implement using interfaces)
2. Hierarchical Inheritance
3. Multi Level Inheritance
4. Hybrid Inheritance
5. Multiple Inheritance (C#.NET implement using interfaces)
Polymorphism:
When a message can be processed in different ways is called
polymorphism. Polymorphism means many forms.
Polymorphism is one of the fundamental concepts of OOP.
Polymorphism is of two types:
1.
Compile time polymorphism/Overloading
2.
Runtime polymorphism/Overriding
Method overloading:
using System;
namespace method_overloading_polymorphism
{
Class Program
{
Public class Shape
{
Public void Area (float r)
{
float a = (float)3.14 * r;
// here we have used
function overload with 1 parameter.
Console.WriteLine ("Area of a
circle: {0}",a);
}
Public void Area(float l, float b)
{
float x = (float)l* b;
// here we have used
function overload with 2 parameters.
Console.WriteLine ("Area of a
rectangle: {0}",x);
}
public void Area(float a, float b, float c)
{
float s = (float)(a*b*c)/2;
// here we have used
function overload with 3 parameters.
Console.WriteLine ("Area of a
circle: {0}", s);
}
}
Static void Main (string[] args)
{
Shape ob = new Shape ();
ob.Area(2.0f);
ob.Area(20.0f,30.0f);
ob.Area(2.0f,3.0f,4.0f);
Console.ReadLine ();
}
}
}
Method Overriding:
Whereas Overriding means changing the
functionality of a method without changing the signature. We can override a
function in base class by creating a similar function in derived class. This is
done by using virtual/override keywords.
Base class method has to be marked with virtual keyword and we can override it in derived class using override keyword.
Derived class method will completely overrides base class method i.e. when we refer base class object created by casting derived class object a method in derived class will be called.
Base class method has to be marked with virtual keyword and we can override it in derived class using override keyword.
Derived class method will completely overrides base class method i.e. when we refer base class object created by casting derived class object a method in derived class will be called.
Example:
// Base class
public class BaseClass
{
public virtual void Method1()
{
Console.Write("Base Class Method");
}
}
// Derived class
public class DerivedClass : BaseClass
{
public override void Method1()
{
Console.Write("Derived Class Method");
}
}
// Using base and derived class
public class Sample
{
public void TestMethod()
{
// calling the overriden method
DerivedClass objDC = new DerivedClass();
objDC.Method1();
// calling the baesd class method
BaseClass objBC = (BaseClass)objDC;
objDC.Method1();
}
}
public class BaseClass
{
public virtual void Method1()
{
Console.Write("Base Class Method");
}
}
// Derived class
public class DerivedClass : BaseClass
{
public override void Method1()
{
Console.Write("Derived Class Method");
}
}
// Using base and derived class
public class Sample
{
public void TestMethod()
{
// calling the overriden method
DerivedClass objDC = new DerivedClass();
objDC.Method1();
// calling the baesd class method
BaseClass objBC = (BaseClass)objDC;
objDC.Method1();
}
}
Output
---------------------
---------------------
Derived Class Method
Derived Class Method
Constructors & Destructors:
Constructor is a
special method of a class which will invoke automatically whenever instance or
object of class is created. Constructors are responsible for object
initialization and memory allocation of its class. If we create any class
without constructor, the compiler will automatically create one default
constructor for that class. There is always at least one constructor in every
class.
Types
of Constructors
Basically constructors are 5
types those are
1. Default
Constructor è A constructor without having any parameters called default
constructor.
2. Parameterized
Constructor è A
constructor with parameters.
3. Copy Constructor è Explanation
below:
Copy
Constructor
A parameterized constructor
that contains a parameter of same class type is called as copy constructor. Main purpose of copy
constructor is to initialize new instance to the values of an existing
instance. Check below example for this
using System;
namespace CopyConstrucor
{
class CopyConstrucorSample
{
public string param1;
public CopyConstrucorSample
(string x)
{
param1 = x;
}
public CopyConstrucorSample
(Sample obj) //
Copy Constructor
{
param1 = obj.param1;
}
}
class Program
{
static void Main(string[]
args)
{
CopyConstrucorSample obj = new CopyConstrucorSample
("Mohammed Ilyas”); //
Create instance to class Sample
CopyConstrucorSample obj1=new CopyConstrucorSample
(obj); // Here obj details will copied to obj1
Console.WriteLine(“Hi”+obj1.param1);
Console.ReadLine();
}
}
}
|
When we run above program it
will show output like as shown below
Output
Hi Mohammed Ilyas
4. Static
Constructor è
Called only at first instance creation.
5. Private
Constructor è
Private
constructor is a special instance constructor used in a class that contains
static member only. If a class has one or more private constructor and no
public constructor then other classes is not allowed to create instance of this
class this mean we can neither create the object of the class nor it can be
inherit by other class. The main purpose of creating private constructor is
used to restrict the class from being instantiated when it contains every member
as static.
Destructor:
As you Know
Construction involves memory allocation
and initialization for objects in reverse Destructor involves cleanup and de-allocation
of memory for objects.
Example of
Destructor
class D
{
public D ()
{
// constructor
}
~D ()
{
// Destructor
}
}
Abstract Class:
a) An abstract class is a special kind of class that cannot be instantiated.
b) It allows the other classes to inherit from it but cannot be instantiated.
c) It is used to carry the same hierarchy or standards for all the subclasses.
Interface:
a) An interface is not a class,but it is an entity and has no implementation.
b) It has only the definition of the methods without the body.
a) An abstract class is a special kind of class that cannot be instantiated.
b) It allows the other classes to inherit from it but cannot be instantiated.
c) It is used to carry the same hierarchy or standards for all the subclasses.
Interface:
a) An interface is not a class,but it is an entity and has no implementation.
b) It has only the definition of the methods without the body.
When to use Interface
and abstract class:
One reason for using abstract classes
is we can code common
functionality and force our developer to use it. I can have a complete
class but I can still mark the class as abstract.
Developing by interface helps in object based communication.
functionality and force our developer to use it. I can have a complete
class but I can still mark the class as abstract.
Developing by interface helps in object based communication.
Interface:
–> If your child classes
should all implement a certain group of methods/functionalities but each of the
child classes is free to provide its own implementation then
use interfaces.
For e.g. if you are implementing a class hierarchy for vehicles
implement an interface called Vehicle which has properties like Colour MaxSpeed
etc. and methods like Drive(). All child classes like Car Scooter AirPlane
SolarCar etc. should derive from this base interface but provide a seperate
implementation of the methods and properties exposed by Vehicle.
–> If you want your child
classes to implement multiple unrelated functionalities in short multiple
inheritance use interfaces.
For e.g. if you are
implementing a class called SpaceShip that has to have functionalities from a
Vehicle as well as that from a UFO then make both Vehicle and UFO
as interfaces and then create a class SpaceShip that implements both
Vehicle and UFO .
Abstract Classes
–> When you have a requirement where your base class should
provide default implementation of certain methods whereas other methods should
be open to being overridden by child classes use abstract classes.
For e.g. again take the example
of the Vehicle class above. If we want all classes deriving from Vehicle to
implement the Drive() method in a fixed way whereas the other methods can be
overridden by child classes. In such a scenario we implement the Vehicle class
as an abstract class with an implementation of Drive while leave the
other methods / properties as abstract so they could be overridden by child
classes.
–> The purpose of
an abstract class is to provide a common definition of a base class
that multiple derived classes can share.
For example a class library may
define an abstract class that is used as a parameter to many of its
functions and require programmers using that library to provide their own
implementation of the class by creating a derived class.
C# Delegates:
Syntax
of Delegate & Methods Declaration
Check below sample code for
delegate declaration and methods declaration
public delegate int Delegatmethod(int a,int b);
public class Sampleclass
{
public int Add(int x, int y)
{
return x
+ y;
}
public int Sub(int x, int y)
{
return x
+ y;
}
}
|
If you observe above code I declared Delegatmethod method
with two parameters which matching with methods declared in Sampleclass class.
Complete Example
public delegate int DelegatSample(int a,int b);
public class Sampleclass
{
public int Add(int x, int y)
{
return x
+ y;
}
public int Sub(int x, int y)
{
return x
- y;
}
}
class Program
{
static void Main(string[]
args)
{
Sampleclass sc=new Sampleclass();
DelegatSample delgate1
= sc.Add;
int i
= delgate1(10, 20);
Console.WriteLine(i);
DelegatSample delgate2
= sc.Sub;
int j
= delgate2(20, 10);
Console.WriteLine(j);
}
}
|
Output
Whenever we run above code we
will get output like as shown below
Add Result : 30
Sub Result : 10
|
What
is the use of Delegates?
A
delegate in C# is similar to a function pointer in C or C++. Using a delegate
allows the programmer to encapsulate a reference to a method inside a delegate
object. The delegate object can then be passed to code which can call the
referenced method, without having to know at compile time which method will be
invoked.
Suppose if you have multiple
methods with same signature (return type & number of parameters) and want
to call all the methods with single object then we can go for delegates.
Delegates are two types
- Single Cast Delegates
- Multi Cast Delegates
Single
Cast Delegates
Single cast delegate means
which hold address of single method like as explained in above example.
Multicast
Delegates
Multi cast delegate is used to
hold address of multiple methods in single delegate. To hold multiple addresses
with delegate we will use overloaded += operator and if you want remove
addresses from delegate we need to use overloaded operator -=
Multicast delegates will work
only for the methods which have return type only void. If we want to create a
multicast delegate with return type we will get the return type of last method
in the invocation list
Check below sample code for
delegate declaration and methods declaration
Syntax
of Multicast Delegate & Method Declaration
Check below sample code for
multicast delegate declaration and methods declaration
public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine("Addition
Value: "+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction
Value: " + (x - y));
}
public static void Mul(int x, int y)
{
Console.WriteLine("Multiply
Value: " + (x * y));
}
}
|
If you observe above code I
declared MultiDelegate method with void return
type.
Complete Example
public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine("Addition
Value: "+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction
Value: " + (x - y));
}
public static void Mul(int x, int y)
{
Console.WriteLine("Multiply
Value: " + (x * y));
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();
MultiDelegate del = Sampleclass.Add;
del += Sampleclass.Sub;
del += Sampleclass.Mul;
del(10, 5);
Console.ReadLine();
}
}
|
Output
Whenever we run above code we
will get output like as shown below
Addition Value : 15
Subtraction Value : 5
Multiply Value : 50
|
Ref & Out keyword:
ref tells the compiler that the object is initialized
before entering the function, while out tells the compiler that the object will be
initialized inside the function.
So while ref is two-ways, out is out-only.
Ex:
using System;
class Program
{
static void Main()
{
int val = 0;
Example1(val);
Console.WriteLine(val); // Still 0!
Example2(ref val);
Console.WriteLine(val); // Now 2!
//Note here
if val =0 is not assigned then it throws an error unassigned variable
Example3(out val);
Console.WriteLine(val); // Now 3!
//Note here
if val =0 is not assigned then it don’t
throws any error
}
static void Example1(int value)
{
value = 1;
}
static void Example2(ref int
value)
{
value = 2;
}
static void Example3(out int
value)
{
value = 3;
}
}
Output
0
2
3
State Management:
There are two types of state
management techniques: client side and server side.
Client side
1.
Hidden Field
2.
View State
3.
Cookies
Ø Persistence Cookies(Has expiry defined)
Ø Non Persistence (No expiry, active till user uses
same browser)
4.
Control State
5.
Query Strings
Server side
1.
Session
2.
Application
How to Use Control State?
Control
state implementation is easy. First, override the OnInit method of the
control and add the call for the Page.RegisterRequiresControlState method
with the instance of the control to register. Then, override the
LoadControlState and SaveControlState in order to save the required
state information.
The
next example shows a simple implementation for a control that saves a
string as a state information:
public
class
ControlStateWebControl : Control
{
#region Members
private
string
_strStateToSave;
#endregion
protected
override
void
OnInit(EventArgs e)
{
Page.RegisterRequiresControlState(
this
);
base
.OnInit(e);
}
protected
override
object
SaveControlState()
{
return
_strStateToSave;
}
protected
override
void
LoadControlState(
object
state)
{
if
(state !=
null
)
{
_strStateToSave = state.ToString();
}
}
}
You
need to remember only one thing – the control state takes away the choice to
disable ViewState. You should
only use it whenever you have to keep a state information that without it your control won’t work
only use it whenever you have to keep a state information that without it your control won’t work
Application State
ASP.NET allows us
to save values using application state. A global storage mechanism that is
accessible from all pages in the Web application. Application state is stored
in the Application key/value dictionary. This information will also be
available to all the users of the website. In case we need user specific
information, then we better use sessionstate
.
ASP.NET provides three events
that enable you to initialize
Application
variables (free
resources when the application
shuts down) and respond to
Application
errors:
·
Application_Start
: Raised when the application starts. This is the
perfect place to initialize Application
variables.
·
Application_End
: Raised when an application shuts down. Use this to
free application resources and perform logging.
·
Application_Error
: Raised when an unhandled error occurs. Use this to
perform error logging.
Let us now store the information
of postbacks in application state:
//global.asax
void Application_Start(object sender, EventArgs e)
{
Application["number"] = 0;
}
//In web pages
Application.Lock();
Application["number"] = Convert.ToInt32(Application["number"]) + 1;
Application.UnLock();
Label5.Text = Application["number"].ToString();
Session State
Like
Application
state, this information is also in a global storage that is
accessible
from all pages in the Web
application.
Session
state is stored in the Sessionkey
/value
dictionary
. This information will be available to the current user only,
i.e., current session only.//global.asax
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Session["number"] = 0;
}
// Web forms
Session["number"] = Convert.ToInt32(Session["number"]) + 1;
Label6.Text = Session["number"].ToString();
There is another event called Session_End executed
when session expires or Session.Abandon();
Types Of session state:
There are four session
storage mechanisms provided by ASP.NET:
·
In
Proc mode
·
State
Server mode
·
SQL
Server mode
·
Custom mode
In Process mode: In proc mode is the default mode provided by ASP.NET. In this
mode, session values are stored
in the web server's memory (in IIS). If there are more
than one IIS servers then
session values are stored in each server separately on which
request has been made. Since the session
values are stored in server, whenever
server is restarted the session
values will be lost.
<configuration>
<sessionstate mode="InProc" cookieless="false" timeout="10"
stateConnectionString="tcpip=127.0.0.1:80808"
sqlConnectionString="Data Source=.\SqlDataSource;User ID=userid;
Password=password"/>
</configuration>
In State Server mode: This mode could store session in the web
server but out of the
application
pool. But usually if this mode is used there will be a separate server for
storing
sessions, i.e.,
stateServer
. The benefit is that when IIS restarts the session is
available. It
stores session in a separate Windows service. For State server session
mode, we have
to configure it explicitly in the web config file and start
the
aspnet_state
service.<configuration><sessionstate mode="stateserver" cookieless="false"
timeout="10" stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="Data Source=.\SqlDataSource;User ID=userid;
Password=password"/>
</configuration>
In SQL Server mode: Session is stored in a SQL Server database. This kind of
session
mode is also separate from IIS,
i.e., session is available even after restarting the IIS
server. This mode is highly
secure and reliable but also has a disadvantage that there
is overhead from serialization
and deserialization of session data. This mode should be
used when reliability is more
important than performance.
<configuration>
<sessionstate mode="sqlserver" cookieless="false" timeout="10"
stateConnectionString="tcpip=127.0.0.1:4 2424"
sqlConnectionString="Data Source=.\SqlDataSource;User ID=userid;
Password=password"/>
</configuration>
Custom Session mode: Generally we should prefer in proc state server mode or
SQL
Server mode but if you need to store session
data using other than these techniques
then ASP.NET provides a custom
session mode. This way we have to maintain
everything customized even generating
session ID, data store, and also security.
Asp.NET Page Life
Cycle
When a visitor first requests an .aspx page on
your server, the server sends it to the HTTP Pipeline.
(HTTP Pipeline is a chain of managed objects that sequentially process the request and convert it to plain HTML text content.)
(HTTP Pipeline is a chain of managed objects that sequentially process the request and convert it to plain HTML text content.)
The HTTP Pipeline handles all processes involved in converting all of the application code into HTML to be interpreted by the browser.
The first class initiated is called HttpRuntime. This class finds a free HttpApplication object to start processing the request. The HttpApplication object then runs the appropriate handler assigned in the web.config and machine.config files for the requested extension.
The extension .aspx can be handled by the HandlerClass or HandlerFactory class. The HttpApplication objects starts the IHttpHandler interface which begins processing the application code by calling the processRequest() method.
The processRequest() method then calls the FrameworkInitialize() method which begins building the control trees for the requested page.
(You can see the Control tree of any aspx page by giving Trace="true" in Page Directive)
Request(.aspx) --> IIS --> HTTPPipeLine --> HttpRuntime -->HttpApplication -->Handler(HandlerClass/HandlerFactory) --> Process Application by processRequest() -->
FrameworkInitialize()
Now the processRequest() method cycles through the page’s life cycle in the order listed below.
Following are the page life cycle events:
PreInit . PreInit is the first event in
page life cycle. It checks the IsPostBack property and determines whether the
page is a postback. It sets the themes and master pages, creates dynamic
controls and gets and sets profile property values. This event can be handled
by overloading the OnPreInit method or creating a Page_PreInit handler.
Init . Init event initializes the control property and the
control tree is built. This event can be handled by overloading the OnInit
method or creating a Page_Init handler.
InitComplete . InitComplete event allows
tracking of view state. All the controls turn on view-state tracking.
LoadViewState . LoadViewState event allows
loading view state information into the controls.
LoadPostData . during this phase, the contents
of all the input fields defined with the <form> tag are processed.
PreLoad . PreLoad occurs before the post
back data is loaded in the controls. This event can be handled by overloading
the OnPreLoad method or creating a Page_PreLoad handler.
Load . the Load event is raised for the page first and then
recursively for all child controls. The controls in the control tree are
created. This event can be handled by overloading the OnLoad method or creating
a Page_Load handler.
LoadComplete . the loading process is
completed, control event handlers are run and page validation takes place. This
event can be handled by overloading the OnLoadComplete method or creating a
Page_LoadComplete handler.
PreRender . the PreRender event occurs just
before the output is rendered. By handling this event, pages and controls can
perform any updates before the output is rendered.
PreRenderComplete . as the PreRender event is
recursively fired for all child controls, this event ensures the completion of
the pre-rendering phase.
SaveStateComplete . state of control on the page is
saved. Personalization, control state and view state information is saved. The
HTML markup is generated. This stage can be handled by overriding the Render
method or creating a Page_Render handler.
UnLoad . the UnLoad phase is the last
phase of the page life cycle. It raises the UnLoad event for all controls
recursively and lastly for the page itself. Final cleanup is done and all
resources and references, such as database connections, are freed. This event
can be handled by modifying the OnUnLoad method or creating a Page_UnLoad
handler.
Short Forms:
PreIn->In->Incomp
LoadVstate->LoadPostData
PreLoad->Load->Loadcomplete
PreRender->PreRendComplete->SaveStatecomplete
UnLoad
Now Let Us Come to Programming Stuff- How to Handle Above Events:
Below is the Code where I handled each event Try and Enjoy...
StringBuilder sb = new StringBuilder();
protected void Page_PreInit(object o, EventArgs e)
{
sb.Append("<b>Page Pre_Init</b> - Occurs at the begining of the Page Initialization <br />");
}
protected void Page_Init(object sender, EventArgs e)
{
sb.Append("<b>Page Init </b>- Occurs when the Server Control is Initialized. It is the first step in the ASP.NET Page Life Cycle <br />");
}
public void Page_InitComplete(object sender, EventArgs e)
{
sb.Append("<b>Page Init Complete </b>- Occurs when the Page Initialization is Complete <br />");
}
public void Page_PreLoad(object sender, EventArgs e)
{
sb.Append("<b>Page Pre Load </b>- Occurs before the Load Event <br />");
}
protected void Page_Load(object sender, EventArgs e)
{
sb.Append("<b>Page Load </b>- Occurs when the Server Control is Loaded in the Page Object <br />");
}
void Page_LoadComplete(object sender, EventArgs e)
{
sb.Append("<b>Page Load Complete </b>- Occurs at the end of Load Stage of the Page Life Cycle. <br />");
}
void Page_PreRender(object sender, EventArgs e)
{
sb.Append("<b>Page Pre Render </b>- Occurs after the Server Controls is Loaded in the Page but before the Rendering</div> <br />");
}
void Page_PreRenderComplete(object sender, EventArgs e)
{
sb.Append("<b>Page Pre Render Complete </b>- Occurs before the Page Content is Rendered <br />");
Response.Write(sb.ToString());
}
/// This is the event when the page is unloaded from the server memory and ready to be returned to the client,
/// Here the response is not available, so you cannot modify the Response
void Page_Unload(object sender, EventArgs e)
{
}
C# Collections Quick
View
Here is
the quick view of glance about collection objects ==>
Lists
Lists allow duplicate items, can be accessed by index, and support linear traversal.
ArrayList - An array-based list that
doesn't support generic types. It does not enforce type safety and should
generally be avoided.
List - An array list that
supports generic types and enforces type-safety. Since it is non-contiguous, it
can grow in size without re-allocating memory for the entire list. This is the
more commonly used list collection.
Hashes
Hashes are look-ups in which you give each item in a list a "key" which will be used to retrieve it later. Think of a hash like a table index where you can ask questions like "I'm going to find this object by this string value. Duplicate keys are not allowed.
HashTable - A basic key-value-pair
map that functions like an indexed list.
Dictionary - A hashtable that supports
generic types and enforces type-safety.
Queues
Queues controls how items in a list are accessed. You typically push/pop records from a queue in a particular direction (from either the front or back). Not used for random access in the middle.
Stack - A LIFO list where you
push/pop records on top of each other.
Queue - A FIFO list where you
push records on top and pop them off the bottom.
Extension Method Concepts came From .NET 3.5 below
example demonstrate this
Writing Extension Method for String Data Type:
public static class StringExtensions
{
public static int WordCount(this string str)
{
return str.Split(new char[] { ' ', '.', '?', '!' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
|
The method WordCount(…) extends the class String. This is indicated by the
keyword this before the type and the
name of the first argument of the method (in our case str). The method itself is static and it is defined in the
static class StringExtensions. The usage of the extension method is done the same way as all
the other methods of the class String. Do not forget to add the corresponding namespace, where the
static class, describing the extension methods, is defined.
Example of using an
extension method:
static void Main()
{
string helloString = "Hello, Extension
Methods!";
int wordCount =
helloString.WordCount();
Console.WriteLine(wordCount);
}
|
C# Data Structures Under One Roof
In this article I am trying to explain C# data structures while programming.I have written the theory in the commented form.
Just go step by step you will get understand better with theory.
In this article I am trying to explain C# data structures while programming.I have written the theory in the commented form.
Just go step by step you will get understand better with theory.
class Empty
{}
static void Main(string[]
args)
{
#region Collections
/*=================ArrayList
- Start====================*/
/*Introduction: There are two distinct collection types in
C#.
The standard collections, which are found under the
System.Collections namespace and the generic collections,
under System.Collections.Generic.
The generic collections are more flexible and are the
preferred way to work with data.
The generic collections or generics were introduced in
.NET framework 2.0.
Generics enhance code reuse, type safety, and performance.
*/
/*ArrayList => An ArrayList is a collection from a
standard System.Collections namespace.
It is a dynamic array.An ArrayList automatically expands
when data is added.
ArrayList can hold data of multiple data types.*/
ArrayList da = new ArrayList();
da.Add("Visual
Basic");
da.Add(344);
da.Add(55);
da.Add(new Empty());
da.Remove(55);
Console.WriteLine("ArrayList
- output");
foreach (object el in da)
{
Console.WriteLine(el);
}
/*Output => Visual Basic
344
YourParentClassName+Empty*/
/*=================ArrayList
- End====================*/
/*=================List
- Start====================*/
/*Introduction: A List is a strongly typed list of objects
that can be accessed by index.
It can be found under System.Collections.Generic
namespace. */
// Use the List type.
List<string>
list = new List<string>();
list.Add("dotnet");
list.Add("ilyas");
list.Add("removeme");
list.Insert(1, "developer"); //You can insert the value
at specific location
list.Sort(); //It sort list collection in
ascending order
list.Remove("removeme");
Console.WriteLine();
Console.WriteLine("List
- output");
/*You can read the list in
this way*/
foreach (string element in list.OrderByDescending(i
=> i)) //show
in descending
{
Console.WriteLine(element);
}
/*Output => ilyas
dotnet
developer*/
/*=================List
- End====================*/
/*=================Linked
List - Start====================*/
/*Introduction:LinkedList only allows sequential access.
LinkedList allows for constant-time insertions or
removals,
but only sequential access of elements.*/
LinkedList<int>
nums = new LinkedList<int>();
nums.AddLast(13);
nums.AddLast(44);
nums.AddLast(53);
nums.AddLast(21);
nums.AddLast(7);
nums.AddFirst(10);
nums.AddFirst(17);
LinkedListNode<int>
node = nums.Find(7); //We
can find the specific element
nums.AddBefore(node, 5);//add
the element before
Console.WriteLine();
Console.WriteLine("LinkedList
- output");
foreach (int num in nums)
{
Console.WriteLine(num);
}
/*Output => 17
10
13
44
53
21
5
7*/
/*=================Linked
List - End====================*/
/*=================Dictionary
- Start====================*/
/*Introduction:Dictionary stores the values with key value
pair,
You can read the dictionary value with a key in this way,
it is also called as associative array,
it is very fast but takes more space since we have each
key with each value*/
Dictionary<string, int>
dictionary = new Dictionary<string, int>();
dictionary.Add("cat",
1);
dictionary.Add("dog",
4);
Console.WriteLine();
Console.WriteLine("Dictionary
- output");
var keys = new List<string>(dictionary.Keys);
foreach (string key in keys) //Reading values with key
{
Console.WriteLine(dictionary[key]);
}
var values = new List<int>(dictionary.Values);
foreach (int val in values)//Reading
keys with value
{
/*Accessing thi way lead to
an error => Console.WriteLine(dictionary[val]);*/
var myValue =
dictionary.FirstOrDefault(x => x.Value == val).Key; //this way you can read key
with value
Console.WriteLine(myValue);
}
foreach (KeyValuePair<string, int>
kvp in dictionary) //Reading key value pair
{
Console.WriteLine("Key
= {0}, Value = {1}", kvp.Key, kvp.Value);
}
/*Output: 1
4
cat
dog
Key = cat, Value =1
Key = dog, Value =4 */
/* In the similar there is called Hashtable which is
Collection type not generic.
Ex:
Hashtable hashtable = new Hashtable();
hashtable.Add("Area", 1000);
hashtable.Add("Perimeter",
55);
hashtable.Add("Mortgage",
540);
Accessing:
Hashtable hashtable = GetHashtable();
Console.WriteLine(hashtable.ContainsKey("Perimeter"));o/p - True
Console.WriteLine(hashtable.Contains("Area")); o/p - True
Console.WriteLine((int)hashtable["Area"]); o/p - 100
The major differences between HashTable and Dictionary are
1. Hashtable is thread safe and while Dictionary is not.
2. Dictionary is types means that the values need not to boxing while Hashtable
values need to be boxed or unboxed because it stored the values and keys as
objects.
3. When you try to get the value of key which does not exists in the collection, the
dictionary throws an exception of 'KeyNotFoundException' while hashtable returns
null value.
4. When using large collection of key value pairs hashtable would be considered more
efficient than dictionary.
5. When we retrieve the record in collection the hashtable does not maintain the order
of entries while dictionary maintains the order of entries by which entries were added.
6. Dictionary relies on chaining whereas Hashtable relies on rehashing.
2. Dictionary is types means that the values need not to boxing while Hashtable
values need to be boxed or unboxed because it stored the values and keys as
objects.
3. When you try to get the value of key which does not exists in the collection, the
dictionary throws an exception of 'KeyNotFoundException' while hashtable returns
null value.
4. When using large collection of key value pairs hashtable would be considered more
efficient than dictionary.
5. When we retrieve the record in collection the hashtable does not maintain the order
of entries while dictionary maintains the order of entries by which entries were added.
6. Dictionary relies on chaining whereas Hashtable relies on rehashing.
Note: I am not taken its output in command prompt.*/
/*=================Dictionary
- End====================*/
/*=================Queues
- Start====================*/
/*Introduction: A queue is a First-In-First-Out (FIFO)
data structure.
The first element added to the queue will be the first to
be removed.*/
Queue<string>
msgs = new Queue<string>();
msgs.Enqueue("Msg-1");
msgs.Enqueue("Msg-2");
msgs.Enqueue("Msg-3");
msgs.Enqueue("Msg-4");
Console.WriteLine();
Console.WriteLine("Queue
- output");
//Dequeue() removes and returns
the item at the beginning of the queue.
Console.WriteLine(msgs.Dequeue()
+ "
=>Dequeue() removed first item" +"\n");
// Peek() method returns the
next item from the queue, but does not remove it from collection
Console.WriteLine(msgs.Peek()
+ "=>Peek()
returned next item" + "\n");
Console.WriteLine("Now
msgs Queue has below elements");
foreach (string msg in msgs)
{
Console.WriteLine(msg);
}
/*Output-
Msg-1 =>Dequeue() removed
first item
Msg-2 =>Peek() returned next item
Now msgs Queue has below
elements
Msg-2
Msg-3
Msg-4 */
/*=================Queues
- End====================*/
/*=================Stacks
- Start====================*/
/*Introduction: A stack is a Last-In-First-Out (LIFO) data
structure.
The last element added to the queue will be the
first to be removed. */
Stack<int>
stk = new Stack<int>();
stk.Push(1);
stk.Push(2);
stk.Push(3);
stk.Push(4);
Console.WriteLine();
Console.WriteLine("Stack
- output");
Console.WriteLine(stk.Pop()
+ " - Pop()
method removes the last one" +"\n");
Console.WriteLine(stk.Peek()
+ " - Peek()
method returns item from stack top but does not remove it. " + "\n");
Console.WriteLine();
Console.WriteLine("Now
stk stack has below elements");
foreach (int item in stk)
{
Console.WriteLine(item);
}
/*Output-
4 - Pop() method removes the
last one
3 - Peek() method returns
item from stack top but does not remove it.
Now stk stack has below
elements
3
2
1
*/
/*=================Stacks -
End====================*/
Console.Read();
#endregion
}
Output Window:
Difference between Generics & Collections:
Generics provides the type safe code with re-usability
like as algorithm. In algorithms such as sorting, searching, comparing etc. you don’t specify what
data type(s) the algorithm operates on. The algorithm can be operates with any
types of data. In the same way Generics operate, you can provide different data
type to Generics. For example, a sorting algorithm can operates on integer
type, decimal type, string type, DateTime type etc.
‘Base’
keyword:
In c#,
to access members and functionalities of the base class, the 'base' keyword is
used within a derived class. In the given code, we have used 'base' keyword to
call the constructor of the Account class.
class Account
{
private string mCode;
private string mName;
private string
mDescription;
private double
mBalance;
public Account(string
code, string name, string description, double balance)
{
mCode = code;
mName = name;
mDescription =
description;
mBalance =
balance;
}
public Account()
{
}
In the below code, the derived class constructor - 'PartyAccount' receives the values first and which are then passed to the base class constructor.
class PartyAccount :Account
{
private string
mAddress;
private string
mPhone;
public PartyAccount(string code, string name, string description,
double balance, string address, string phone)
: base(code, name,
description, balance)
{
mAddress = address;
mPhone = phone;
}
public PartyAccount()
: base()
{
}
Example2:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text;
namespace NS_HRapplication
{
//declare a base Class...
class CL_employees
{
public void FN_displaySalary()
{
Console.WriteLine("Salary is 1000 euro...");
}
}
//create a derived Class and inherit base Class...
class CL_tehnicians : CL_employees
{
public void FN_displaySalary()
{
//we assume that managers are getting paid 1000 euro extra
than base employee salary...
base.FN_displaySalary();
}
}
class CL_x
{
static void Main(string [] args)
{
//create a technician instance-object
CL_tehnicians o_aTechnician = new CL_tehnicians();
//display salary...
o_aTechnician.FN_displaySalary();
Console.ReadLine();
}
}
}
}
}
}
Note : The 'MyBase' keyword in vb.net is the counterpart for the 'base' keyword in c#.
if you have worked on c# & vb.net then I would suggest you to refresh the differences between them,
clear differences has been explained very nice here
Different Dot Net Frameworks their Major Differences
dotnet framework 4.5
Async
Support
Support
for building Windows Store apps
Features
Enhancement to WPF, WCF, WF, and ASP.NET
dotnet framework 4.0
Application
Compatibility and Deployment > Related to deployment.
Client Profile
In-Process Side-by-Side Execution
Portable Class Library
Core
New Features and Improvements (with the .NET Framework 4, you can get processor
usage and memory usage estimates per application domain),
Background
GC
dotnet framework 3.5
3.5
> LINQ, AJAX
dotnet framework 3.0
3.0
> WCF, WPF, WWF
dotnet framework 2.0
2.0
> Generics, Partial classes, anonymous methods, nullable types
Diagrammatical
View:
No comments:
Post a Comment