Saturday, August 18, 2007

WebConfig

web.config is an XML-based configuration file.
The root element of a web.config file is always a tag.
The tag contains three different types of elements:
1) configuration section handler declarations
2) configuration section groups
3) configuration section settings.

1) Appsettings
2) Authentication
3) Authorization
4) Compilation
5) CustomErrors
6) Globalization
7) Identity
8) MachineKey
9) Pages
10) ProcessModel
11) SessionState
12) Trace


AuctionAds

Remoting

Dcom replacement is Remoting.
Use remoting for more efficient exchange of information when you control both ends of the application.
Remoting is designed to .Net to .Net Communication.

Remoting object calls different Application Domains.Remote objects runs in different process client calling the remote object can't call it directly. so they uses proxy.

Namespace::: System.MarshllbyRefObject.

Remoting depends on
1) Channels
tcp(transaction commit protocol) data representation.
http(hypertext transperprotocol) xmlbased syntax
2) Serialization & DeSerailization
Coverting object into stream Serialization
Reading the stream and constuction object is Deserialization.
3)Formatter classes
Binaryformatter::: it is used by tcp channel
Soap formatter:::: it is used by http channel

NameSpace:::: System.Runtime.Serialization.Formatters.Binay/soap

Serialize(object,stream)
DeSerialize(Stream)
4)Activation modes
client activated and serveractivated.

Serveractivated:: when user makes a call to the method of class, the object creation takes place.
client activated:: whenever the client request comes to the remote server an object will be created and the reference will be send to client application.

Client activated objects maintain state.

Marshal byvalue:: when the client request comes, object will be created on the server machine. This object will be send to client machine.

Marshl byReferece:: when the client request comes, object will be created on the server machine. This object reference will be send to client machine.

Singlecall:: When user makes a call to the method, the object will be created, after sending the response the object will be destroy.This is stateless.
For single cleint we have single object.

SingleTon:: This will maintain single object for all the clients at a time. The lifetime will be 5 min by default.

client can be created objects on the server by two ways, one is using Keyword "NEW" and seconde one is "Activator.CreateInstace().


Try AuctionAds

WebServices

Communication between different business partners is possible by using webservices.way of invoking a remote method over http connection soap.Remote procedure call is based on soap protocal.Description will be generated using wsdl, which is xml format.Transmission is through xml based.Transmission protocal is http.

Webservices do not have any state. Webservices can access Asp.Net intrinsic objects like session, application.
Webservices are completely open standards.
To expose each method as a webservice,u simply add [Webmethod] attribute before it.
WSDL::::: Is a language derived from xml syntax. wsdl discribes the methods names, parameters, location of the webservice and standards for request and response.
To view the wsdl content typ like
http://localhost/WSCalculator/Service1.asmx?wsdl

To Create the Proxy for the clientwsdl
http://localhost/WSCalculator/Service1.asmx?wsdl

Togenerate proxy for the client application in the form of xmlfile is by soap.
soapsuds -ia:RemotingServer -oa:ClientProxy.dll
soapsuds -ia:RemotingServer -os:ClientProxy.xml

ia::: input Assembly
oa:: Output Assembly
os:: output stream

Proxy code will contain complete logic for interacting with webservice for method calls.

Namespace:: System.Web.Servicesif includes
1)webservice 2) webservice attribute class and 3) webmethod

The extension is asmx.

Webpage::: Provide consumption of data, This will for enduser.
Webservice::: Provide consumption of logic, This will for Developer.

When we want to reduce number of interactions between werbservice method and database server applying catching for the webmethod.

Webservices supports only textbased format.
ie, http-GET
http-Post Soap

Http-Get and Http-Post supports basic datatypes only.Soap supports complex datatypes like arrays and userdefined types.Soap will define standards for exchanging data between client and webservice interms of request and response.It is not vendor specific, it is xml standard, introduced in 99-2000.


AuctionAds: Increase the bid on your site's income!

Wednesday, August 15, 2007

ASPNET

ASP.NET

1. ASP .NET enables you to access any datasource ie., DB,text,XML files.
2. ASP .Net enables you to use programming code called templates. Which can be customized according to the data that we retrieve from the database.
3. ASP .NET enalbes you to bifurcate the logical code and the Interface into different files which further the logical file will be compiled into an DLL(Dynamic Link Library).


All Web Forms will interact with the state management which has the following components. These components are used to access the webforms for multi sessions.

Web.config is the main file which will hold the info about the application and the security info.

webservices are meant for writing the logical files and deploy to any type of application ie., windows based or web based.

These components internally interact with .netframework base class called (System) and internally calls Common Language Runtime(CLR).

Features of ASP.NET
1. Compiled Code
2. Enriched Tool Support
3. Power and Flexibility
4. Simplicity
5. Manageability
6. Scalability
7. Security

1. The code wrriten in ASP .NET gets compiled by the CLR but it will not be interpreted, unlike ASP.
2.It has fully gaphical support the way we design the same output will be seen after compilation ie., WYSIWYG(What You See Is What You Get)
3.The ASP. NET is compiled by the CLR for faster execution and it can interpret any language of source code.
4.It is very simple in programming as it is going to implement IDE(Integrated Devdelopment Environment)
5.It is vey easy to manage as the code is seperated from the HTML interface.
6.It can be run on multiprocess.
7. It provides security for the web pages so that anonymous user will not access the web page.

PROGRAMMIING MODELS
1. WebForm
2. WebServices

1. We will find the Interface designed in the webforms which will have an extension .aspx(Acitve Server Page extensions)
2. This will contain only the logic which is accessed only through the web sever and can be implemented in window based applicaiton as well as web based applicaiton.

Page Events
1.Init
2.Load
3.Control
4.UnLoad

1. This event is fired when the page is loaded to initialize all the member
variables.
2. This event is used to load all the variable info into the memory.
3. This event is fired when page s reloaded.
4. This event is fired when the page is destroyed or when the application is destroyted.

Files that are generated when the application is created.
1. Webform1.aspx
2. Global.asax(Active Server Application eXtension)
3. web.config
4. Applicationname.vsdisco(Visual Studio Dynamic Discovery)
5. Assemblyinfo.cs
6.references

1. This file is used to create the interface for the clients to operate.
2. This file keeps the different procedures like SESSION, APPLICATIONS,ERRORS.
3. This file will be in the form of an xml elements. which will keep track of all security info.
4. This file is necessaruy when u want to call the web services into ur applicaiton.
5.This file contains the info about the assemblies, interfaces, structures etc.,
5. This will contain about the default namespaces like
System, System.Data, System.Web, System.Drawing, System.XML

Structures of ASP.NET
1. Directives
2. Code Declaration Block
3. Code Render Block
4. Server Side Includes
5. Server Side Comments

1.It will specify that what compiler we have to use. It is broadly categorized into
1.1 Page Directives
1.2 Import Directives

1.1 To declare any page directives we use
<%@ Page Language="C#" %>
1.2 To declare the import directive
<%@ import namespace="System.Web.Mail" %>

2. It is used to define the functions

3. In case of code render block we assing a value to a variable which we call it as INLINE CODE and we display the value of the variable which is called INLINE EXPRESSION


<% str="hello"; %> //inline code
<% =str; %> //inline expression

4. It is used to call one file to another file. This process can be done in 2 ways.
4.1.

4.2

5.This is used to implement the comment line to the code written


ASP .NET Controls
Control are broadly categorized into 4 types
1. ASP .NET HTML Control
2. ASP .NET WEB Control
3. Validation Control
4. USer Control

1. ASP .NET Control runs from the client side. we have to fire the events explicitly
2. ASP .NET Web Control get executed from the server side ie., Web server.
3. Validation controls are called as special control. The list of validation control are
3.1.RequiredField Validator
3.2.Compare Validator
3.3.Range Validator
3.4.RegularExpression Validator
3.5.Validation Summary

3.1. It checks for the emptyness of the controls
3.2. It is used to compare the values of 2 controls like password and confirm password
3.3 It will validate for a range like the age should be between 30 and 60
3.4 It will validate for an expression like phoneno, email etc.,
3.5 We can consolidate all the messages and store it in a single control and display all the error messages.

4. User Control : We can also create our own control which will have our own properties and methods.

DotnetFAQ1

Framework

Dot net framework is a platform contains collection of services in distributed manner. Using this we can design, develop, build and run the applications.

The services are 1) Runtime 2) Language compiler and 3) Base class libraries.

1) Runtime

The Common Language Runtime
At the heart of the .NET Framework is the Common Language Runtime (CLR). The CLR performs Type safety checking, application memory isolation, memory management, garbage collection, and cross language exception handling.

The CLR greatly simplifies cross language communication through the Introduction of the Common Type System (CTS). The CTS defines all of the basic types that can be used in the .NET Framework and the operations that can be performed on those types. All CTS types are classes that derive from a base class called System. Object
A subsection of the CTS called the Common Language Specification (CLS) specify how .NET languages share and extend one another’s libraries.

The CLR another responsibility is security. An integral part of the .NET Runtime is something called Code Access Security. You can modify the permissions that are granted to code from a certain location using a utility called CASPOL.EXE.

The .NET Runtime classes are organized in hierarchical manner using namespaces.

. Net Framework is a SERVICE as well as Development platform.

When CLR compiles the managed code this can be converted into MSIL code.

Base class Libraries

Common libraries for all the .net languages.

64 base class libraries are there.
System.dll Basic
System.io.dll File Handling
System.data.dll Ado.net
System.web.dll Asp.net

These libraries developed using c# language.



Assemblies

Assemblies are the building blocks of the Dot net Framework.
Assembly can be defined as collection of user defined types or resources.
An assembly consists of one or more files like Dll, exe and html files.
Assembly consists of 3 things.
1) Manifest 2) Type Metadata and 3) MSIL code.

Manifest: Manifest will describe the assembly; this will describe information about other assemblies. We can view manifest through ILDASM.EXE tool.

Type Metadata: Description of namespaces and us er defined types.

MSIL code: .Net CLR understandable code is called as MSIL, Microsoft Intermediate Language.

Assemblies are two types. 1) Shared assemble and 2) private assembly.

Shared Assemble::(name, key and version)
When the assembly is required in more than one application through out the system, we use shared assembly or machine wide assembly.
When the assembly is signed with public key then it is called as Strong named assembly.
Then this Strong name assembly is placed in GAC, and then it is called Shared.

Public key takes 8bytes memory.
Version number has 4 parts. Major.Minor.Build.Revision
Revision: When we are modifying logic of the subprogram then change.
Build: When u adds a new subprogram.
Minor: When u change subprogram Name and class Names.
Major: When u change subprogram Name, Class Names and new classes

Exe and Dll

You can create an object of Dll but not of the EXE.
Dll is an In-Process Component whereas EXE is an Out-Process Component.
Exe is for single use whereas you can use Dll for multiple uses.
Exe can be started as standalone where Dll cannot be.

Namespaces

Namespaces provide a scope (or container) in which types are defined.
A Namespace can be defined as logical container for collection of user-defined types like class, interface.
Namespaces can also be nested. You will use namespaces throughout the .NET framework to:
• Access the .NET Runtime classes
• Access custom classes authored by other developers
• Provide a namespace for your own classes, to avoid naming conflicts with other classes and namespaces

Reflection

System. Reflection is the namespace.

All Dot net assemblies have metadata information stored about the types defined in modules. This metadata information can be accessed by mechanism called as Reflection.
Using reflection we can dynamically find the methods information.

Reflection can also be used to dynamically invoke methods (see System.Type.InvokeMember), or even dynamically create types at run-time (see System.Reflection.Emit.TypeBuilder).

Attribute


Attaching metadata is called as attribute. We can view attributes through the ildasm tool.

Intrinsic and custom are two methods.
Intrinsic are supplied with the framework.

Vb.net and C#. Net

Advantages of VB.Net:

It supports optional parameters and Com Interoperability.
With option Strict Off late binding is supported.
Has WITH Constructs.

C#. NET advantages:

XML document is generated from source code.
Operator overloading is supported.
Using statement for disposing unmanaged references.
Access to unsafe code (i.e. pointers)




Accessspecifiers

Public
Can be instantiated by any element of the application.
Visible to any method of any class.
Friend (internal)
Can be instantiated only by members of the same assembly.
Private
Can be accessible only to the methods of same class.
Protected
Can be accessible by the methods in the same class and the methods that are derived from the same class.
Protected internal
The methods in the same class, the methods derived from the class and the assemble where the class is located.

Static

Array:____Binarysearch(),copy(),indexof(),sort(),reverse(),syncronized()

Array list-----adapter (), fixed size (), repeat(), Sysncronized()

String:----compare(),concat(),copy(),equals()

Appdomain::-------------createdomain(),getcurrentthreadid()



They can't be instantiated.
By default object is created on the first method call to that object.
Static classes cannot be inherited.
Static classes can have only static members
Static classes can have only static constructors.


Structure

Collection of dissimilar data with related functionalities is called structure.

Structure comes under value type.
Doesn’t support inheritance.
Doesn’t support destructor.
Structures don’t use Garbage collector like classes.
Structure also has constructors, methods, properties, fields, constants, enumerations, events, and event handlers.
Structures also implement interfaces.
Structures also have without and with parameter constructors.
Structures also have delegates and events.



Overloading

A sub program more than one signature is called as method overloading.

Shadowing (NEW)

Overriding redefines only the implementation, while shadowing redefines the whole element.
In overriding derived classes can refer the parent class element by using "ME" keyword, but in shadowing u can access it by "MYBASE"

Interface

Interface defines the behavior of the class.

An interface can't implement another interface.
An interface can inherit another interface.
A class can inherit another class by implementing more than one interface.

In interfaces all the methods are abstract, i.e. without implementation.
The variables are Static final only.
An interface implementation may be added to any existing third party class.
You can write a new code for an interface.
Speed of interface is slow.

I unknown interface:

Every COM object supports at least one interface, i.e. I Unknown interface.
This interface has 3 methods.
1) AddRef: Increment count by one.
2) Release: Decrement Count by one.
3) Query Interface.


When count is Zero then object will be freed from the memory.



Ado.net
Namespace: System. Data: This contains Dataset, Data table, and Data Relation objects.
System.data.sqlclient: this contains sqlconnections, sqlcommand, and data reader.

DATASET
The Dataset can be defined as In-memory database for the client application. The Dataset object contains a collection of zero or more Data Tables, Dataset is purely disconnected architecture. The Dataset contains Data Relations collection, DataTable collection, Data Rows collection, Data Columns collection, and the Constraint collection,

DATAREADER
The Data Reader object provides a forward-only, read-only, connected record set.
When data reader is used we must close the connection. If we use command behavior connection will be implicitly called. We didn’t close the connection.

DATAADAPTER
The Data Adapter object populates a disconnected Dataset or Data Table with data and performs updates. The Data Adapter is mediator between the database and a Dataset. The Data Adapter fills a Data Table or Dataset with data from the database whenever the Fill method is called. The Data Adapter provides four properties

Command
Command objects provide three methods that are used
!) ExecuteNonQuery: Executes commands that return no records, such as INSERT, UPDATE, or DELETE. It returns how many records are affected by the query.
2) Execute Scalar. Returns a single value from a database query
3) Execute Reader. Returns a result set by way of a Data Reader object execute commands on the database:
Connection
Oledbconnection object is used with an oledb provider
Sqlconnection object uses with an sqlserver database

Ado.net Architecture

The most important section in Ado.net architecture is “Data Provider”. Data provider provides access to data source. This handles like, opening and closing connection, retrieve data and update data. The main sections of data provider are:
Connection-Establish connection
Command object-To use stored procedures
Data Adapter – This is bridge between data store and dataset
Data Reader – This reads data from data source in forward only.

Dataset object represents disconnected and cached data. The dataset is not directly connected to the database rather it connects to Data Adapter, who is responsible for filling the dataset. Dataset can have one or more Data Tables and relations.
Data View object is used to sort and filter data in Data Table.

Dif between dataset and data Reader

Data Reader provides forward-only and read-only access to data,
Data Set object can hold more than one table with the relationships between them.
Data Reader is connected architecture, where as Data Set is Disconnected.



Garbage Collection

Garbage collector is the service of the CLR.
The garbage collector is a Low priority thread that runs in the background of managed .NET applications. It constantly traces and finds the non-referenced objects and freed them. This will release the objects from the heap memory, which doesn’t have reference from the stack. This will call by the clr implicitly.

Whenever user wants, then he calls the GC explicitly by SupressFinalize () method.

Exception Handling

Exception: The runtime error, which can be handled by the developer, is called as exception.

Try
Catch
Finally
Try: Will contain collection of statements, which can cause the error.
Catch: Will contain the solution for the error.
Finally: A try block can have any number of catch blocks but only one finally block.

There are two types of exceptions: exceptions generated by an executing program and exceptions generated by the common language runtime. System. Exception is the base class for all exceptions in C#. Several exception classes inherit from this class including Application Exception and System Exception. System. Exception includes IoException, Web Exception etc.
The common language runtime throws System Exception.
A user program rather than the runtime throws the ApplicationException. The System Exception includes the ExecutionEngineException, StackOverFlowException etc. It is not recommended that we catch System Exceptions.

Ex:
System.outofmemoryexception
System.nullreferenceexception
System.invalidcastexception
System.indexoutofrangeexception
System.arraytypemismatchexception
System.arithmeticexception
System.devidebyzeroexceptin
System.overflowexception

Threading

Unit of code by maintaining its own execution path is called as Thread. When the application has only one execution path then it is called as single threaded application. When the application has more than one execution path then it is called as multithreaded application.
Thread has the methods,
Start, Suspend, Resume, Sleep and Join.
Priority in the Threads.

ThreadPriority.Highest, AboveNormal, Normal, BelowNormal and Lowest.

sleep-suspent
interrupt-resume

Thread. Join:

Suppose t1 and t2 are two threads, while executing t1 you call t2.join (), so t1 will wait until t2 has completed its execution, and again invoke t1.

We use events with the threading.

Monitor: A block of code runs without being interrupted by code running on other threads.

Difference between Thread and Process:

Thread is a path of execution that runs on CPU,
Process is a collection of threads that share the same virtual memory.
Process has at least one thread, and a thread is always runs under a process.

Delegate

Delegate means function pointer. It represents the address of the method or subprogram. It allows you to pass a reference to the entry point for a method and invoke that method without making an explicit method call. When you declare a delegate, you specify the signature of the method that it can call and the return type. A delegate represents how events work.

Events:

Declaring events is directly tied to delegates. Events in Visual C# are raised by calling them by name as you would a method.
To handle an event in Visual C#;
Create an instance of the appropriate delegate for the event that specified the method that will handle the event, and use the += operator to associate the event with the delegate.

Collection

Collections provide advanced functionality for managing groups of objects. Collections can be resized dynamically, and members can be added and removed at run time.
The System.Collections.ArrayList class provides general collection functionality suitable for most purposes. This class allows you to dynamically add and remove items from a simple list. Accessing the item index retrieves items in the list. The list of objects managed by the Array List is a zero-based collection. Zero-based means that the first object added to the list is assigned the index zero and every subsequent object to be added is assigned to the next available index.

Indexer

In Visual C#, the indexer is the equivalent of a Visual Basic .NET default property. The indexer is a specialized property that allows you to expose a group of objects on the name of the object. The name used in the indexer code is always this, which indicates that the name of the object itself will be used to access the property.
Public int this ()
{
get
{
return IntArray[index];
}
set
{
IntArray[index] = value;
}
}

Representing group of objects like an array is called as indexer.
In C# we didn’t have any static Indexers.

Array List

Array list is an array whose size can automatically increase and decrease dynamically.
Array list can hold item of different types. You can access any item in array using the index value of the array position.

Value and Reference

Value types directly contain their data. They are stored in stack.

Reference types store a reference to the values memory address, and are located on Heap.

Reference types are self-discribing. Like pointer and interface.

Variables of value types, operations on one variable do not affect other variable.
Variables of reference types, operations on one variable can affect the other variable.

Boxing and Unboxing

Boxing, converting value type into reference type (object).

This is implicitly done by the clr.
int x;
object y;
x=10;
y=x

Unboxing, converting reference type into value type.
This is explicitly handled.
x=(object)y
Com and Dcom

COM is a technology for component software development. Which is language independent.
DCOM is Distributed version of COM. It differs from COM,
Com Interoperability

We can use COM Components in .NET through the RCW (Runtime callable wrappers).
Dot net components communicate with COM is possible through RCW. In this we can use TLbimp.exe tool (Type Library Import tool)
System.Runtime.Interopservices namespace is used.

In this Com classes and interface methods are converted into Metadata.

Dot net Components are used in Com With CCW (Com Callable Wrapper)
In this we use a tool, Tlbexp (Type library export tool)

Object Pooling

Object pooling is a COM+ service that enables you to reduce the overhead of creating each object from scratch. When an object is activated, it is pulled from the pool. When the object is deactivated, it is placed back into the pool to await the next request. You can configure object pooling by applying the ObjectPoolingAttribute attribute to a class that derives from the System.EnterpriseServices.ServicedComponent class.

When object is activated it is activated from the pool.
When object is deactivated it is pushed back in to the pool.

When a class is marked with object pooling attribute it cannot be inherited.
Object pooling lets you control the number of connections you use

Application Domain

In Application Domains multiple application can run in same process with out influencing each other. If one of the application domains throws error it does not affect the other application domains.

Remoting

Dcom replacement is Remoting.
Use Remoting for more efficient exchange of information when you control both ends of the application. Remoting is designed to .Net to .Net Communication.

Remoting object calls different Application Domains. Remote objects run in different process client calling the remote object can't call it directly. So they use proxy.

Namespace: System.MarshllbyRefObject.

Remoting depends on
1) Channels
Tcp (transaction commit protocol), data representation.
Http(hypertext transperprotocol) xmlbased syntax
2) Serialization & Desertification
Coverting object into stream Serialization
Reading the stream and construction object is Deserialization.
3) Formatter classes
Binary formatter: it is used by tcp channel
Soap formatter: it is used by http channel

Namespace: System.Runtime.Serialization.Formatters.Binay/soap

Serialize (object, stream)
DeSerialize(Stream)
4) Activation modes
Client activated and server activated.

Server activated: when user makes a call to the method of class, the object creation takes place.
Client activated: whenever the client request comes to the remote server an object will be created and the reference will be send to client application.

Client activated objects maintain state.

Marshal by value: when the client request comes, object will be created on the server machine. This object will be send to client machine.

Marshal by Reference: when the client request comes, object will be created on the server machine. This object reference will be send to client machine.

Single call: When user makes a call to the method, the object will be created, after sending the response the object will be destroy. This is stateless.
For single client we have single object.

Singleton: This will maintain single object for all the clients at a time. The lifetime will be 5 min by default.

Client can be created objects on the server by two ways, one is using Keyword "NEW" and second one is "Activator.CreateInstace ().

Web service

Communication between different business partners is possible by using web services.
Way of invoking a remote method over http connection soap.
Remote procedure call is based on soap protocol.
Description will be generated using wsdl, which is xml format.
Transmission is through xml based.
Transmission protocol is http.

Web services do not have any state. Web services can access Asp.Net intrinsic objects like session, application.
Web services are completely open standards.
To expose each method as a web service, u simply add [Web method] attribute before it.

WSDL: Is a language derived from xml syntax? Wsdl describes the methods names, parameters, location of the web service and standards for request and response.
To view the wsdl content type like http://localhost/WSCalculator/Service1.asmx? Wsdl

To Create the Proxy for the client
Wsdl http://localhost/WSCalculator/Service1.asmx? Wsdl

Togenerate proxy for the client application in the form of xmlfile is by soap.
soapsuds -ia:RemotingServer -oa:ClientProxy.dll
soapsuds -ia:RemotingServer -os:ClientProxy.xml

ia::: input Assembly
oa:: Output Assembly
os:: output stream

Proxy code will contain complete logic for interacting with web service for method calls.

Namespace:: System.Web.Services
if includes 1)webservice 2) webservice attribute class and 3) webmethod

The extension is asmx.

WebPages: Provide consumption of data, this will for end user.
Web service: Provide consumption of logic, this will for Developer.

When we want to reduce number of interactions between werbservice method and database server applying catching for the web method.

Web services supports only text based format.
ie, http-GET
http-Post
Soap

Http-Get and Http-Post supports basic data types only.
Soap supports complex data types like arrays and user-defined types.
Soap will define standards for exchanging data between client and web service interims of request and response.
It is not vendor specific; it is xml standard, introduced in 99-2000.

CSharpFAQ1

1.1 What is C#?
C# is a programming language designed by Microsoft. It is loosely based on C/C++, and bears a striking similarity to Java in many ways. Microsoft describe C# as follows:
"C# is a simple, modern, object oriented, and type-safe programming language derived from C and C++. C# (pronounced 'C sharp') is firmly planted in the C and C++ family tree of languages, and will immediately be familiar to C and C++ programmers. C# aims to combine the high productivity of Visual Basic and the raw power of C++."
1.2 How do I develop C# apps?
The (free) .NET SDK contains the C# command-line compiler (csc.exe). Visual Studio.NET has fully integrated support for C# development.
1.3 Where can I download the .NET SDK & Visual Studio.NET?
You can download the SDK from
http://www.microsoft.com/net. If you are an MSDN Universal subscriber, you can also download Visual Studio.NET.
1.4 Does C# replace Java?
C# is a very Java-like language - the core of both languages have similar advantages and limitations when compared to C++. For example, both languages have garbage collection, but neither language has templates. Microsoft have ceased production of Visual J++, so it's hard not to view C# as Microsoft's alternative to Java.
1.5 Does C# replace C++?
The obvious answer is no. However it's difficult to see C++ as the best choice for new .NET code. For the .NET runtime to function fully, it requires the programming language to conform to certain rules - one of these rules is that language types must conform to the Common Type System (CTS). Unfortunately many C++ features are not supported by the CTS - for example multiple inheritance of classes and templates.
Microsoft's answer to this problem is to offer Managed Extensions (ME) for C++, which allows you to write C++ that conforms to the CTS. New keywords are provided to mark your C++ classes with CTS attributes (e.g. __gc for garbage collection). However, it's difficult to see why ME C++ would be chosen over C# for new projects. In terms of features they are very similar, but unlike C++, C# has been designed from the ground-up to work seamlessly with the .NET environment. The raison d'etre for ME C++ would therefore appear to be porting existing C++ code to the .NET environment.
So, in answer to the question, my suspicion is that C++ will remain an important language outside of the .NET environment, and will be used (via ME) to port existing code to .NET, but I think C# will become the language of choice for one-time C++ developers developing new .NET applications. But only time will tell ...
1.6 What does a simple C# program look like?
Sorry, my imagination has deserted me. Yes, you guessed it, here comes 'Hello, world' ...class CApplication
{
public static void Main()
{
System.Console.Write( "Hello, new .NET world." );
}
}
(No, you can't put Main() as a global function - global functions don't exist in C#.)
1.7 Is C# object-oriented?
Yes, C# is an OO language in the tradition of Java and C++.
1.8 Does C# have its own class library?
Not exactly. In common with all .NET languages (e.g. VisualBasic.NET, JScript.NET) C# has access to the .NET class library. C# does not have its own class library.
2. Basic types
2.1 What standard types does C# supply?
C# supports a very similar range of basic types to C++, including int, long, float, double, char, string, arrays, structs and classes. However, don't assume too much. The names may be familiar, but some of the details are different. For example, a long is 64 bits in C#, whereas in C++ the size of a long depends on the platform (typically 32 bits on a 32-bit platform, 64 bits on a 64-bit platform). Also classes and structs are almost the same in C++ - this is not true for C#.
2.2 Is it true that all C# types derive from a common base class?
Yes and no. All types can be treated as if they derive from object (System.Object), but in order to treat an instance of a value type (e.g. int, float) as object-derived, the instance must be converted to a reference type using a process called 'boxing'. In theory a developer can forget about this and let the run-time worry about when the conversion is necessary, but in reality this implicit conversion can have side-effects that may trip up the unwary.
2.3 So this means I can pass an instance of a value type to a methodthat takes an object as a parameter?
Yes. For example:class CApplication
{
public static void Main()
{
int x = 25;
string s = "fred";

DisplayMe( x );
DisplayMe( s );
}

static void DisplayMe( object o )
{
System.Console.WriteLine( "You are {0}", o );
}
}
This would display:You are 25
You are fred

2.4 What are the fundamental differences between value types andreference types?
C# divides types into two categories - value types and reference types. Most of the basic intrinsic types (e.g. int, char) are value types. Structs are also value types. Reference types include classes, interfaces, arrays and strings. The basic idea is straightforward - an instance of a value type represents the actual data (stored on the stack), whereas an instance of a reference type represents a pointer or reference to the data (stored on the heap).
The most confusing aspect of this for C++ developers is that C# has predetermined which types will be represented as values, and which will be represented as references. A C++ developer expects to take responsibility for this decision.
For example, in C++ we can do this:int x1 = 3; // x1 is a value on the stack
int *x2 = new int(3) // x2 is a reference to a value on the heap
but in C# there is no control:int x1 = 3; // x1 is a value on the stack
int x2 = new int();
x2 = 3; // x2 is also a value on the stack!
2.5 Okay, so an int is a value type, and a class is areference type. How can int be derived from object?
It isn't, really. When an int is being used as an int, it is a value (on the stack). However, when it is being used as an object, it is a reference to an integer value on the heap. In other words, when you treat an int as an object, the runtime automatically converts the int value to an object reference. This process is called boxing. The conversion involves copying the contents of the int from the stack to the heap, and creating an object instance which refers to it. Unboxing is the reverse process - the object is converted back to a stack-based value.int x = 3; // new int value 3 on the stack
object objx = x; // new int on heap, set to value 3 - still have x=3 on stack
int y = (int)objx; // new value 3 on stack, still got x=3 on stack and objx=3 on heap
2.6 C# uses references instead of pointers. Are C# references the sameas C++ references?
Not quite. The basic idea is the same, but one significant difference is that C# references can be null . So you cannot rely on a C# reference pointing to a valid object. If you try to use a null reference, a NullReferenceException is thrown.
For example, look at the following method:void displayStringLength( string s )
{
Console.WriteLine( "String is length {0}", s.Length );
}
The problem with this method is that it will throw a NullReferenceException if called like this:string s = null;
displayStringLength( s );
Of course for some situations you may deem a NullReferenceException to be a perfectly acceptable outcome, but in this case it might be better to re-write the method like this:void displayStringLength( string s )
{
if( s == null )
Console.WriteLine( "String is null" );
else
Console.WriteLine( "String is length {0}", s.Length );
}
3. Classes and structs
3.1 Structs are largely redundant in C++. Why does C# have them?
In C++, a struct and a class are pretty much the same thing. The only difference is the default visibility level (public for structs, private for classes). However, In C# structs and classes are very different. In C#, structs are value types (stored on the stack), whereas classes are reference types (stored on the heap). Also structs cannot inherit from structs or classes, though they can implement interfaces. Structs cannot have destructors.
3.2 Does C# support multiple inheritance (MI)?
C# supports multiple inheritance of interfaces, but not of classes.
3.3 Is a C# interface the same as a C++ abstract class?
No, not quite. An abstract class in C++ cannot be instantiated, but it can (and often does) contain implementation code and/or data members. A C# interface cannot contain any implementation code or data members - it is simply a group of method names & signatures. A C# interface is more like a COM interface than a C++ abstract class.
The other major difference is that a C# class can inherit from only one class (abstract or not), but can implement multiple interfaces.
3.4 Are C# constructors the same as C++ constructors?
Very similar.
3.5 Are C# destructors the same as C++ destructors?
No! They look the same but they're very different. First of all, a C# destructor isn't guaranteed to be called at any particular time. In fact it's not guaranteed to be called at all. Truth be told, a C# destructor is really just a Finalize method in disguise. In particular, it is a Finalize method with a call to the base class Finalize method inserted. So this:class CTest
{
~CTest()
{
System.Console.WriteLine( "Bye bye" );
}
}
is really this:class CTest
{
protected override void Finalize()
{
System.Console.WriteLine( "Bye bye" );
base.Finalize();
}
}
With the arrival of Beta 2, explicitly overriding Finalize() like this is not allowed - the destructor syntax must be used.
3.6 If C# destructors are so different to C++ destructors, why did MSuse the same syntax?
Because they're evil, and they want to mess with your mind.
3.7 What is a static constructor?
A constructor for a class, rather than instances of a class. The static constructor is called when the class is loaded.
3.8 Are all methods virtual in C#?
No. Like C++, methods are non-virtual by default, but can be marked as virtual.
3.9 How do I declare a pure virtual function in C#?
Use the abstract modifier on the method. The class must also be marked as abstract (naturally). Note that abstract methods cannot have an implementation (unlike pure virtual C++ methods).
4. Exceptions
4.1 Can I use exceptions in C#?
Yes, in fact exceptions are the recommended error-handling mechanism in C# (and in .NET in general). Most of the .NET framework classes use exceptions to signal errors.
4.2 What types of object can I throw as exceptions?
Only instances of the System.Exception classes, or classes derived from System.Exception. This is in sharp contrast with C++ where instances of almost any type can be thrown.
4.3 Can I define my own exceptions?
Yes, as long as you follow the rule that exceptions derive from System.Exception. More specifically, MS recommend that user-defined exceptions inherit from System.ApplicationException (which is derived from System.Exception).
4.4 Are there any standard exceptions that I can re-use?
Yes, and some of them loosely correspond to standard COM HRESULTs. The table below shows a mapping from HRESULTs to .NET (and therefore C#) exceptions:
HRESULT
.NET EXCEPTION
E_INVALIDARG
ArgumentOutOfRangeException, or the more general ArgumentException. Alternatively FormatException if a supplied parameter is not the correct format - e.g. a URL is specified as htp:// instead of http://
E_POINTER
ArgumentNullException
E_NOTIMPL
NotImplementedException
E_UNEXPECTED
Some may consider InvalidOperationException to be equivalent. InvalidOperationException is normally used to indicate that an object cannot perform the requested operation because it is not in a suitable state to do so.
E_OUTOFMEMORY
OutOfMemoryException
Other standard exceptions that you might want to re-use are IndexOutOfRangeException and ArithmeticException .
4.5 Does the System.Exception class have any cool features?
Yes - the feature which stands out is the StackTrace property. This provides a call stack which records where the exception was thrown from. For example, the following code:using System;
class CApp
{
public static void Main()
{
try
{
f();
}
catch( Exception e )
{
Console.WriteLine( "System.Exception stack trace = \n{0}", e.StackTrace );
}
}
static void f()
{
throw new Exception( "f went pear-shaped" );
}
}
produces this output:System.Exception stack trace =
at CApp.f()
at CApp.Main()
Note, however, that this stack trace was produced from a debug build. A release build may optimise away some of the method calls which could mean that the call stack isn't quite what you expect.
4.6 When should I throw an exception?
This is the subject of some debate, and is partly a matter of taste. However, it is accepted by many that exceptions should be thrown only when an 'unexpected' error occurs. How do you decide if an error is expected or unexpected? This is a judgement call, but a straightforward example of an expected error is failing to read from a file because the seek pointer is at the end of the file, whereas an example of an unexpected error is failing to allocate memory from the heap.
4.7 Does C# have a 'throws' clause?
No, unlike Java, C# does not require (or even allow) the developer to specify the exceptions that a method can throw.
5. Run-time type information
5.1 How can I check the type of an object at runtime?
You can use the is keyword. For example:using System;
class CApp
{
public static void Main()
{
string s = "fred";
long i = 10;
Console.WriteLine( "{0} is {1}an integer", s, (IsInteger(s) ? "" : "not ") );
Console.WriteLine( "{0} is {1}an integer", i, (IsInteger(i) ? "" : "not ") );
}

static bool IsInteger( object obj )
{
if( obj is int obj is long )
return true;
else
return false;
}
}
produces the output:fred is not an integer
10 is an integer
5.2 Can I get the name of a type at runtime?
Yes, use the GetType method of the object class (which all types inherit from). For example:using System;
class CTest
{
class CApp
{
public static void Main()
{
long i = 10;
CTest ctest = new CTest();
DisplayTypeInfo( ctest );
DisplayTypeInfo( i );
}

static void DisplayTypeInfo( object obj )
{
Console.WriteLine( "Type name = {0}, full type name = {1}", obj.GetType(), obj.GetType().FullName );
}
}
}
produces the following output:Type name = CTest, full type name = CTest
Type name = Int64, full type name = System.Int64
6. Advanced language features
6.1 What are delegates?
A delegate is a class derived from System.Delegate. However the language has a special syntax for declaring delegates which means that they don't look like classes. A delegate represents a method with a particular signature. An instance of a delegate represents a method with a particular signature on a particular object (or class in the case of a static method). For example:using System;
delegate void Stereotype();
class CAmerican
{
public void BePatriotic()
{
Console.WriteLine( "... ... God bless America.");
}
}
class CBrit
{
public void BeXenophobic()
{
Console.WriteLine( "Bloody foreigners ... " );
}
}
class CApplication
{
public static void RevealYourStereotype( Stereotype[] stereotypes )
{
foreach( Stereotype s in stereotypes )
s();
}

public static void Main()
{
CAmerican chuck = new CAmerican();
CBrit edward = new CBrit();
// Create our list of sterotypes.
Stereotype[] stereotypes = new Stereotype[2];
stereotypes[0] = new Stereotype( chuck.BePatriotic );
stereotypes[1] = new Stereotype( edward.BeXenophobic );

// Reveal yourselves!
RevealYourStereotype(stereotypes );
}
}
This produces the following result:... ... God bless America.
Bloody foreigners ...
6.2 Are delegates just like interfaces with a single method?
Conceptually delegates can be used in a similar way to an interface with a single method. The main practical difference is that with an interface the method name is fixed, whereas with a delegate only the signature is fixed - the method name can be different, as shown in the example above.
6.3 What is the C# equivalent of QueryInterface?
The as keyword. For example:using System;
interface IPerson
{
string GetName();
}
interface IPerson2 : IPerson
{
int GetAge();
}
class CPerson : IPerson
{
public CPerson( string name )
{
m_name = name;
}

// IPerson
public string GetName()
{
return m_name;
}

private string m_name;
}
class CPerson2 : IPerson2
{
public CPerson2( string name, int age )
{
m_name = name;
m_age = age;
}

// IPerson2
public string GetName() { return m_name; }
public int GetAge() { return m_age; }
private string m_name; private int m_age;
}
public class CApp
{
public static void Main()
{
CPerson bob = new CPerson( "Bob" );
CPerson2 sheila = new CPerson2( "Sheila", 24 );

DisplayAge( bob );
DisplayAge( sheila );
}

static void DisplayAge( IPerson person )
{
IPerson2 person2 = person as IPerson2; // QueryInterface lives on !!!
if( person2 != null )
Console.WriteLine( "{0} is {1} years old.", person2.GetName(), person2.GetAge() );
else
Console.WriteLine( "Sorry, don't know {0}'s age.", person.GetName() );
}
}
Running the program produces the following output:Sorry, don't know Bob's age.
Sheila is 24 years old.
7. It doesn't work like that in C++ ...
7.1 I 'new'-ed an object, but how do I delete it?
You can't. You are not allowed to call the destructor explicitly, and no delete operator is provided. Don't worry, the garbage collector will destroy your object .... eventually .... probably .... :-)
7.2 I tried to create an object on the stack, but the C# compilercomplained. What's going on?
Unlike C++, you cannot create instances of classes on the stack. Class instances always live on the heap and are managed by the garbage collector.
7.3 I defined a destructor, but it never gets called. Why?
A C# destructor is really just an implementation of Finalize, and the runtime doesn't guarantee to call Finalize methods. The semantics of a C# destructor are quite different from a C++ destructor.
7.4 Most of the C# basic types have the same names as C++ basic types?Are they the same?
No. A char in C# is equivalent to a wchar_t in C++. All characters (and strings, obviously) are Unicode in C#. Integral values in C# are concrete sizes, unlike C++ (where size depends on processor). For example, a C# int is 32 bits, whereas a C++ int is normally 32 bits on a 32-bit processor and 64 bits on a 64-bit processor. A C# long is 64 bits.
8. Miscellaneous
8.1 String comparisons using == seem to be case-sensitive? How do I doa case-insensitive string comparison?
Use the String.Compare function. Its third parameter is a boolean which specifies whether case should be ignored or not."fred" == "Fred" // false
System.String.Compare( "fred", "Fred", true ) // true
8.2 I've seen some string literals which use the @ symbol, and somewhich don't. What's that all about?
The @ symbol before a string literal means that escape sequences are ignored. This is particularly useful for file names, e.g.string fileName = "c:\\temp\\test.txt"
versus:string fileName = @"c:\temp\test.txt"
8.3 Does C# support a variable number of arguments?
Yes, using the params keyword. The arguments are specified as a list of arguments of a specific type, e.g. int. For ultimate flexibility, the type can be object. The standard example of a method which uses this approach is System.Console.WriteLine().
8.4 How can I process command-line arguments?
Like this:using System;
class CApp
{
public static void Main( string[] args )
{
Console.WriteLine( "You passed the following arguments:" );
foreach( string arg in args )
Console.WriteLine( arg );
}
}
8.5 Does C# do array bounds checking?
Yes. An IndexOutOfRange exception is used to signal an error.
8.6 How can I make sure my C# classes will interoperate with other .NETlanguages?
Make sure your C# code conforms to the Common Language Subset (CLS). To help with this, add the [assembly:CLSCompliant(true)] global attribute to your C# source files. The compiler will emit an error if you use a C# feature which is not CLS-compliant.