a. View State – Asp.Net uses View State to track the values in the Controls. You can add
custom values to the view state. It is used by the Asp.net page framework to automatically
save the values of the page and of each control just prior to rendering to the page. When
the page is posted, one of the first tasks performed by page processing is to restore view
state.
b. Control State – If you create a custom control that requires view state to work properly,
you should use control state to ensure other developers don’t break your control by
disabling view state.
c. Hidden fields – Like view state, hidden fields store data in an HTML form without
displaying it in the user's browser. The data is available only when the form is processed.
d. Cookies – Cookies store a value in the user's browser that the browser sends with every
page request to the same server. Cookies are the best way to store state data that must be
available for multiple Web pages on a web site.
e. Query Strings - Query strings store values in the URL that are visible to the user. Use
query strings when you want a user to be able to e-mail or instant message state data with
a URL.
b. Session State – Session State information is available to all pages opened by a user
during a single visit.
Both application state and session state information is lost when the application restarts. To
persist user data between application restarts, you can store it using profile properties.
Implementation Procedure
View State:
The ViewState property provides a dictionary object for retaining values between multiple
requests for the same page. When an ASP.NET page is processed, the current state of the
page and controls is hashed into a string and saved in the page as a hidden field. If the data
is too long for a single field, then ASP.NET performs view state chunking (new in ASP.NET
2.0) to split it across multiple hidden fields. The following code sample demonstrates how
view state adds data as a hidden form within a Web page’s HTML:
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE”
value="/wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2ID
E6Mzc6MTEgUE1kZGROWHn/rt75XF/pMGnqjqHlH66cdw==" />
Encrypting of the View State: You can enable view state encryption to make it more difficult
for attackers and malicious users to directly read view state information. Though this adds
processing overhead to the Web server, it supports in storing confidential information in
view state. To configure view state encryption for an application does the following:
<Configuration>
<system.web>
<pages viewStateEncryptionMode="Always"/>
</system.web>
</configuration>
Alternatively, you can enable view state encryption for a specific page by setting the value
in the page directive, as the following sample demonstrates:
View State is enabled by default, but if you can disable it by setting the EnableViewState
property for each web control to false. This reduces the server processing time and
decreases page size.
Reading and Writing Custom View State Data:
If you have a value that you’d like to keep track of while the user is visiting a single
ASP.NET Web page, adding a custom value to ViewState is the most efficient and secure
way to do that. However, ViewState is lost if the user visits a different Web page, so it is
useful only for temporarily storing values.
Example: Determine the time of last visit to the page
// Define the ViewState object for the next page view ViewState.Add("lastVisit",
DateTime.Now.ToString());
Control State: If you create a custom control that requires ViewState, you can use the
ControlState property to store state information for your control. ControlState allows you to
persist property information that is specific to a control and cannot be turned off like the
ViewState property. To use control state in a custom control, your control must override the
OnInit method and call the Register-RequiresControlState method during initialization and
then override the SaveControl-State and LoadControlState methods.
Hidden fields: ViewState stores information in the Web page using hidden fields. Hidden
fields are sent back to the server when the user submits a form; however, the information
is never displayed by the Web browser (unless the user chooses to view the page source).
ASP.NET allows you to create your own custom hidden fields and store values that are
submitted with other form data. A HiddenField control stores a single variable in its Value
property and must be explicitly added to the page. You can use hidden fields only to store
information for a single page, so it is not useful for storing session data. If you use hidden
fields, you must submit your pages to the server using Hypertext Transfer Protocol (HTTP)
POST (which happens if the user presses a button) rather than requesting the page using
HTTP GET (which happens if the user clicks a link). Unlike view state data, hidden fields
have no built-in compression, encryption, hashing, or chunking, so users can view or modify
data stored in hidden fields.
Cookies: Web applications can store small pieces of data in the client’s Web browser by
using cookies. A cookie is a small amount of data that is stored either in a text file on the
client file system (if the cookie is persistent) or in memory in the client browser session (if
the cookie is temporary). The most common use of cookies is to identify a single user as he
or she visits multiple Web pages.
If you do not define the Expires property, the browser stores it in memory and the cookie is
lost if the user closes his or her browser.
To delete a cookie, overwrite the cookie and set an expiration date in the past. You can’t
directly delete cookies because they are stored on the client’s computer.
Controlling the Cookie Scope: By default, browsers won’t send a cookie to a Web site with a
different hostname. You can control a cookie’s scope to either limit the scope to a specific
folder on the Web server or expand the scope to any server in a domain. To limit the scope
of a cookie to a folder, set the Path property, as the following example demonstrates:
Example:
Response.Cookies["lastVisit"].Path = "/Application1";
Through this the scope is limited to the “/Application1” folder that is the browser submits
the cookie to any page with in this folder and not to pages in other folders even if the folder
is in the same server. We can expand the scope to a particular domain using the following
statement:
Example:
Response.Cookies[“lastVisit”].Domain = “Contoso”;
Response.Cookies["info"]["visit"].Value = DateTime.Now.ToString();
Response.Cookies["info"]["firstName"].Value = "Tony";
Response.Cookies["info"]["border"].Value = "blue";
Response.Cookies["info"].Expires = DateTime.Now.AddDays(1);
Running the code in this example sends a cookie with the following value to the Web
browser:
(visit=4/5/2006 2:35:18 PM) (firstName=Tony) (border=blue)
Query Strings: Query strings are commonly used to store variables that identify specific
pages, such as search terms or page numbers. A query string is information that is
appended to the end of a page URL. A typical query string might look like the following real-
world example:
http://support.microsoft.com/Default.aspx?kbid=315233
In this example, the URL identifies the Default.aspx page. The query string (which starts
with a question mark [?]) contains a single parameter named “kbid,” and a value for that
parameter, “315233.” Query strings can also have multiple parameters, such as the
following real-world URL, which specifies a language and query when searching the
Microsoft.com Web site:
http://search.microsoft.com/results.aspx?mkt=en-US&setlang=en-US&q=hello+world
Application State: ASP.NET allows you 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. Once you add your application-
specific information to application state, the server manages it, and it is never exposed to
the client. Application state is a great place to store information that is not user-specific. By
storing it in the application state, all pages can access data from a single location in
memory, rather than keeping separate copies of the data. Data stored in the Application
object is not permanent and is lost any time the application is restarted.
ASP.NET provides three events that enable you to initialize Application variables (free
resources when the application shuts down) and respond to Application errors:
a. Application_Start: Raised when the application starts. This is the perfect place to initialize
Application variables.
b. Application_End: Raised when an application shuts down. Use this to free application
resources and perform logging.
c. Application_Error: Raised when an unhandled error occurs. Use this to perform error
logging.
Session State: ASP.NET allows you to save values using session state, a storage
mechanism that is accessible from all pages requested by a single Web browser session.
Therefore, you can use session state to store user-specific information. Session state is
similar to application state, except that it is scoped to the current browser session. If
different users are using your application, each user session has a different session state. In
addition, if a user leaves your application and then returns later after the session timeout
period, session state information is lost and a new session is created for the user. Session
state is stored in the Session key/value dictionary.
ii. Store session-specific data on the server for use across multiple browser or client-device
requests during the same session. This is perfect for storing shopping cart information.
iii. Raise appropriate session management events. In addition, you can write application
code leveraging these events.
ASP.NET session state supports several different storage options for session data:
a. InProc Stores session state in memory on the Web server. This is the default, and it
offers much better performance than using the ASP.NET state service or storing state
information in a database server. InProc is fine for simple applications, but robust
applications that use multiple Web servers or must persist session data between application
restarts should use State Server or SQLServer.
b. StateServer Stores session state in a service called the ASP.NET State Service. This
ensures that session state is preserved if the Web application is restarted and also makes
session state available to multiple Web servers in a Web farm. ASP.NET State Service is
included with any computer set up to run ASP.NET Web applications; however, the service is
set up to start manually by default. Therefore, when configuring the ASP.NET State Service,
you must set the startup type to Automatic.
c. SQLServer Stores session state in a SQL Server database. This ensures that session state
is preserved if the Web application is restarted and also makes session state available to
multiple Web servers in a Web farm. On the same hardware, the ASP.NET State Service
outperforms SQLServer. However, a SQL Server database offers more robust data integrity
and reporting capabilities.
d. Custom Enables you to specify a custom storage provider. You also need to implement
the custom storage provider.
e. Off Disables session state. You should disable session state if you are not using it to
improve performance.
Advantages
1. Better Scalability: With server-side state management, each client that connects to the
Web server consumes memory on the Web server. If a Web site has hundreds or thousands
of simultaneous users, the memory consumed by storing state management information can
become a limiting factor. Pushing this burden to the clients removes that potential
bottleneck.
2. Supports multiple Web servers: With client-side state management, you can distribute
incoming requests across multiple Web servers with no changes to your application because
the client provides all the information the Web server needs to process the request. With
server-side state management, if a client switches servers in the middle of the session, the
new server does not necessarily have access to the client’s state information. You can use
multiple servers with server-side state management, but you need either intelligent load-
balancing (to always forward requests from a client to the same server) or centralized state
management (where state is stored in a central database that all Web servers access).
Access modifiers determine the extent to which a variable or method can be accessed from
another class or object
The following five accessibility levels can be specified using the access modifiers
• Private
• Protected
• Internal
• Protected internal
• Public
In OOP Attributes, Methods, Properties, Constructors declared with “private” access modifier
get access or visible only to members of current class
For e.g.: Let’s take class BankDetail with access modifier “private”
class BankDetail
{
}
Create another class “clsShowDetails”
}
From class “clsShowDetail”
public void getDetails()
{
objBank.DisplayDetail();
}
We will get error message
For e.g.: Let’s take class BankDetail with access modifier “protected”
class BankDetail
{
}
From class “clsShowDetail”
This means we can access Attributes, Methods, Properties, Constructors declared with
“protected” access modifier in derived class
For e.g.: Let’s take class BankDetail with access modifier “internal”
class BankDetail
{
This means we can access Attributes, Methods, Properties, and Constructors declared with
“internal” access or visible only to members of current project or in current namespace
In OOP Attributes, Methods, Properties, Constructors declared with “public” access modifier
get access or visible to all members of classes and projects
class BankDetail
{
public string _employeename;
public int _accountnumber;
public double _balanceamount;
public string EmployeeName
{
set
{
_employeename = value;
}
get
{
return _employeename;
}
}
public int AccountNumer
{
set
{
_accountnumber = value;
}
get { return _accountnumber; }
}
public double BalanceAmount
{
set { _balanceamount = value; }
get { return _balanceamount; }
}
}
Create another class “clsShowDetails”
}
From class “clsShowDetail”
}
From class “clsShowDetail”
public void getDetails()
{
objBank.DisplayDetail();
}
We will get no error message
This means “public” access modifier is access or visible to all members of classes and
projects.
What is an Abstraction?
• Abstraction is thinking about something a certain way
• Abstraction is the representation of only the essential features of an object and hiding un
essential features of an object.
• Through Abstraction all relevant data can be hide in order to reduce complexity and
increase efficiency
• Abstraction is simplifying complex reality by modeling classes appropriate to the problem
• Abstraction-outer layout, used in terms of design
• Encapsulation protects abstraction.
• It taking required data and hiding the unwanted data.
In this above example abstraction shows only necessary details of car or shows only
necessary details to drive a car like rear view mirror, gear, clutch, steering And hides
internal detail of car like Piston, crankshaft, carburetors, gas turbines etc which is
encapsulation for a car.
3. Abstraction is a technique that helps to 3. Encapsulation is the technique for packaging the
identify which specific information should information in such a way as to hide what should
be visible and which information should be hidden, and make visible what is intended to be
be hidden. visible.
In this above example abstraction shows only necessary details of car or shows only
necessary details to drive a car like rear view mirror, gear, clutch, steering And hides
internal detail of car like Piston, crankshaft, carburetors, gas turbines etc which is
encapsulation for a car
In above example which shows encapsulated detail of a car which is not necessary to
expose to outside world and make visible what is intended to be visible.
What is Polymorphism?
Types of Polymorphism
What is Encapsulation?
Benefits of Encapsulation
Polymorphism
The word Polymorphism means of many forms.In programming this word is meant to reuse
the single code multiple times. In object oriented programming its a big question that why
the Polymorphism is done, what is the purpose of it in our code?
There are lots of people who don't even know the purpose and usage of
Polymorphism.Polymorphism is the 3rd main pillar of OOP without it the object oriented
programming is incomplete. Lets go in the depth of Polymorphism.
Why Polymorphism is done in OOP?
Its obvious that when we do inheritance between two classes, all the methods and
properties of the first class are derived to the other class so that this becomes the child
class which adobes all the functionality of base class.It can also possesses its own separate
methods.
But there is a big problem in inheriting the second class to the first class as it adobes all the
methods same as the base class has,which means that after inheritance both(base class&
child class) have the methods of same name and same body as shown in this example:~
____Base Class___
______Derived Class______
class Dolphen:fish
{
In this example it is clear that when we Inherit two classes, all the methods with the same
name and same body are adobed by the derived class as shown above.Both methods have
the same name but if we change the body of the second method then it makes Compiler
disturb whether to compile base class method or derived class's
method first...
______Derived Class______
class Dolphin:fish
{
In this example we have changed the body of the methods of Derived class.Now this will
make the Compiler disturb to compile which method first,because they both have same
name but different bodies.
To remove this problem and to tell the compiler that which method is to be executed we
need to use Polymorphism.
Polymorphism is used to remove the problem which is shown in the above code.It is done
not by changing the name of the methods of both base & derived class.Infect it is done by
adding the "virtual" keyword before the base class method, and the "override" keyword
before the derived class method.As shown in this exmple:
____Base Class___
public class fish
{
public virtual void eat()
{
Console.WriteLine("fish eat");
}
public virtual void swim()
{
Console.WriteLine("fish swim");
}
}
______Derived Class______
This is actually the Polymorphism in which we write virtual keyword with the base class
method and we write override keyword with the derived class method as we did. It helps
the compiler to select the method to be executed.
class Program
{
public class fish
{
public virtual void eat()
{ }
public virtual void swim()
{}
public virtual void dive()
{}
}
public class Dolphin : fish
{
public override void eat()
{ Console.WriteLine("Dolphin eats Plants"); }
public override void swim()
{ Console.WriteLine("Dolphin swims quickly"); }
public override void dive()
{ Console.WriteLine("Dolphin dive deeply "); }
public void dance()
{ Console.WriteLine("Dolphin can Dance"); }
}
public class Shark : fish
{
public override void eat()
{ Console.WriteLine("Shark eats dead animal"); }
public override void swim()
{ Console.WriteLine("Sharks swim fastest than Dolphin"); }
public override void dive()
{ Console.WriteLine("Sharks Dive deeper than Dolphin"); }
What is Inheritance?
Inheritance, together with encapsulation and polymorphism, is one of the three primary
characteristics (concept) of object-oriented programming Inheritance enables you to create
new classes that reuse, extend, and modify the behavior that is defined in other classes The
Class whose methods and variables are defined is called super class or base class The Class
that inherits methods and variables are defined is called sub class or derived class
Sometimes base class known as generalized class and derived class known as specialized
class Keyword to declare inheritance is “:” (colon) in visual c#.
Benefits of using Inheritance
Once a behavior (method) or property is defined in a super class(base class),that behavior
or property is automatically inherited by all subclasses (derived class). Code reusability
increased through inheritance Inheritance provide a clear model structure which is easy to
understand without much complexity Using inheritance, classes become grouped together in
a hierarchical tree structure Code are easy to manage and divided into parent and child
classes
Example of Inheritance
• Implementation Inheritance
• Multiple Inheritances (Interface Inheritance)
Implementation Inheritance
One base class (super class) and one derived class (sub class).
Sample Picture:
Interface Inheritance
An interface looks like a class, but has no implementation. It contains definitions of events,
indexers, methods and properties. An interface inherited by classes An interface inheritance
defined with keyword “interface”. In C# Interface Inheritance also known as multiple
inheritances.
Inheritance Tree Structure:
Code Example
Compiler converts the program from one computer language to another computer language
that is translating from a higher level language to a lower level language. A compiler has to
cope with any valid syntax in the source language, and generate semantically equivalent
code in the target language.
Translator which translate one language to many other language or else we can say a
translator is usually translating from a high level language to another high level language,
or from a low level language to a high level language. A translator usually has a fixed body
of code that is required to translate the program.
What is an application pool?
Posted by: Prasham
1. An application pool is a set of one or more websites in IIS served by the worker process.
3. This process isolation prevents processing from interfacing with one another.
Define the list of properties, methods and events included in SmtpClient class in
the Framework?
Posted by: Tripati_tutu
1) Properties:
• Host- The name or IP address of your email server.
• Port- The number of the port to use when sending an email message.
2) Methods:
• Send- It enables you to send an email message synchronously
• SendAsync- It enables you to send an email message asynchronously.
3) Events:
• Send Completed- It is raised when an asynchronous send operation completes.
Answer:
The common language runtime (CLR) is major component in the .NET Framework and it is
the execution engine for .NET Framework applications.
8. Interoperation between managed code, COM objects, and pre-existing DLLs (unmanaged
code and data)
All memory in the app domain is managed by the .net runtime so the runtime can ensure
that app domain do not access each other's memory. Objects in different application
domains communicate either by transporting copies of objects across application domain
boundries or by using a proxy to exchange messages.
It is a often used to deploy language specific resources for an application. These assemblies
work in side-by-side execution because the application has a separate product ID for each
language & installed satellite assemblies in a language specific sub-directory.
When uninstalling, the application removes only the satellite assemblies associated within a
give language & .NET Framework version.
What is MSIL?
Posted by: Raja
What is CLS?
Overload is the another version of the same function into the class. There can be different
parameters, return type in overload functions (in brief: Same function and different
parameters).
Override is entirely overriding the base class function and creating our own version in the
child class. Base class and child class function name and return type should be same.
System.Threading.Thread.Abort
What is multi-threading?
There are two main ways of multi-threading which .NET encourages: starting your own
threads with ThreadStart delegates, and using the ThreadPool class either directly (using
ThreadPool.QueueUserWorkItem) or indirectly using asynchronous methods (such as
Stream.BeginRead, or calling BeginInvoke on any delegate).
What’s difference between System.SystemException and
System.ApplicationException?
Code Access Security (CAS), in the Microsoft .NET framework, is Microsoft's solution to
prevent untrusted code from performing privileged actions.
1. Defines permissions and permission sets that represent the right to access various
system resources.
2. Enables administrators to configure security policy by associating sets of permissions with
groups of code (code groups).
3. Enables code to request the permissions it requires in order to run, as well as the
permissions that would be useful to have, and specifies which permissions the code must
never have.
4. Grants permissions to each assembly that is loaded, based on the permissions requested
by the code and on the operations permitted by security policy.
5. Enables code to demand that its callers have specific permissions.
6. Enables code to demand that its callers possess a digital signature, thus allowing only
callers from a particular organization or site to call the protected code.
7. Enforces restrictions on code at run time by comparing the granted permissions of every
caller on the call stack to the permissions that callers must have.
What is Metadata?
Metadata is the complete way of describing what is in a .NET assembly. Digging into the
metadata yields the types available in that assembly, viz. classes, interfaces, enums,
structs, etc., and their containing namespaces, the name of each type, its visibility/scope,
its base class, the interfaces it implemented, its methods and their scope, and each
method’s parameters, type’s properties, and so on.
What is Manifest?
The manifest describes the assembly, providing the logical attributes shared by all the
modules and all components in the assembly. The manifest contains the assembly name,
version number, locale and an optional strong name that uniquely identifying the assembly.
Namespace:
1. It is a Collection of names wherein each name is Unique.
2. They form the logical boundary for a Group of classes.
3. Namespace must be specified in Project-Properties.
Assembly:
1. It is an Output Unit. It is a unit of Deployment & a unit of versioning. Assemblies contain
MSIL code.
2. Assemblies are Self-Describing. [e.g. metadata,manifest]
3. An assembly is the primary building block of a .NET Framework application. It is a
collection of functionality that is built, versioned, and deployed as a single implementation
unit (as one or more files). All managed types and resources are marked either as
accessible only within their implementation unit, or by code outside that unit.
Managed Code is what Visual Basic .NET and C# compilers create. It compiles to
Intermediate Language (IL), not to machine code that could run directly on your computer.
The IL is kept in a file called an assembly, along with metadata that describes the classes,
methods, and attributes (such as security requirements) of the code you've created. This
assembly is the one-stop-shopping unit of deployment in the .NET world. You copy it to
another server to deploy the assembly there—and often that copying is the only step
required in the deployment.
Unmanaged code is what you use to make before Visual Studio .NET 2002 was released.
Visual Basic 6, Visual C++ 6, heck, even that 15-year old C compiler you may still have
kicking around on your hard drive all produced unmanaged code. It compiled directly to
machine code that ran on the machine where you compiled it—and on other machines as
long as they had the same chip, or nearly the same. It didn't get services such as security
or memory management from an invisible runtime; it got them from the operating system.
And importantly, it got them from the operating system explicitly, by asking for them,
usually by calling an API provided in the Windows SDK. More recent unmanaged
applications got operating system services through COM calls.
A little description
While compiling of .NET program, its code is converted into Common Intermediate
Language code that is done by Common Language Runtime.
But while executing the program this CIL code is converted into Machine code or Native
code that is done by JIT Compiler.
C:\$WINDOWS\assembly
Can you give an example of when it would be appropriate to use a web service as
opposed to a non-serviced .NET component?
4. Software Reuse This takes place at multiple levels. Code Reuse at the Source code level
or binary componet-based resuse. The limiting factor here is that you can reuse the code
but not the data behind it. Webservice overcome this limitation. A scenario could be when
you are building an app that aggregates the functionality of serveral other Applicatons. Each
of these functions could be performed by individual apps, but there is value in perhaps
combining the the multiple apps to present a unifiend view in a Portal or Intranet.
2. Homogeneous Applications on a LAN If you have Win32 or Winforms apps that want to
communicate to their server counterpart. It is much more efficient to use DCOM in the case
of Win32 apps and .NET Remoting in the case of .NET Apps
. This property is used to check whether the page is being loaded and accessed for the first
time or whether the page is loaded in response to the client postback.
Example:
Consider two combo boxes
In one lets have a list of countries
In the other, the states.
Upon selection of the first, the subsequent one should be populated in accordance. So this
requires postback property in combo boxes to be true.
Friend/Internal - Method, Properties in that class can be accessed by all the classes within
that particular assembly.
Protected Friend/Protected Internal - Methods, Properties can be accessed by the child
classes of that particular class in that particular assembly.
What is the difference between overloading and overriding ? how can this be
.NET?
Overriding - Method has the same signature as the parent class method.
Overloading - Method having diff parameters list or type or the return type may be
different.
Explain serialization?
No, maintaining value in cookie wont be possible. In that case you have to make use of
other ways to maintain state of the data on page.
you can check whether client support cookies or not by using
Request.Browser.Cookies property.
using System;
using System.Collections.Generic;
class Shapes
class OutPuts
objshapes.getVolume();
}
Difference between VB.NET and C#.
C#.net :
-------------
1) supports unsigned int
2)strongly typed language
3)supports operator overloading
4)supports pointers
5)supports auto XML documentation
Indexers are similar to properties, except that the get and set accessors of indexers take
parameters, while property accessors do not.
A jagged array is an array whose elements are arrays. The elements of a jagged array can
be of different dimensions and sizes. A jagged array is sometimes called an "array-of-
arrays."
What is an Interface?
It defines derivation of new classes from more than one super class, that means by using
interface we can implement multiple inheritance.
Interface can not be instantiated but can have reference variable. Interface can contain
only final and static datamembers as well as methods of abstract type, it means the
methods have to be overridden by child.
There is an interface means there must be a child class which has to override all
the methods of interface. If it will not override completely the it should be
abstract class and offers to form concrete class to override.
interface NAME
{
final static datamembers;
methods;
}
See the following sample program with one interface and two child implementing the
interface class.
interface Area
{
double Get(double x, double y);
}
class Circle:Area
{
//overriding interface method
public double Get(double x, double y)
{
return 3.14* x * x;
}
}
class Rect:Area
{
//overriding interface method
public double Get(double x, double y)
{
return x * y;
}
}
class InterfaceDemo
{
static void Main(string[] args)
{
//creating objects of child class
Rect r = new Rect();
Circle c = new Circle();
double k = r.Get(10.2, 12.9);
double l = c.Get(5.0,0);
Console.WriteLine("Area of rect= {0}", k);
Console.WriteLine("Area of circle= {0}", l);
}
}
OUTPUT
Area of rect=131.58
Area of circle=78.5
Combining Tables
A query result can include data from multiple tables. To combine data from
multiple tables, you can use the JOIN operation from SQL. The JOIN operation
matches the rows of one table with rows of another table, based on values in
those rows.
Types of JOIN
1. Inner Join
2. Outer Join
Left-Outer Join
Right-Outer Join
Full-Outer Join
3. Cross Join
INNER JOIN
SELECT table1.col, table1.col, table2.col, table2.col FROM table1 INNER JOIN table2 ON
table1.col = table2.col
It is a join that displays only the rows that have a match in both the joined
tables.
Columns containing NULL do not match any values when you are creating an
inner join and are excluded from the result set. NULL values do not match other
NULL values.
SELECT table1.col, table1.col, table2.col, table2.col FROM table1 LEFT OUTER JOIN table2
ON table1.col = table2.col
It is a join that includes rows even if they do not have related rows in the
joined table.
All rows from the first named table(the "left" table, which appears leftmost in the
JOIN clause) are included. Unmatched rows in the right table do not appear.
For every unmatched record a NULL value will appear for the rightmost table.
SELECT table1.col, table1.col, table2.col, table2.col FROM table1 RIGHT OUTER JOIN table2
ON table1.col = table2.col
It is a join that includes rows even if they do not have the related rows in the
joined table.
All the rows from the second-named table(the "right" table, which appears rightmost
in the JOIN clause) are included. Unmatched rows in the left table do not appear.
For every unmatched record a NULL value will appear in the leftmost table.
SELECT table1.col, table1.col, table2.col, table2.col FROM table1 FULL OUTER JOIN table2
ON table1.col = table2.col
It is a join that includes rows even if they do not have related rows in the
joined table.
All rows in all joined tables are included, whether they are matched or not.
For every unmatched record a NULL value will appear for the corresponding
table.
CROSS JOIN
It is a join whose result set includes one row for each possible pairing of rows from
the two tables.
Trigger
Syntax
trigger_name:- It is the name of the trigger. A trigger name must confirm to the rules
for identifiers and must be unique within the database.
table_name:- It is the name of the table on which the trigger is executed and is
sometimes called trigger table.
Example1:-
CREATE TRIGGER ti1 ON Student FOR INSERT AS Print 'Record inserted successfully' // This
will add trigger for insert operation in table student.
Firing a trigger
Example2:-
CREATE TRIGGER ti2 ON Student FOR INSERT AS select*from inserted
Inserted is a logical table and structure is similar to the table on which the
trigger is defined. That is the table on which the user action is attempted, and new values
of the rows that may be changed by the user action.
Name Roll
Abinash 107
1 row(s) affected
Syntax
Example1
Example2:-
Deleted is a logical table and the structure is similar to the table on which
the trigger is defined. That is, the table on which the user action is attempted, and the
old values of the rows that may be changed by the user action.
Name Roll
Abinash 107
1 row(s) affected
Syntax:-
Example1:-
CREATE TRIGGER tu1 ON Student FOR UPDATE AS 'Record updated successfully'
Example2:-
CREATE TRIGGER tu2 ON Student FOR UPDATE AS select*from deleted select*from inserted
Deleted and inserted are logical tables and are structurally similar to the
table on which the trigger is defined. That is, the table on which the user action is
attempted, and hold the old values and new values of the rows that may be changed by the
user action.
Name Roll
Abhisek 108
Name Roll
Abhisek Panda 108
1 row(s) affected
NB:- First you have to create and execute that trigger and then you have to fire it.
What is an object?
• Class is the general thing and object is the specialization of general thing
• Attribute
• Behavior
• Identity
1. What is an Attribute?
• Attributes define the characteristics of a class.
Example of Attribute:
2. What is a Behavior?
Example of Behavior:
3. What is an Identity?
• This identity is usually created using an identifier which is derived from the type of
item
Example of Identity:
The source code is attached at the top of this article.
sing System;
class SalaryCheque
_EmployeeName = name;
return _EmployeeName;
if (type == 1)
this._Amount = 50000;
if (type == 2)
this._Amount = 27000;
if (type == 3)
this._Amount = 5000;
}
public void DisplayCheque()
class SalaryChequeDisplay
string _name;
int _employeeType;
_name = Console.ReadLine();
_employeeType = Convert.ToInt16(Console.ReadLine());
objsal.EmployeeName(_name);
objsal.EmployeeType(_employeeType);
objsal.DisplayCheque();
}
Introduction
In order to store ordered list of items (objects), we can simply use an ArrayList, however
there are many disadvantages of using ArrayList particularly when you have a huge number
of objects into it. The most important is every time you need to cast them to get your actual
object and this itself is a big overhead on the application. Also there is no type safety
because you can store a string, an integer as well as a custom class into a single ArrayList
that will not throw any error at compile time but you will get an exception at runtime if you
were intended to store only integer in the ArrayList and were casting for integer object but
someone had added string type of data also.
The best solution in this scenario would be to restrict the type of object you are intended to
store in your collections at the time of declaration itself so that it won't accept any other
type of data.
Generics
The solution of the problem identified above can be solved by using is .NET Generics. In
.NET Framework generic type exist for most of the collection classes, however we will
discuss about generic type of ArrayList in this article. List class is the generic equivalent
of an ArrayList class.
As an ArrayList is used to add ordered list of object so the List class is. Additionally it is used
to create type-safe ordered list. Lets understand it by an example. Suppose we want to
store only integer value in our collection so we will create List object by specifying the
integer type for the generic parameter. For example
list.Add(1);
list.Add(2);
Notice the data type between less than and greather than symbol (<int>), this is how data
type is declared at the time of instantiating List object. In place of int you can use any type
of object, like string, datetime or your custom business objects etc.
When you compile above code it will complie properly. Now lets try to add some string into
it and compile. Notice the 4th line in the below code snippet.
list.Add(1);
list.Add(2);
list.Add("REA");
If you will try to compile, you will get following error (below picture) as I have passed int as
the generic parameter to the List object and trying to add a string value into it.
If this would have been an ArrayList it would have compiled properly however at run time
while casting this into integer it would have thrown error (as "REA" can't be converted into
integer) .
int intTotal = 0;
intTotal += i;
As against ArrayList, Generic list saves us from any potential exception that may occur at
runtime. As written earlier, List is the generic equivalant of ArrayList so almost all methods
that ArrayList supports (See http://www.dotnetfunda.com/articles/article140.aspx for
ArrayList article) are supported by List. Apart from that there are many overloads and extra
methods also that are very useful.
Useful Resources
There are few articles I came across that are very useful on this topic and I would like to
mention them for the benefits of the readers. Please feel free to respond to this article if you
have some useful resources on this topic.
http://www.ondotnet.com/pub/a/dotnet/2005/06/20/generics.html?page=2
http://www.developer.com/net/net/article.php/11087_3499301_2
http://msdn.microsoft.com/en-us/library/6sh2ey19(VS.80).aspx
This article describes about ArrayList, its various methods and uses. ArrayList is a simple
and resizable index-based collections of objects. This is a kind of array that is capable of
increase its size dynamically.
Introduction
In series of next few articles, I am planning to write about collections. Collections are a
place to store similar or different types of data in an orderly manner. .NET Framework
provide different type of collections for use at different places. Collections classes are the
base of application development because of the utility they provide to the developer.
There are several types of collections in .NET and all these collections classes resides in
System.Collections namespace.
This article describes about ArrayList (Read article on List, Generic equivalent of ArrayList
http://www.dotnetfunda.com/articles/article152.aspx) and where it best fits. ArrayList is a
simple and resizable index-based collections of objects. This is nothing but a kind of array
that is capable of increase its size dynamically. It can store any kind of data that inherit
from System.Object (In .NET all data types are inherited from System.Object so virtually
you can store any type of data into any collections.) ArrayList still uses array type to
implement most of its functionality. ArrayList best fits in the scenario where you don't know
what is the exact size of the items you are going to add in the collections, want to store
variable data irrespective of the data types and your collections are relatively small or
medium size.
Add Method
ArrayList supports two methods of adding items to the collections and these are Add and
AddRange. Add method is used to store any kind of data into the collections, it can either be
string, numeric or any custom objects.
// ArrayList
arrayList.Add("Sheo");
arrayList.Add(lastName);
arrayList.Add(31);
arrayList.Add(new object());
Here you can see that I have added variable, string, numeric or simple object into the
collections. In order to add object into an ArrayList, its not necessary to be of the same
type.
AddRange Method
In addition to Add method, ArrayList also supports AddRange method that is used to add
more than an item into the collection at one go. This is done usually from either an Array or
another collections.
arrayList.AddRange(items);
AddRange supports adding a range of items from any collections that support ICollection
interface (Infact most of the collections object supports this interface).
One important thing to notice here is that Add and ArrayList add items into the collection at
the end of it, what if you want to insert the items in the mid of the collection or at any
specific postions? To do that ArrayList supports Insert and InsertRange methods. These
methods works in the same way as Add and AddRange do but one more parameter you
need to pass into these methods is the postion at which you want to insert the item.
arrayList.Insert(3, "Dutta");
arrayList.InsertRange(7, insertItems);
Overwriting an item
If you want to overrite an item already in the ArrayList, you can use the indexers to do that.
The way we added the items into the ArrayList, we can remove the items from ArrayList
using Remove and RemoveRange methods. One additional method is provided by ArrayList
to remove an item is RemoteAt. Lets see them one by one
Remove Method
Remove method is used to remove a item from the collections. But notice that if you are
trying to remove an item that doesn't exist into the collections, ArrayList will not throw any
error, this is cool, isn't it?.
arrayList.Remove(31);
// ArrayList - Remove method, this will not throw any error even if this item doesn't exist in
the collection
arrayList.Remove("Unknown Item");
RemoveAt Method
In case you need to remove an item from a specific location from the ArrayList, you can use
RemoveAt method. In the following example, 4 item from the ArrayList will be removed.
arrayList.RemoveAt(4);
RemoveRange Method
If you want to remove more than one item from the ArrayList at one go, simply use the
RemoveRange method. In this method you need to specify from which index you want to
start with and how many items you want to remove. In following example 6th, 7th, and 8th
item will be removed from the ArrayList as I have specified first parameter from where to
start removing item is 5 (Actually it will be 6th item as collections are 0 based index and its
counting starts from 0) and from there 3 items will be removed.
arrayList.RemoveRange(5, 3);
// Demo of RemoveRange
myArrayList.AddRange(myInt);
myArrayList.RemoveRange(1, 3);
string str = string.Empty;
The output of above code will be 1, 5. As the first parameter is 1, it means the 2nd item ie.
2, and remove 3 items from there ie. 2, 3, 4.
You must be agree that if we will not have any option to iterate through the items of the
collections and get it back, it will be of hardly any use. ArrayList also provids way to iterate
through the items of the collections and there are many ways to do that.
Using Indexers
ArrayList has a Count property that tells us the size of the collections, we can use them to
loop through the ArryaList.
Using Enumerators
ArrayList also supports IEnumerable interface that allows us to use enumerators to access
the items of the collections.
while (enm.MoveNext())
ForEach loop is just like enumerators, actually internally it use Enumerators to enumerate
through all the items in the collections. The benefit of using ForEach loop is you can specify
the the data type while looping through the items that saves time in casting from objects
while looping.
// Generic - it will work for all types of object stored in the ArrayList
Sorting an ArrayList
ArrayList also supports sorting of the item. To sort the item simply call the Sort method.
This method also takes IComparer object as parameter if you want to use case insensitive
sorting or you want to specify your own comparer class to compare and sort.
arrayList.Sort();
myArrayList.Sort(new CaseInsensitiveComparer());
There are few more methods that are frequently used while working with ArrayList. These
are:
Clear Method
Clear method is used to clear all the item from the collections.
myArrayList.Clear();
IndexOf Method
// will return 1
myArrayList.IndexOf(5);
// Will return -1 as I have removed 2, 3, 4 has been removed from the list
myArrayList.IndexOf(3);
Hope this article will be useful for beginners as well as mid level developers. Please let me
know if you have comments or suggestions. Thanks for reading.
This article describes about most of the Value Types variables, its uses and how to use
them.
Introduction
Variables are of two types. Reference and Value types. In this article, we are going to cover
Value Types variables. Value types are variables that contain their actual data directly
instead of reference of the data stored elsewhere in the memory. Instances of value types
variables are stored in an area of memory called Stack. Stack is a place where runtime can
create, read, update and remove the data quickly.
Value types variables can be of two types. Build-in and User defined. Lets see each one of
them one by one.
There are many built-in value types variables and we can use them based on our
requirement.
sbyte
(System.SByte) 1 -128 to 127 Signed byte values
byte
(System.Byte) 1 0 to 255 Unsigned byte
short
(System.Int16) 2 -32768 to 32767 To store small number
int
(System.Int32) 4 –2147483648 to 2147483647 Whole numbers
uint
(System.UInt32) 4 0 to 4294967295 Only Positive whole nu
long –9223372036854775808 to
(System.Int64) 8 9223372036854770000 Large whole numbers
float
(System.Single) 4 –3.402823E+38 to 3.402823E+38 Floating point number
char
(System.Char) 2 Single unicode charac
Boolean
(System.Boolean) 4 True/False
Use of int and uint for variables are recommended as these variables are optimzed by
runtime. For floating point use double for the same reason.
int i = 0;
Here int is the data type of the variable, i is the name of the variable and 0 is the default
value I have used to initialize the variable.
There are situation where you don't want anything to store in the variable, in that case you
can go ahead with nullable variables.
Nullable<int> i = null;
int? ii = null;
Note that by default you can't assign null to a Value types variables, so if you are planning
to store null in the value types variables, you should declared them as nullable variables.
Now there is a question, how to know whether a nullable variable value has been set or not?
To do that use use following code.
User-defined types are also called sructs. According to MSDN, A struct type is a value type
that can contain constructors, constants, fields, methods, properties, indexers, operators,
events, and nested types. As with other value types, instances of user-defined types are
stored on the stack and they contain their data directly. Structures are a composite of other
types that make it easier to work with related data. Structs are used to represent light
weight object. Struct can't inherit a class but it can inherit an interface.
struct Person
firstName = _firstName;
lastName = _lastName;
}
Notice that I have not initialized the firstName and lastName variables in the struct, if you
do so it will throw error at compile time(Person.firstName': cannot have instance field
initializers in structs, in case you are trying to initialize firstName).
Enumerations
Enumerations are group of symbols that have fixed value. The enum keyword is used to
declare an enumeration, a distinct type consisting of a set of named constants called the
enumerator list.
enum tasteType
hot,
sour,
sweet,
salty
tasteType.hot
Enumerations simplifies the coding by providing limited set of options in readable and
understandable forat to the developers for a particular object.
Conclusion
In this article, we have gone through almost all Value types variables that are generally
used while developing applications. Hope you enjoyed this. Thanks for reading.
Working with Collections - Generic List
This article describes about List class that is generic equivalent of ArrayList class.
Introduction
In order to store ordered list of items (objects), we can simply use an ArrayList, however
there are many disadvantages of using ArrayList particularly when you have a huge number
of objects into it. The most important is every time you need to cast them to get your actual
object and this itself is a big overhead on the application. Also there is no type safety
because you can store a string, an integer as well as a custom class into a single ArrayList
that will not throw any error at compile time but you will get an exception at runtime if you
were intended to store only integer in the ArrayList and were casting for integer object but
someone had added string type of data also.
The best solution in this scenario would be to restrict the type of object you are intended to
store in your collections at the time of declaration itself so that it won't accept any other
type of data.
Generics
The solution of the problem identified above can be solved by using is .NET Generics. In
.NET Framework generic type exist for most of the collection classes, however we will
discuss about generic type of ArrayList in this article. List class is the generic equivalent
of an ArrayList class.
As an ArrayList is used to add ordered list of object so the List class is. Additionally it is used
to create type-safe ordered list. Lets understand it by an example. Suppose we want to
store only integer value in our collection so we will create List object by specifying the
integer type for the generic parameter. For example
list.Add(1);
list.Add(2);
Notice the data type between less than and greather than symbol (<int>), this is how data
type is declared at the time of instantiating List object. In place of int you can use any type
of object, like string, datetime or your custom business objects etc.
When you compile above code it will complie properly. Now lets try to add some string into
it and compile. Notice the 4th line in the below code snippet.
list.Add(1);
list.Add(2);
list.Add("REA");
If you will try to compile, you will get following error (below picture) as I have passed int as
the generic parameter to the List object and trying to add a string value into it.
If this would have been an ArrayList it would have compiled properly however at run time
while casting this into integer it would have thrown error (as "REA" can't be converted into
integer) .
intTotal += i;
As against ArrayList, Generic list saves us from any potential exception that may occur at
runtime. As written earlier, List is the generic equivalant of ArrayList so almost all methods
that ArrayList supports (See http://www.dotnetfunda.com/articles/article140.aspx for
ArrayList article) are supported by List. Apart from that there are many overloads and extra
methods also that are very useful.
Useful Resources
There are few articles I came across that are very useful on this topic and I would like to
mention them for the benefits of the readers. Please feel free to respond to this article if you
have some useful resources on this topic.
http://www.ondotnet.com/pub/a/dotnet/2005/06/20/generics.html?page=2
http://www.developer.com/net/net/article.php/11087_3499301_2
http://msdn.microsoft.com/en-us/library/6sh2ey19(VS.80).aspx
To efficiently write the code of Data Access Layer we must be aware about the
functionality/features of DataSet, SqlDataReader and XmlReader. In this article, I am trying
to describe which objects fits in what scenario.
Buy proven .NET Trainings on www.ITFunda.Com (Adv)
Introduction
When we need to retrive mutliple records from databsae, we have following options
1. DataSet or DataTable - use SqlDataAdapter to generate it
2. SqlDataReader - use it to provide read only, forward only data stream
3. XmlReader - use it to provide a read only, forward only data stream of XML data.
Use DataSet
1. We don't need to explicitly open or close the database connection as SqlAdapter Fill
method opens the database connection and then closes it before it returns. If the
connection is already open (before using it into SqlDataAdapter) then it leaves it as it is.
2. If we require the connection object to use it further then better to open the connection
before calling Fill method of SqlDataAdapter to avoid reopening it again.
Use SqlDataReader
1. We are dealing with large volumes of data - too much to maintain in single cache.
2. We want to reduce the memory occupied by the application (using DataSet consumes
memory)
3. We want to perform data binding with a control that supports a data source that
implements IEnumerable.
Use XmlReader
Conclusion
We generally do these activities on almost all projects, a little attention on what to use
when increases the performance of the overall project and increases the scalability.
Discussing Constructors in C#
In a simple words Constructor is nothing but a method, a special kind of method of a class,
which gets executed when its (class) object is created.
Now, let’s take above in broader sense, a constructor is a class method automatically
executed whenever class’s object is created or whenever class is initialized
Introduction
In a simple words Constructor is nothing but a method, a special kind of method of a class,
which gets executed when its (class) object is created.
Now, let’s take above in broader sense, a constructor is a class method automatically execut
ed whenever class’s object is created or whenever class is initialized.
public MsDotNetHeaven()
//Class members
What happened behind the scenes : whenever you try to create an object of class or
initialize a class, then the default constructor is invoked.
Types of Constructor
This is a n issue of debate but I always like to segregated Constructors in following types:
Default Constructor
A constructor that takes no parameters is called a default constructor. Default constructors
are invoked whenever an object is instantiated by using the new operator and no arguments
are provided to new.
Parameterized Constructor
Besides a default constructor when its need to pass some argument on the initialization of a
class a parameterized constructor is come to picture. It follows the same rules as default
constructor with a difference that it has some parameters which also differentiate it from
default constructor. Go through following snippet:
public MsDotNetHeaven()
//Class members
}
Note:
2. Some writer also take Private constructor and Static Constructor as types of
constructor but in my view these are constructor with different modifiers so behave
differ; I will cover these in next section.
By default Constructors are public but we can also use other modifiers and prefix like
private and static. With the use of these modifiers constructors behave differently:
When put private as access modifier to constructor then that constructor is known as
private Constructor
Some time there is a need where we have not allow outer world to get instantiate our class
then we need to use private modifier with constructor. Consider following piece of code:
private MsDotNetHeaven()
//Class members
}
Now, question comes to mind if the above contains error then what the use is of private
constructor, we can make above class to be initialized by declaring another public
constructor, modify above code-snippet with bellow one:
private MsDotNetHeaven()
//Class members
With the use of static with constructor gives a name as static constructor
static MsDotNetHeaven()
//Class members
Now whenever you create an instance of the class MsDotNetHeaven the line I am a static
constructor get printed.
static MsDotNetHeaven()
public MsDotNetHeaven()
{
//Class members
Above code is perfectly alright and will perform same result as earlier code.
Now, suppose a scenario when you are inheriting a class and want to use Parent class
constructor then how to attain that.
public MsDotNetHeaven()
//Class members
public MsDotNetMentor ()
//Class members
(A) From above : the sequence of invoking a constructor is first public MsDotNetHeaven()
and then public MsDotNetMentor()
Note:
Important :
• Constructor is nothing but a special method, which initializes the class or its task to
initialize the object of it class.
• This is a special method as constructors do not have return types, not even void
• Constructor cannot return any value because they didn’t have any return type.
• Constructor can’t be get inherited, although a derived class can class the base class
constructor.
• A class has atleast one constructor also known as default constructor [a constructor
without parameter]