private void file_write()
{
string path="D:\\Temp\\My Documents\\"; // Parent Directory
string name=TextBox1.Text;
string ext=".txt";
string fname=path+name+ext;
FileInfo file1=new FileInfo(fname);
StreamWriter sw=file1.CreateText();
sw.WriteLine("This is a demo for writing to a text file"); // Writing a string directly to the file
sw.WriteLine(TextBox2.Text); // Writing content read from the textbox in the form
sw.Close();
}
private void file_read()
{
string path="D:\\Temp\\My Documents\\"; // Parent Directory
string name=TextBox1.Text;
string ext=".txt";
string fname=path+name+ext;
string readcontent;
FileInfo file1=new FileInfo(fname);
StreamReader sr=new StreamReader(file1);
readcontent=sr.ReadToEnd(); // Reading content from the file and storing to a string
sr.Close();
TextBox2.Text=readcontent; // Display contents in a textbox in the form
}
private void file_append()
{
string path="D:\\Temp\\My Documents\\"; // Parent Directory
string name=TextBox1.Text;
string ext=".txt";
string fname=path+name+ext;
FileInfo file1=new FileInfo(fname);
StreamWriter sw=File.AppendText(file1)
sw.WriteLine("This is a demo for appending text content to a file");
// Writing a string directly to the file
sw.WriteLine(TextBox2.Text); // Writing content read from the textbox in the form
sw.Close();
}
There are couple of advantage of LINQ over stored procedures.
1. Debugging - It is really very hard to debug the Stored procedure but as LINQ is part of .NET, you can use visual studio's debugger to debug the queries.
2. Deployment - With stored procedures, we need to provide an additional script for stored procedures but with LINQ everything gets complied into single DLL hence deployment becomes easy.
3. Type Safety - LINQ is type safe, so queries errors are type checked at compile time. It is really good to encounter an error when compiling rather than runtime exception!
private DataTable getmyDatatable()
{
DataTable dt = new DataTable();
DataColumn dc;
dc = new DataColumn("Name");
dt.Columns.Add(dc);
dc = new DataColumn("Age");
dt.Columns.Add(dc);
dc = new DataColumn("Address");
dt.Columns.Add(dc);
dc = new DataColumn("Phone");
dt.Columns.Add(dc);
//dc = new DataColumn("Sex");
//dt.Columns.Add(dc);
dc = new DataColumn("Name");
dt.Columns.Add(dc);
dc = new DataColumn("Age");
dt.Columns.Add(dc);
dc = new DataColumn("Address");
dt.Columns.Add(dc);
dc = new DataColumn("Phone");
dt.Columns.Add(dc);
dc = new DataColumn("Sex");
dt.Columns.Add(dc);
string strchklist = "";
foreach (ListItem li in ChkAddress.Items)
{
if (strchklist == "")
{
if (li.Selected)
{
strchklist = li.Text;
}
}
else
{
if (li.Selected)
{
strchklist += "," + li.Text;
}
}
}
1. What is an IL?
(IL)Intermediate Language is also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language). All .NET source code is compiled to IL. IL is then converted to machine code at the point where the software is installed, or at run-time by a Just-In-Time (JIT) compiler.
2. What is a CLR?
Full form of CLR is Common Language Runtime and it forms the heart of the .NET framework.All Languages have runtime and it is the responsibility of the runtime to take care of the code execution of the program. For example, VC++ has MSCRT40.DLL, VB6 has MSVBVM60.DLL,and Java has Java Virtual Machine etc. Similarly, .NET has CLR. Following are the responsibilities of CLR
• Garbage Collection: - CLR automatically manages memory thus eliminating memory leaks. When objects are not referred, GC automatically releases those memories thus providing efficient memory management.
• Code Access Security: -
• Code Verification: -
• IL (Intermediate language)-to-native translators and optimizer’s:-
3. What is CTS?
In order that two language communicate smoothly CLR has CTS (Common Type System).Example in VB you have “Integer” and in C++ you have “long” these datatypes are not compatible so the interfacing between them is very complicated. In order that these two different languages communicate Microsoft introduced Common Type System. So “Integer” data type in VB6 and “int” data type in C++ will convert it to System.int32, which is data type of CTS. CLS,which is covered in the coming question, is subset of CTS.
4. What is a CLS?
This is a subset of the CTS, which all .NET languages are expected to support. It was always a dream of Microsoft to unite all different languages in to one umbrella and CLS is one-step towards that. Microsoft has defined CLS, which are nothing but guidelines, that language should follow so that it can communicate with other .NET languages in a seamless manner.
5. What is a Managed Code?
Managed code runs inside the environment of CLR i.e. .NET runtime. In short, all IL are managed code. However, if you are using some third party software example VB6 or VC++ component they are unmanaged code, as .NET runtime (CLR) does not have control over the source code execution of these languages.
6. What is an Assembly?
An assembly is the primary building block of a .NET application and can take the form of a dynamic link library (DLL) or executable file (EXE). An assembly is a collection of functionality that is built, versioned, and deployed as a single implementation unit.
A .NET assembly may contain the following elements:
Assembly Manifest – Metadata that describes the assembly and its contents (see below)
Source Code – Compiled into Microsoft intermediate language (MSIL)
Type Metadata – Defines all types, their properties and methods, and most importantly, public types exported from this assembly
Resources – Icons, images, text strings and other resources
7. What are the different types of Assembly?
There are two types of assembly Private and Public assembly. A private assembly is normally used by a single application, and is stored in the application's directory, or a sub-directory beneath. A shared assembly is normally stored in the global assembly cache, which is a repository of assemblies maintained by the .NET runtime. Shared assemblies are usually libraries of code,which many applications will find useful, e.g. Crystal report classes that will be used by all application for Reports.
8. What is Namespace?
Namespaces allow to group entities like classes, objects and functions under a name. System is the basic namespace used by every .NET code. If we can explore the System namespace little bit, we can see it has lot of namespace user the system namespace. For example, System.Io, System.Net, System.Collections, System.Threading, etc.
9. What is GAC?
GAC (Global Assembly Cache) is where all shared .NET assembly reside. GAC is used in the following situations:-
• If the application has to be shared among several application.
• If the assembly has some special security, requirements like only administrators can remove the assembly. If the assembly is private then a simple delete of assembly the assembly file will remove the assembly.
10. Can we force garbage collector to run?
System.GC.Collect () forces garbage collector to run.
11. What is reflection?
All .NET assemblies have metadata information stored about the types defined in modules. This metadata information can be accessed by mechanism called as “Reflection”. System. Reflection can be used to browse through the metadata information.
12. What are Value types and Reference types?
Value types: -They directly contain data. When you declare an int variable, the system allocates memory to store the value.
Reference type: -The reference types do not maintain data but they contain a reference to the variables, which are stored in memory. This means that if the value in the memory location is modified by one of the variables, the other variables automatically reflect the changes value
13. What is concept of Boxing and Unboxing?
Boxing converts a value-type to a reference-type, thus storing the object on the heap.
Unboxing converts a reference-type to a value-type, thus storing the value on the stack.
Remoting and Web services
1. What is an application domain?
An Application Domain is a light weight process and provides a logical and physical isolation from another .NET application. This ensures that the Applications can work independent and isolated of each other. An Application Domain is created by the Common Language Runtime (CLR) and it ensures that if one Application Domain crashes or goes down, it does not in any way effect the functioning of another Application Domain. Multiple .NET applications can be executed in one single process by loading these applications in separate Application Domains.The following are the benefits of Application Domains.
· Isolation of code, data and configuration information of one application from another
· A failure in one application will not affect the other
2. What is a Web Service?
The term Web services describes a standardized way of integrating Web-based applications using the XML, SOAP, WSDL and UDDI open standards over an Internet protocol backbone. XML is used to tag the data, SOAP is used to transfer the data, WSDL is used for describing the services available and UDDI is used for listing what services are available.
3. Isolation? LOW (IIS process):- In this main IIS, process, and ASP.NET application run in same process.So if any one crashes the other is also affected. Example let us say (well this is not possible) I have hosted yahoo, hotmail .amazon and goggle on a single PC. So all application and the IIS process runs on the same process. In case any website crashes, it affects every one.
Medium (Pooled):- In Medium pooled scenario, the IIS, and web application run in different process. Therefore, in this case there are two processes process1 and process2. In process1, the IIS process is running and in process2, we have all Web application running.
High (Isolated):-In high isolated scenario every process is running is there own process. In below figure here are five processes and every one handling individual application. This consumes heavy memory but has highest reliability.
Caching Concepts
1. What is View State?
View state is a built-in structure for automatically retaining values amongst the multiple requests for the same page. The view state is internally maintained as a hidden field on the page but is hashed, providing greater security than developer-implemented hidden fields do.
2. What does the "EnableViewState" property do?
IT keeps the data of the control during post backs. If we turn off the values should not populate during server round trip.
3. What is Caching?
Caching enables you to store the expensive data into Cache object and later retrieve it without doing expensive operations. Caching is a technique of persisting the data in memory for immediate access to requesting program calls. Many in the developer community consider caching as one of the features available to improve performance of Web applications.
OOPS
1. What is a Class?
A class describes all the attributes of objects, as well as the methods that implement the behavior of member objects.
2. What is an Object?
They are instance of classes. It is a basic unit of a system. An object is an entity that has attributes, behavior, and identity.
3. What are abstract classes?
We cannot create an object of abstract class. Abstract classes are similar to interfaces. After declaring an abstract class, it cannot be instantiated on its own, it must be inherited. Abstract class is designed to act as a base class. A class can only implement one abstract class only due non-existence of Multi-inheritance in C#.
Public abstract Animal
{
Public void eat (Food food)
{
// do something with food....
}
Public abstract void makeNoise ();
}
Public Dog extends Animal
{
Public void makeNoise ()
{
System.out.println ("Bark! Bark!") ;
}
}
Public Cow extends Animal
{
Public void makeNoise ()
{
System.out.println ("Moo! Moo!") ;
}
}
4. What is an Interface?
An interface contains only the signatures of methods, delegates or events. An interface is a group of related methods with empty bodies.
Class ACMEBicycle implements Bicycle {
// remainder of this class implemented as before
}
5. What is difference between abstract classes and interfaces?
•Abstract classes can have concrete methods while interfaces have no methods
implemented.
• Interfaces do not come in inheriting chain, while abstract classes come in
inheritance.
• You can only inherit one base class, but you can implement multiple interfaces
• Interfaces can only define the API (method signatures, event declarations, property declarations), not the implementation (fields, method bodies, etc)
6. What is a delegate?
A delegate can be defined as a type safe function pointer. You use delegates to call the methods of other objects. A delegate actually stores the address of a method that is contained in some other class. So, a delegate is really the equivalent of a function pointer in C++.
A delegate is basically a reference to a method. A delegate can be passed like any other variable. This allows the method to be called anonymously, without calling the method directly.
In C#, delegates are the basis for events.
For example: A object can create a delegate that refers to one of its private methods. Then the object can pass that delegate to another object. The second object could then call that private method without knowing anything about it (loose-binding).
7. What are Events?
Events are the actions of the system on user manipulations (e.g. mouse clicks, key press etc.) or any event triggered by the program.
An event is basically a list of delegates. Technically, it is a multicast delegate. However, the event keyword allows the compiler to encapsulate the delegate to control how it is accessed.
The object that has the event is called the publisher. The object that handles the event is called the subscriber. An event allows a publisher to call a subscriber's event handler without knowing anything about the subscriber.
For example, a Button object with a Click event can call all the ClickEventHandlers without knowing the class or method names which handle the event.
It is the subscriber's responsibility to subscribe to the event. The publisher simply raises the event at the appropraite time. Whenever the event is raised, each delegate that is in the event's list will be called.
8. What is the difference between delegate and events?
• Actually, events use delegates in bottom. But they add an extra layer on the delegates,thus forming the publisher and subscriber model.
• As delegates are function to pointers, they can move across any clients. So any of the clients can add or remove events, which can be confusing. But events give the extra protection by adding the layer and making it a publisher and subscriber model.
An event offers more restricted access than a delegate. When an event is public, other classes are only able to add or remove handlers for that event: such classes cannot—necessarily—fire the event, locate all the handlers for it, or remove handlers of which they are unaware.
Further, events are more flexibile in terms of how handlers are stored.
9. Can you prevent a class from overriding?
If you define a class as “Sealed” in C
10. What does virtual keyword mean?
They signify that method and property can be overridden.
11. Differentiate Dispose and Finalize.
Dispose method is used to release unmanaged resources when unmanaged resources are no longer in use and referenced and is manually called by the programmer
Finalize is called by the Garbage Collector, and the state of manage objects cannot be guaranteed, so we cannot reference them. Also, we cannot determine when the GC will run, and which objects it will Finalize.
Dispose is called by the programmer, and is used to dispose of managed and unmanaged objects. Within we dispose method, we release all of our resources and call GC.SuppressFinalize as we have done the work of the GC.
12. What is the use of “Overrides” and “Overridable” keywords?
Overridable is used in parent class to indicate that a method can be overridden. Overrides is used in the child class to indicate that you are overriding a method
13. What is Array List?
Array is whose size can increase and decrease dynamically. Array list can hold item of different types. As Array list can increase and decrease size dynamically you do not have to use the REDIM keyword. You can access any item in array using the INDEX value of the array position.
14. What is a Hash Table?
You can access array using INDEX value of array, but how many times you know the real value of index. Hashtable provides way of accessing the index using a user identified KEY value, thus removing the INDEX problem.
15. What are queues and stacks?
Queue is for first-in, first-out (FIFO) structures. Stack is for last in, first-out (LIFO) structures.
16. What is ENUM?
It is used to define constants.
ASP.NET
1. What’ is the sequence in which ASP.NET events are processed?
• Page_Init.
• Page Load.
• Control events
• Page- Unload event.
2. What is event bubbling?
Event Bubbling is nothing but events raised by child controls is handled by the parent control.Server Controls like DataGrid,DataGridView , DataList etc have other controls inside them. Example an DataGridView can have an TextBox or an button inside it. These Child Controls cannot raize events by themselves,but they pass the event to the parent control (DataGridView), which is passed to the page as "ItemCommand" event.
This process is known as EventBubling
3. What is AppSetting Section in “Web.Config” file?
Web.config file defines configuration for a web project. Using “AppSetting” section, we can define user-defined values. Example below defined is “Connection String” section, which will be used through out the project for database connection.
4. Where is View State information stored?
In HTML Hidden Fields.
5. Can you explain “AutoPostBack”?
If we want the control to automatically post back in case of any event, we will need to check this attribute as true. Example on a Combo Box change we need to send the event immediately to the server side then set the “AutoPostBack” attribute to true.
6. What is the use of “GLOBAL.ASAX” file?
It allows to execute ASP.NET application level events and setting application-level variables.
7. What is the difference between ‘Server. Transfer’ and ‘response. Redirect’?
‘Response.Redirect’ sends message to the browser saying it to move to some different page,while server. Transfer does not send any message to the browser but rather redirects the user directly from the server itself. So in ‘server.transfer’ there is no round trip while ‘response.redirect’ has a round trip and hence puts a load on server.
NET Architecture
1. What is MVC pattern?
The main purpose using MVC pattern is to decouple the GUI from the Data. It also gives the ability to provide multiple views for the same Data. MVC pattern separates objects in to three important sections:-
• Model: - This section is specially for maintaining data. It is actually where your business logic, querying database, database connection etc. is actually implemented. • Views: - Displaying all or some portion of data, or probably different view of data. View is responsible for look and feel, Sorting, formatting etc. • Controller: - They are event-handling section, which affects either the model or the view. Controller responds to the mouse or keyboard input to command model and view to change. Controllers are associated with views. User interaction triggers the events to change the model, which in turn calls some methods of model to update its state to notify other registered views to refresh their display.
2. What is three-tier architecture?
There are three layers when we talk about three-tier architecture:- User Interface (Client):- This is mostly the windows user interface or the Web interface but this has only the UI part. Mid layer: - Middle tier provides process management where business logic and rules are executed and can accommodate hundreds of users (as compared to only 100 users with the twotier architecture) by providing functions such as queuing, application execution, and database staging. Data Access Layer: - This is also termed by the famous acronym "DAL" component. It has mainly the SQL statement which do the database operation part of the job.
3. What is difference between dataset and data reader?
• Data Reader provides forward-only and read-only access to data, while the Dataset object can hold more than one table (in other words more than one row set) from the same data source as well as the relationships between them.
• Dataset is a disconnected architecture while data reader is connected architecture.
• Dataset can persist contents while data reader cannot persist contents, they are forward only.
• However, one of the biggest drawbacks of Dataset is speed. As “Dataset” carry considerable overhead because of relations, multiple table’s etc speed is slower than “Data Reader”.
4. What are major difference between classic ADO and ADO.NET?
• In ADO we have recordset and in ADO.NET we have dataset.
• In recordset we can only have one table. If we want to accommodate more than one tables we need to do inner join and fill the recordset. Dataset can have multiple tables.
• All data persist in XML as compared to classic ADO where data persisted in Binary format also.
5. Web garden ?
A Web garden is configured on a single server by specifying multiple worker processes for an application pool. Web farms use multiple servers for a Web site.
Interface
An interface is a contract: the guy writing the interface say "hey, I accept things looking that way", and the guy using the interface say "OK, the class I write looks that way". And interface is an empty shell, there are only the signatures (name / params / return type) of the methods. The methods do not contain anything. The interface can't do anything. It's just a pattern.
E.G (pseudo code):
// I say all motor vehicles should look like that :interfaceMotorVehicle{void run();int getFuel();}// my team mate complies and write vehicle looking that wayclassCarimplementsMotoVehicle{int fuel;void run(){print("Wrroooooooom");}int getFuel(){returnthis.fuel;}}
Implementing an interface consume very little CPU, because it's not a class, just a bunch of names, and therefor there is no expensive lookup to do. It's great when it matters such as in embedded devices. Abstract classes
Abstract classes, unlike interfaces, are classes. There are more expensive to use because there is a lookup to do when you inherit from them.
Abstract classes look a lot like interfaces, but they have something more : you can define a behavior for them. It's more about a guy saying "these classes should look like that, and they got that in common, so fill in the blanks !".
e.g:
// I say all motor vehicles should look like that :abstractclassMotorVehicle{int fuel;// they ALL have fuel, so why let others implement that ?// let's make it for everybodyint getFuel(){returnthis.fuel;}// that can be very different, force them to provide their// implementationabstractvoid run();}// my team mate complies and write vehicle looking that wayclassCarextendsMotorVehicule{void run(){print("Wrroooooooom");}}
Interface:
Every single Method declared in an Interface will have to be implemented in the subclass. Only Events, Delegates, Properties (C#) and Methods can exist in a Interface. A class can implement multiple Interfaces.
Abstract Class Only Abstract methods have to be implemented by the subclass. An Abstract class can have normal methods with implementations. Abstract class can also have class variables beside Events, Delegates, Properties and Methods. A class can only implement one abstract class only due non-existence of Multi-inheritance in C#.
interfaces can have no state or implementation
a class that implements an interface must provide an implementation of all the methods of that interface
abstract classes may contain state (data members) and/or implementation (methods)
abstract classes can be inherited without implementing the abstract methods (though such a derived class is abstract itslef)
interfaces may be multiple-inherited, abstract classes may not (this is probably the key concrete reason for interfaces to exist separately from abtract classes - they permit an implementation of multiple inheritance that removes many of the problems of general MI).
QUESTIONS:
What is the point of creating a class that can't be instantiated?
Why would anybody want such a class?
What is the situation in which abstract classes become NECESSARY?
most commonly to serve as a base-class or interface (some languages have a separate interface construct, some don't) - it doesn't know the implementation (that is to be provided by the subclasses / implementing classes)
abstraction and re-use
when the base-class can provide no meaningful default-implementation for a method (but allowing subclasses to re-use the non-abstract parts of the implementation; any fields, non-abstract methods, etc)
That interview question reflects a certain belief of the person asking the question. I believe that the person is wrong, and therefore you can go one of two directions.
Give them the answer they want.
Respectfully disagree.
The answer that they want, well, the other posters have highlighted those incredibly well. Multiple interface inheritance, the inheritance forces the class to make implementation choices, interfaces can be changed easier.
However, if you create a compelling (and correct) argument in your disagreement, then the interviewer might take note. First, highlight the positive things about interfaces, this is a MUST. Secondly, I would say that interfaces are better in many scenarios, but they also lead to code duplication which is a negative thing. If you have a wide array of subclasses which will be doing largely the same implementation, plus extra functionality, then you might want an abstract class. It allows you to have many similar objects with fine grained detail, whereas with only interfaces, you must have many distinct objects with almost duplicate code.
Interfaces have many uses, and there is a compelling reason to believe they are 'better'. However you should always be using the correct tool for the job, and that means that you can't write off abstract classes.
In C#, interfaces are distinct from classes (even abstract classes);
interfaces can only define the API (method signatures, event declarations, property declarations), not the implementation (fields, method bodies, etc)
you can only inherit one base class, but you can implement multiple interfaces
But they have similarities in some usages - for example when used in an abstract factory implementation.
Let's take your example of a Dog and a Cat class, and let's illustrate using C#:
Both a dog and a cat are animals, specifically, quadruped mammals (animals are waaay too general). Let us assume that you have an abstract class Mammal, for both of them:
public abstract class Mammal
This base class will probably have default methods such as:
* Hunt
* Feed
* Mate
All of which are behavior that have more or less the same implementation between either species. To define this you will have:
public class Dog : Mammal
public class Cat : Mammal
Now let's suppose there are other mammals, which we will usually see in a zoo:
public class Giraffe : Mammal
public class Rhinoceros : Mammal
public class Hippopotamus : Mammal
This will still be valid because at the core of the functionality, Hunt(), Feed() and Mate() will still be the same.
However, giraffes, rhinoceros, and hippos are not exactly animals that you can make pets out of. That's where an interface will be useful:
The implementation for the above contract will not be the same between a cat and dog; putting their implementations in an abstract class to inherit will be a bad idea.
Your Dog and Cat definitions should now look like:
public class Dog : Mammal, IPettable public class Cat : Mammal, IPettable
Theoretically you can override them from a higher base class, but essentially an interface allows you to add on only the things you need unto a class without the need for inheritance.
Consequently, because you can usually only inherit from one abstract class (in most statically typed OO languages that is... exceptions include C++) but be able to implement multiple interfaces, it allows you to construct objects in a strictly as required basis.
link|edit|flag
"EXCEPTION IS A RUNTIME ERROR WHICH ARISES BECAUSE OF ABNORMAL CONDITION IN A CODE SEQUENCE. "
The try block contains the code segment expected to raise an exception. This block is executed until an exception is thrown The catch block contains the exception handler. This block catches the exception and executes the code written in the block. If we do not know what kind of exception is going to be thrown we can simply omit the type of exception.
The finally block is used to do all the clean up code. It does not support the error message, but all the code contained in the finally block is executed after the exception is raised. We can use this block along with try...catch and only with catch too. The finally block is executed even if the error is raised. Control is always passed to the finally block regardless of how the try blocks exits.
There are a number of exception classes provided by C#, all of which inherit from the System.Exception class. Following are some common exception classes:
Exception Class - - Cause
SystemException - A failed run-time check;used as a base class for other.
AccessException - Failure to access a type member, such as a method or field.
ArgumentException - An argument to a method was invalid.
ArgumentNullException - A null argument was passed to a method that doesn't accept it.
ArgumentOutOfRangeException - Argument value is out of range.
ArithmeticException - Arithmetic over - or underflow has occurred.
ArrayTypeMismatchException - Attempt to store the wrong type of object in an array.
BadImageFormatException - Image is in the wrong format.
CoreException - Base class for exceptions thrown by the runtime.
DivideByZeroException - An attempt was made to divide by zero.
FormatException - The format of an argument is wrong.
IndexOutOfRangeException - An array index is out of bounds.
InvalidCastExpression - An attempt was made to cast to an invalid class.
InvalidOperationException - A method was called at an invalid time.
MissingMemberException - An invalid version of a DLL was accessed.
NotFiniteNumberException - A number is not valid.
NotSupportedException - Indicates sthat a method is not implemented by a class.
NullReferenceException - Attempt to use an unassigned reference.
OutOfMemoryException - Not enough memory to continue execution.
Now you have added the connection string in the web.config file. Let's see some code that we can use to access the database. We want to load some data from the database when the page is loaded for the first time.
private void Page_Load(object sender, System.EventArgs e) { if(!Page.IsPostBack) { string connectionString = (string) ConfigurationSettings.AppSettings["ConnectionString"]; SqlConnection myConnection = new SqlConnection(connectionString); SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Categories",myConnection); DataSet ds = new DataSet(); ad.Fill(ds,"Categories"); myDataGrid.DataSource = ds; myDataGrid.DataBind(); } }
First, we check that if it's not a postback we load data. For this example to work you need to add the namespace: using System.Configuration;
Let's see what is going on here:
1) string connectionString receives the string from the web.config file which is referred by the "ConnectionString" key we set in the web.config file.
2) We make the object of the SqlConnection class which deals with SQL Server databases.
3) We made the data adapter object. Data adapter is a kind of connection to the database. In the data adapter object we specify that what we want from the database. In this case we want all the rows of the Categories table.
NOTE:
Always use stored procedures for accessing the data. Accessing or running Ad-hoc queries are dangerous as they are open for SQL Injections.
4) Next we made an instance of the DataSet class. DataSet will contain the result of the SqlDataAdapter even if the database connection is not made.
5) Later, we filled the dataset with the data using dataadapter.
6) And finally we assigns the datagrid to the dataset and binds it on the screen.
Pretty simple right?
In the code above we are using the SqlCommand object and stored procedure. You might have noted SqlDataReader, if you want to merely iterate through the database rows and select them its best to use SqlDataReader since its much faster than DataSet.
Finally we catch exceptions if any of them are generated and closes the connection.
Elements That Are Not Types
The following programming elements do not qualify as types, because you cannot specify any of them as a data type for a declared element:
Namespaces
Modules
Events
Properties and procedures
Variables, constants, and fields
An example
This example shows the difference between how a value type works in memory, and how a reference does. First we define a newValue Typeand a newReference Type.
class ReferenceType
{public Int32 X;
}
struct ValueType
{public Int32 X;
}
Now we want to use these types to show how they work:
ReferenceType ref1 = new ReferenceType();
ValueType val1 = new ValueType();
ref1.X = 5;
val1.X = 5;
The layout of the memory at this point looks something like the following:
If we now make copies of these values using the following code:
ReferenceType ref2 = ref1;
ValueType val2 = val1;
The layout of the memory now looks something like the following:
If we now change the value of each of the new copies using the following code:
Ref2.X = 8;
Val2.X = 8;
The layout of the memory now looks something like the following:
A variable that is of type value directly contains a value. Assigning a variable of type value to another variable of type value COPIES that value.
A variable of type reference, points to a place in memory where the actual object is contained. Assigning a variable of type reference to another variable of type reference copies that reference (it tells the new object where the place in memory is), but does not make a copy of the object.
Value types are stored on the stack.
Reference types are stored on the heap.
Value types can not contain the valuenull.*
Reference types can contain the valuenull.
Value types have a default implied constructor that initializes the default value.
Reference types default to anullreference in memory.
Value types derive fromSystem.ValueType.
Reference types derive fromSystem.Object.
Value types cannot derive a new type from an existing value type, but they are able to implement interfaces.
Reference types can derive a new type from an existing reference type as well as being able to implement interfaces.
Changing the value of one value type does not affect the value of another value type.
Changing the value of one reference type MAY change the value of another reference type.
Thenullable type(only in .NET 2.0) can be assigned the valuenull.