Tuesday, April 1, 2008

Remoting

.NET Remoting

What is .NET Remoting?
.NET Remoting is an enabler for application communication. It is a generic system for different applications to use to communicate with one another. .NET objects are exposed to remote processes, thus allowing interprocess communication. The applications can be located on the same computer, different computers on the same network, or even computers across separate networks.
.NET Remoting versus Distributed COM
In the past interprocess communication between applications was handled through Distributed COM, or DCOM. DCOM works well and the performance is adequate when applications exist on computers of similar type on the same network. However, DCOM has its drawbacks in the Internet connected world. DCOM relies on a proprietary binary protocol that not all object models support, which hinders interoperability across platforms. In addition, have you tried to get DCOM to work through a firewall? DCOM wants to communicate over a range of ports that are typically blocked by firewalls. There are a ways to get it to work, but they either decrease the effectiveness of the firewall (why bother to even have the firewall if you open up a ton of ports on it), or require you to get a firewall that allows support for binary traffic over port 80.
.NET Remoting eliminates the difficulties of DCOM by supporting different transport protocol formats and communication protocols. This allows .NET Remoting to be adaptable to the network environment in which it is being used.
.NET Remoting versus Web Services
Unless you have been living in a cave, or are way behind in your reading, you have probably read something about Web services. When you read the description of .NET Remoting it may remind you a lot of what you're read about Web services. That is because Web services fall under the umbrella of .NET Remoting, but have a simplified programming model and are intended for a wide target audience.
Web services involve allowing applications to exchange messages in a way that is platform, object model, and programming language independent. Web services are stateless and know nothing about the client that is making the request. The clients communicate by transferring messages back and forth in a specific format known as the Simple Object Access Protocol, or SOAP. (Want to get some funny looks in the hallway? Stand around in the hallway near the marketing department with your colleagues and discuss the benefits of using SOAP).
The following list outlines some of the major differences between .NET Remoting and Web services that will help you to decide when to use one or the other:
· ASP.NET based Web services can only be accessed over HTTP. . NET Remoting can be used across any protocol.
· Web services work in a stateless environment where each request results in a new object created to service the request. .NET Remoting supports state management options and can correlate multiple calls from the same client and support callbacks.
· Web services serialize objects through XML contained in the SOAP messages and can thus only handle items that can be fully expressed in XML. .NET Remoting relies on the existence of the common language runtime assemblies that contain information about data types. This limits the information that must be passed about an object and allows objects to be passed by value or by reference.
· Web services support interoperability across platforms and are good for heterogeneous environments. .NET Remoting requires the clients be built using .NET, or another framework that supports .NET Remoting, which means a homogeneous environment.
Remoting Objects:
Remotable objects are objects that function well in a widely distributed environment. There are two main kinds of remotable objects:
· Marshal-by-value objects, which are copied and passed out of the application domain.
· Marshal-by-reference objects, for which a proxy is created and used by the client to access the object remotely.

Marshall – by – Value:
Marshal-by-value (MBV) objects declare their serialization rules (either by implementing ISerializable to implement their own serialization, or by being decorated with SerializableAttribute, which tells the system to serialize the object automatically) but do not extend MarshalByRefObject. The remoting system makes a complete copy of these objects and passes the copy to the calling application domain. Once the copy is in the caller's application domain, calls to the copy go directly to that copy. Further, MBV objects that are passed as arguments are also passed by value. Other than declaring the SerializableAttribute attribute or implementing ISerializable, you do not need to do anything to pass instances of your class by value across application or context boundaries.
Use MBV objects when it makes sense for performance or processing reasons to move the complete state of the object and any executable functionality to the target application domain. In many scenarios, this reduces lengthy, resource-consuming round trips across network, process, and application domain boundaries. MBV objects are also used directly from within the object's original application domain. In this case, because no marshaling takes place, no copy is made and access is very efficient.
On the other hand, if your published objects are very large, passing an entire copy around a busy network might not be the best choice for your application. In addition, no changes to the state of the copied object are ever communicated back to the original object in the originating application domain. At an abstract level, this scenario is similar to that of a static HTML page requested by a client browser. The server copies the file, writes it into a stream, sends it out, and forgets about it. Any subsequent request is merely another request for another copy.

Marshall – by – reference:
Marshal-by-reference (MBR) objects are remotable objects that extend at least System.MarshalByRefObject. Depending on what type of activation has been declared, when a client creates an instance of an MBR object in its own application domain, the .NET remoting infrastructure creates a proxy object in the caller's application domain that represents the MBR object, and returns to the caller a reference to that proxy. The client then makes calls on the proxy. Remoting marshals those calls, sends them back to the originating application domain, and invokes the call on the actual object.
Note If the client is in the same application domain as the MBR object, the infrastructure returns to the client a direct reference to the MBR object, avoiding the overhead of marshaling.
If a MarshalByRefObject is passed as a parameter, it becomes a proxy in the other application domain when the call arrives. MBR return values and out parameters work in the same way.
You should use MBR objects when the state of the object and any executable functionality should stay in the application domain in which it was created. For example, an object that has an internal field that is an operating system handle should extend MarshalByRefObject because the operating system handle would not be meaningful in another application domain, in another process, or on another computer. Sometimes an object can also be prohibitively large; that might work on a robust server, but not when sent over a wire to a 33.6 kbps modem.

Activatoin:

Client Activation:

Client-activated objects are objects whose lifetimes are controlled by the calling application domain, just as they would be if the object were local to the client. With client activation, a round trip to the server occurs when the client tries to create an instance of the server object, and the client proxy is created using an object reference (ObjRef) obtained on return from the creation of the remote object on the server. Each time a client creates an instance of a client-activated type, that instance will service only that particular reference in that particular client until its lease expires and its memory is recycled. If a calling application domain creates two new instances of the remote type, each of the client references will invoke only the particular instance in the server application domain from which the reference was returned.

To create an instance of a client-activated type, clients either configure their application programmatically (or using a configuration file) and call new (New in Visual Basic), or they pass the remote object's configuration in a call to Activator.CreateInstance. The following code example shows such a call, assuming a TcpChannel has been registered to listen on port 8080.

[Visual Basic]
Dim Object() = {New UrlAttribute("tcp://computername:8080/RemoteObjectApplicationName ")}
' Note that the second parameter (Nothing) specifies that no arguments
' are being passed.
Dim MyRemoteClass As RemoteObjectClass = _
CType( _
Activator.CreateInstance(GetType(RemoteObjectClass), Nothing, url), _
RemoteObjectClass)

[C#]
object[] url = {new UrlAttribute("tcp://computername:8080/RemoteObjectApplicationName")};
// Note that the second parameter (null) specifies that no arguments
// are being passed.
RemoteObjectClass MyRemoteClass = (RemoteObjectClass)Activator.CreateInstance(
typeof(RemoteObjectClass),
null,
url
);



Server Activation:

Server-activated objects are objects whose lifetimes are directly controlled by the server. The server application domain creates these objects only when the client makes a method call on the object, rather than when the client calls new (New() in Visual Basic) or Activator.GetObject; this saves a network round trip solely for the purpose of instance creation. Only a proxy is created in the client application domain when a client requests an instance of a server-activated type.

There are two activation modes (or WellKnownObjectMode values) for server-activated objects: Singleton and SingleCall.

Singleton types never have more than one instance at any one time. If an instance exists, all client requests are serviced by that instance. If an instance does not exist, the server creates an instance and all subsequent client requests will be serviced by that instance. Because Singleton types have an associated default lifetime, clients will not always receive a reference to the same instance of the remotable class, even if there is never more than one instance available at any one time.

SingleCall types always have one instance per client request. The next method invocation will be serviced by a different server instance, even if the previous instance has not yet been recycled by the system. SingleCall types do not participate in the lifetime lease system.

To create an instance of a server-activated type, clients either configure their application programmatically (or using a configuration file) and call new, or they pass the remote object's configuration in a call to Activator.GetObject.

The following code example shows a call to Activator.GetObject, assuming a TcpChannel has been registered to communicate on port 8080. If your client knows only that the server object implements a particular interface, you must use a call to Activator.GetObject, because you can only use new (New in Visual Basic) to create an instance of a class.

[Visual Basic]
Dim MyRemoteClass As RemoteObjectClass = _
CType( _
Activator.GetObject(_
GetType(RemoteObjectClass), _
"tcp://computername:8080/RemoteObjectUri" _
), _ RemoteObjectClass )

[C#]
RemoteObjectClass MyRemoteClass = (RemoteObjectClass)Activator.GetObject(
typeof(RemoteObjectClass),
"tcp://computername:8080/RemoteObjectUri ");

Remember, the preceding call does not create the remote object on the server. It returns to the client only a reference to the local proxy for the remote object. The client can now continue to treat MyRemoteClass as though it is a direct reference to the remote object. The instance that the client actually uses to communicate from method call to method call depends on whether the server object is declared as a Singleton or SingleCall type. Regardless of whether the publisher of the server object exposes this information, the client treats the object reference that it has exactly the same.

Leases:
Leases are created when an MBR object is activated in another application domain.
Whenever an MBR object is remoted outside an application domain, a lifetime lease is created for that object. Each application domain contains a lease manager that is responsible for administering leases in its domain. The lease manager periodically examines all leases for expired lease times. If a lease has expired, the lease manager walks its list of sponsors for that object and queries whether any of them want to renew the lease. If no sponsor renews the lease, the lease manager removes the lease, the object is deleted, and its memory is reclaimed by garbage collection. An object's lifetime, then, can be much longer than its lifetime lease, if renewed more than once by a sponsor or by continually being called by clients.
Because the remote object's life is independent of the lives of its clients, the lease for a simple or lightweight object can be very long, be used by a number of clients, and be periodically renewed by an administrator or a client. This approach uses leases efficiently because very little network traffic is needed for distributed garbage collection. However, remote objects that use scarce resources can have a lease with a short lifetime, which a client frequently renews with a short time span. When all the clients are finished with the remote object, the .NET remoting system deletes the object quickly. This policy substitutes increased network traffic for more efficient use of server resources.
Since it’s a bit complex and needs a sample code, I have not covered this topic. For more information on leases, you can find more at the url(s) below:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconremotableobjects.asp


Channels:
A channel is an object that implements communication between a client and a remote object, across app domain boundaries. The .NET Framework implements two default channel classes, as follows:
· HttpChannel: Implements a channel that uses the HTTP protocol.
· TcpChannel: Implements a channel that uses the TCP protocol (Transmission Control Protocol).
Both of these classes are dual-purpose in that they implement both a client channel, used on the client side to communicate with remote objects, and a server channel, used on the server side to communicate with clients. The HttpChannel class formats messages using the SOAP protocol, which encodes communications as XML. In contrast the TcpChannel class uses a binary format for messages. While binary formatting is more efficient (formatted messages are smaller), the plain text format of SOAP is much less likely to have problems with firewalls and other network security measures.


When and why to choose Marshal by Value or by Reference
Remoting makes an object in one process (the server) available to code in another process (the client). This is called marshalling, and there are two fundamentally different ways to marshal an object:
· Marshal by value: the server creates a copy of the object passes the copy to the client.
· Marshal by reference: the client creates a proxy for the object and then uses the proxy to access the object.
When a client makes a call to an object marshaled by value (MBV), the server creates an exact copy and sends that copy to the client. The client can then use the object's data and executable functionality directly within its own process or application domain without making additional calls to the server. To implement MBV you must either implement the ISerializable interface in your classes, or mark them with the attribute.

In contrast, when a client makes a call to an object marshaled by reference (MBR), the .NET framework creates a proxy in the client's application domain and the client uses that proxy to access the original object on the server. To implement MBR a class must, at minimum, extend the System.MarshalByRefObject class. Figure 1 illustrates the differences between MBV and MBR.

First picture demonstrates MBVSecond picture demonstrates MBR

Given the differences between MBV and MBR, how do you decide which to use when you're programming a remotable class? In some situations you have no choice—you must use MBR, such as when the remote component must run in its own original app domain, in order to access local files or use operating system handles. These operations could not be carried out by a copy of the object running in the client's app domain. You would also need to use MBR when the client must be made aware of changes in the object. When using MBV the copy of the object that is sent to the client is static, and does not reflect subsequent changes to the state of the object on the server.

In many situations, however, either MBV or MBR will work, and the question is which is better? The concern here is that old bugaboo—bandwidth. Ask yourself which technique places fewer demands on the transport between server and client? With MBV you need move the object copy from the server to the client one time. While that can be a significant task with large objects, after the copy is at the client, calls to it are all within the client's app domain and do not involve the transport mechanism at all.

In contrast, MBR does not require a copy of the entire object to be transported to the client—but each and every time the client accesses the remote object it requires either a one-way or round-trip transport of information. Individually these calls may not place a heavy demand on communication, but hundreds or thousands of calls can add up.

Bottom line?
-Small objects that the application accesses frequently are best remoted using MBV.
-Large objects that the application accesses relatively infrequently are good candidates for MBR.

Unfortunately, that leaves a middle ground where the choice between MBR and MBV may not be immediately obvious. You may want to do some performance testing to aid in your decision.






Sample to demonstrate:

This demonstration program presents a simple remoting example. It illustrates the basic tasks involved in creating a remotable class, a server, and a client.

1. Creating Remotable class:

The remotable class (called RemoteClass) contains a single method that returns a "secret" word to the caller. The class constructor displays a console message when a client activates the class. I've included the console message for demonstration purposes only; it's not required for the class to function. the source code for the RemoteClass. Note that the only aspect of the class related to remoting is that it inherits from MarshalByRefObject. You can create the demo code using any text editor and then save it in the project folder under the name RemoteClass.cs. Then, from the command prompt, compile the class using the following command (enter the command on a single line):
csc /t:library /debug /r:System.Runtime.Remoting.dll RemoteClass.cs

The class compiles to the file RemoteClass.dll.

using System;

namespace RemotingDemo {

public class MyRemoteClass : MarshalByRefObject {

public MyRemoteClass()
{
Console.WriteLine("MyRemoteClass activated");
}

public String SecretWord()
{
return "REMOTING";
}
}
}

2. Creating Client:

Next, you must build the client, which will call the remotable class. the client code, called Client.cs. The program does the following things:
1. Creates a TcpChannel on port 8084.
2. Registers the channel with the .NET infrastructure.
3. Attempts to obtain a reference to the remote class by calling the Activator.GetObject() method.
4. If the program can't obtain a reference, it displays a message to the user. Otherwise it calls the remote object's SecretWord() method and displays the returned data.
The call to the Activator.GetObject() method needs some more explanation. The method accepts two arguments. The first is the type of the remote class, which you can obtain by using the typeof() method with the class's namespace and name as argument. The second argument has the following parts:
· tcp://: identifies the protocol being used. Tcp is specified because the client and the server are using a TcpChannel for communication.
· localhost: the name of the computer on which the remote class is located. In this sample, the remote class is on the same computer as the client, so the code uses the name "localhost". If the class were located on a network computer with the name "BIGSERVER", you would use that instead.
· :8085: This identifies the port on which the remote class is listening.
· /Secret: the URI associated with the remote class. This is an arbitrary name and can be anything you like as long as it matches the URI established by the server.
To compile the client, save the code as Client.cs and compile with the following command line (enter the command on a single line). Note that the compiler command specifies a reference to the remotable class RemoteClass.dll that you created previously.
csc /debug /r:remoteclass.dll /r:System.Runtime.Remoting.dll Client.cs

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

namespace RemotingDemo {
public class Client
{
public static int Main(string [] args)
{
TcpChannel chan = new TcpChannel(8084);
ChannelServices.RegisterChannel(chan);
MyRemoteClass obj = (MyRemoteClass)
Activator.GetObject(typeof(RemotingDemo.MyRemoteClass),
"tcp://localhost:8085/Secret");
if (obj == null)
System.Console.WriteLine("Server not found.");
else
Console.WriteLine("The secret word is " +
obj.SecretWord());
return 0;
}
}
}


3. Creating server:

Finally, you need to create the server. The server listens for calls from clients and connects them to the remotable class. Here's what the code does:
1. Creates a new TcpChannel on port 8085. Note that this is the same channel on which the client will look for the remotable class.
2. Registers the channel with the .NET infrastructure.
3. Registers the remotable class using a call to the RemotingConfiguration.RegisterWellKnownServiceType() method. The arguments to this call are:
4. The first argument identifies the class being registered.
5. The second argument specifies the URI for the class. A client will use this URI when looking for the class.
6. The third argument specifies that if there are multiple calls to the class (from more than one client), they will all be services by the same instance of the class.
7. Display a message to the user and then pause until the user presses Enter.
Step 4 is required because the server must be executing to do its job. In other words, only while the server program is running will it "listen" for client requests for the remotable class.

To complete the server, save the code as Server.cs and compile it with the following command line (enter the command on a single line):
csc /debug /r:remoteclass.dll /r:System.Runtime.Remoting.dll Server.cs



using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

namespace RemotingDemo {
public class Demo {

public static int Main(string [] args) {

TcpChannel chan = new TcpChannel(8085);
ChannelServices.RegisterChannel(chan);
RemotingConfiguration.RegisterWellKnownServiceType(
Type.GetType("RemotingDemo.MyRemoteClass,RemoteClass"),
"Secret", WellKnownObjectMode.SingleCall);
System.Console.WriteLine("Hit to exit...");
System.Console.ReadLine();
return 0;
}
}
}

Summary

I didn’t have much time to think of a good remoting sample and then discuss that. My main idea of compiling this article was to cover the basic knowledge of .net remoting with a simple test code which I have included.

That’s it for now and after writing such a simple .NET Remoting overview in a simple manner, I hope it will be clear to the reader that how easy is to use .NET remoting and to make your objects remotable.

Dotnet Basics

1. Write a simple Windows Forms MessageBox statement.
System.Windows.Forms.MessageBox.Show ("Hello, Windows Forms");

2. Can you write a class without specifying namespace? Which namespace does it belong to by default??

Yes, you can, then the class belongs to global namespace which has no name. For commercial products, naturally, you wouldn’t want global namespace.

3. You are designing a GUI application with a window and several widgets on it. The user then resizes the app window and sees a lot of grey space, while the widgets stay in place. What’s the problem?

One should use anchoring for correct resizing. Otherwise the default property of a widget on a form is top-left, so it stays at the same location when resized.

4. How can you save the desired properties of Windows Forms application?
.config files in .NET are supported through the API to allow storing and retrieving information.
They are nothing more than simple XML files, sort of like what .ini files were before for Win32 apps.

5. So how do you retrieve the customized properties of a .NET application from XML .config file?

Initialize an instance of AppSettingsReader class. Call the GetValue method of AppSettingsReader class, passing in the name of the property and the type expected. Assign the result to the appropriate variable.

6. Can you automate this process?

In Visual Studio yes, use Dynamic Properties for automatic .config creation, storage and retrieval.

7. My progress bar freezes up and dialog window shows blank, when an intensive background process takes over.

Yes, you should’ve multi-threaded your GUI, with taskbar and main form being one thread, and the background process being the other.

8. What’s the safest way to deploy a Windows Forms app?

Web deployment: the user always downloads the latest version of the code; the program runs within security sandbox, properly written app will not require additional security privileges.
9. Why is it not a good idea to insert code into InitializeComponent method when working with Visual Studio?

The designer will likely throw it away; most of the code inside InitializeComponent is auto-generated.

10. What’s the difference between WindowsDefaultLocation and WindowsDefaultBounds?

WindowsDefaultLocation tells the form to start up at a location selected by OS, but with internally specified size. WindowsDefaultBounds delegates both size and starting position choices to the OS.

11. What’s the difference between Move and LocationChanged? Resize and SizeChanged?

Both methods do the same, Move and Resize are the names adopted from VB to ease migration to C#.

12. How would you create a non-rectangular window, let’s say an ellipse?

Create a rectangular form, set the TransparencyKey property to the same value as BackColor, which will effectively make the background of the form transparent. Then set the FormBorderStyle to FormBorderStyle.None, which will remove the contour and contents of the form.

13. How do you create a separator in the Menu Designer?

A hyphen ‘-’ would do it. Also, an ampersand ‘&\’ would underline the next letter.

14. How’s anchoring different from docking?

Anchoring treats the component as having the absolute size and adjusts its location relative to the parent form. Docking treats the component location as absolute and disregards the component size. So if a status bar must always be at the bottom no matter what, use docking. If a button should be on the top right, but change its position with the form being resized, use anchoring

Web Service

This article will explain you everything about Web Services in .Net, so lets get started with Web Service

What is Web Service?
· Web Service is an application that is designed to interact directly with other applications over the internet. In simple sense, Web Services are means for interacting with objects over the Internet.
· Web Service is
o Language Independent
o Protocol Independent
o Platform Independent
o It assumes a stateless service architecture.
· We will discuss more on web service as the article proceed. Before that lets understand bit on how web service comes into picture.
History of Web Service or How Web Service comes into existence?
· As i have mention before that Web Service is nothing but means for Interacting with objects over the Internet.
· 1. Initially Object - Oriented Language comes which allow us to interact with two object within same application.
· 2. Than comes Component Object Model (COM) which allows to interact two objects on the same computer, but in different applications.
· 3. Than comes Distributed Component Object Model (DCOM) which allows to interact two objects on different computers, but within same local network.
· 4. And finally the web services, which allows two object to interact internet. That is it allows to interact between two object on different computers and even not within same local network.
Example of Web Service
· Weather Reporting: You can use Weather Reporting web service to display weather information in your personal website.
· Stock Quote: You can display latest update of Share market with Stock Quote on your web site.
· News Headline: You can display latest news update by using News Headline Web Service in your website.
· In summary you can any use any web service which is available to use. You can make your own web service and let others use it. Example you can make Free SMS Sending Service with footer with your companies advertisement, so whosoever use this service indirectly advertise your company... You can apply your ideas in N no. of ways to take advantage of it.

Web Service Communication
Web Services communicate by using standard web protocols and data formats, such as
· HTTP
· XML
· SOAP
Advantages of Web Service Communication
Web Service messages are formatted as XML, a standard way for communication between two incompatible system. And this message is sent via HTTP, so that they can reach to any machine on the internet without being blocked by firewall.
Terms which are frequently used with web services
· What is SOAP?
o SOAP are remote function calls that invokes method and execute them on Remote machine and translate the object communication into XML format. In short, SOAP are way by which method calls are translate into XML format and sent via HTTP.
· What is WSDL?
o WSDL stands for Web Service Description Language, a standard by which a web service can tell clients what messages it accepts and which results it will return.
o WSDL contains every details regarding using web service
§ Method and Properties provided by web service
§ URLs from which those method can be accessed.
§ Data Types used.
§ Communication Protocol used.
· What is UDDI?
o UDDI allows you to find web services by connecting to a directory.
· What is Discovery or .Disco Files?
o Discovery files are used to group common services together on a web server.
o Discovery files .Disco and .VsDisco are XML based files that contains link in the form of URLs to resources that provides discovery information for a web service.
o .Disco File (static)
§ .Disco File contains
§ URL for the WSDL
§ URL for the documentation
§ URL to which SOAP messages should be sent.
§ A static discovery file is an XML document that contains links to other resources that describe web services.
o .VsDisco File (dynamic)
§ A dynamic discovery files are dynamic discovery document that are automatically generated by VS.Net during the development phase of a web service.
· What is difference between Disco and UDDI?
o Disco is Microsoft's Standard format for discovery documents which contains information about Web Services, while UDDI is a multi-vendor standard for discovery documents which contains information about Web Services.
· What is Web Service Discovery Tool (disco.exe) ?
o The Web Services Discovery Tool (disco.exe) can retrieve discovery information from a server that exposes a web service.
· What is Proxy Class?
o A proxy class is code that looks exactly like the class it meant to represent; however the proxy class doesn't contain any of the application logic. Instead, the proxy class contains marshalling and transport logic.
o A proxy class object allows a client to access a web service as if it were a local COM object.
o The Proxy must be on the computer that has the web application.
· What is Web Service Description Language Tool (wsdl.exe)?
o This tool can take a WSDL file and generate a corresponding proxy class that you can use to invoke the web service.
o Alternate of generating Proxy class through WSDL.exe is you can use web reference. Web Reference automatically generate a proxy classes for a web service by setting a web reference to point to the web service.
o Advantage of using Web Reference as compare to using WSDL.exe Tool is you can update changes done in web service class easily by updating web reference, which is more tedious task with WSDL.exe tool.
· Testing a Web Service?
o You can test web service without building an entire client application.
§ With Asp.net you can simply run the application and test the method by entering valid input paramters.
§ You can also use .Net Web Service Studio Tool comes from Microsoft.

Example of Creating Web Service in .Net

This Web Service will retrieve CustomerList Country Wise and return as dataset to client application for display.

Step1: Create a Web Service Application by File > New > Web Site > Asp.net Web Services
Named the web service, for example here i have choosen name "WSGetCustomerCountryWise"

Step2: Rename the default Service.asmx file to proper name, you also need to switch design view and change the class name with the same name you use to rename the service.asmx.
For example, "WSGetCustomerCountryWise.asmx" and switch to design view and change the class="Service" to class="WSGetCustomerCountryWise"

Step3: Rename the Service.CS File to proper name, you need to change the class name and constructor name too.
For example, "WSGetCustomerCountryWise.CS" and switch to code view and change the class and constructor name to "WSGetCustomerCountryWise"

After three steps your solution explorer looks as shown in figure




Step4: Create a Logic for Web Service
· Create a Method "GetCustomerCountryWise"
· Note: You need to specify [WebMethod] before method definition, if you want it to be accessible public, otherwise the method would not be accessible remotely.
· Specify proper argument and return type for method in web service.
· It is also good practise to specify the use "Description" attribute to tell what method is meant for.
For example, here i need to access data of northwind customers and want to return customer list country wise, so add namespace for

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

[WebMethod(Description="It will generate Customer List, Country Wise")] public System.Xml.XmlElement GetCustomerCountryWise(string sCountry)
{
string sConn = ConfigurationManager.ConnectionStrings["connStr"].ToString();

string sSQL = "select CustomerId, CompanyName, ContactTitle, City " +
" from Customers where country = '" + sCountry + "'";

SqlConnection connCustomer = new SqlConnection(sConn);

DataSet dsCustomer = new DataSet();

SqlDataAdapter daCustomer = new SqlDataAdapter(sSQL, sConn);

daCustomer.Fill(dsCustomer,"Customers");

//Known bug while return "DataSet" is "Data source is an invalid type.
It must be either an IListSource, IEnumerable, or IDataSource."
//For more details on Error: http://support.microsoft.com/kb/317340

//So to access data we need to make use of XmlElement.

// Return the DataSet as an XmlElement.
System.Xml.XmlDataDocument xdd = new System.Xml.XmlDataDocument(dsCustomer);
System.Xml.XmlElement docElem = xdd.DocumentElement;
return docElem;
}

Step5: Build Web Service and Run the Web Service for testing by pressing F5 function key.






By pressing "Invoke" button will generate XML File.

So you are done creating web service application.

Example of Testing Web Service in .Net

This Web Service will display the information which had been retrieved from Remote computer by accessing public method "GetCustomerCountryWise".

Step1: Create a Test Web Site by File > New > Web Site > Asp.net Web Site
Named the web site, for example here i have choosen name "TestGetCustomerCountryWise"

Step2: Displaying data in gridview, so drag the gridview on to the form.

Step3: Right Click Solution Explorer and Choose "Add Web Reference"



Step4: Choose the option Web Service on the local machine or you can enter the .WSDL File address directly in URL space and press Go button.




Step5: Press "Add Reference button"


Step6: Writing Code for Displaying data in GridView
Here note: I have Pass "USA" as parameter in Country Field.

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Create object of WSGetCustomerCountryWise Object
localhost.WSGetCustomerCountryWise objGetCustomerCountryWise
= new localhost.WSGetCustomerCountryWise();

DataSet dsCustomer = new DataSet();

// Get the data from Webservice.
XmlElement elem = objGetCustomerCountryWise.GetCustomerCountryWise("USA");

// Load the XML to the Typed DataSet that you want.
XmlNodeReader nodeReader = new XmlNodeReader(elem);
dsCustomer.ReadXml(nodeReader, XmlReadMode.Auto);

GridView1.DataSource = dsCustomer;

GridView1.DataBind();
}
}


Step7: Output as data displayed in GridView.




Few Facts about Web Service in .Net
· Each Response from web service is a new object, with a new state.
· Web Service are asynchronous because the request object from the client application and the response object from the web service are unique SOAP envelopes that do not require shared connection.
· This allow client application and the web service to continue processing while the interaction is ongoing.
· Instead of a user interface, it provides a standard defined interface called a contract.
Posted by Subhash at 2:21 AM 2 comments
Friday, February 29, 2008
This is the Code for sending an e-mail with attachment and without attachments (Asp.net & C#.net)

In Desing Page take a text boxes controls for from,to,Bcc,Subject,messages
and a fileupload control for Attachment and one button control to send the mail
In button control writethe following code:
Using.System.IO;
Using .System.web.mail;
protected void btnSubmit_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
mail.From = txtFrom.Text;
mail.To = txtTo.Text;
mail.Bcc = txtbcc.Text;
mail.Subject = txtSubject.Text;
mail.Body = txtMsg.Text;
mail.BodyFormat = MailFormat.Html;
//string s;
if (txtFile.Value == “”)
{
try
{
SmtpMail.Send(mail);
}
catch (Exception ex)
{
Response.Write(”Exception Occured: ” + ex);
}
finally
{
Response.Write(”Your E-mail has been sent sucessfully”);
}
}
else
{
string strdir = “D:\\temp\\”;
string strfilename = Path.GetFileName(txtFile.PostedFile.FileName);
txtFile.PostedFile.SaveAs(strdir + strfilename);
mail.Attachments.Add(new MailAttachment(strdir + strfilename));
try
{
SmtpMail.Send(mail);
}
catch (Exception ex)
{
Response.Write(”Exception Occured: ” + ex);
}
finally
{
Response.Write(”Your E-mail has been sent sucessfully”);
}
// Uploaded file deleted after sending e-mail
File.Delete(strdir + strfilename);
}
}

Dot Net - Asp.Net - Basic II

Dot Net - Asp.Net - Basic II
1 . What is the difference between URL and URI?
A URL is the address of some resource on the Web, which means that normally you type the address into a browser and you get something back. There are other type of resources than Web pages, but that's the easiest conceptually. The browser goes out somewhere on the Internet and accesses something.
A URI is just a unique string that uniquely identifies something, commonly a namespace. Sometimes they look like a URL that you could type into the address bar of your Web browser, but it doesn't have to point to any physical resource on the Web. It is just a unique set of characters, that, in fact, don't even have to be unique.
URI is the more generic term, and a URL is a particular type of URI in that a URL has to uniquely identify some resource on the Web.
2 . How to convert milliseconds into time?
VB.NET
dim ts as TimeSpan = TimeSpan.FromMilliseconds(10000)
Response.Write (ts.ToString () )

C#

TimeSpan ts = TimeSpan.FromMilliseconds(10000);
Response.Write (ts.ToString () );
3 . How to include multiple vb/cs files in the source?

You can do this using assembly directives.

<%@ assembly src="test1.vb" %>
<%@ assembly src="test2.vb" %>

or

<%@ assembly src="test1.cs" %>
<%@ assembly src="test2.cs" %>


However, note that each source file will be compiled individually into its own assembly, so they cannot have dependencies on each other.
4 . How to convert a string to Proper Case?
Use the namespace System.Globalization
VB.NET

Dim myString As String = "syncFusion deVeloPer sUppOrt"
' Creates a TextInfo based on the "en-US" culture.
Dim TI As TextInfo = New CultureInfo("en-US", False).TextInfo
Response.Write(TI.ToTitleCase(myString))

C#

string myString = "syncFusion deVeloPer sUppOrt";
// Creates a TextInfo based on the "en-US" culture.
TextInfo TI = new CultureInfo("en-US",false).TextInfo;
Response.Write (TI.ToTitleCase( myString ));

For more details refer TextInfo.ToTitleCase()
5 . How can I ensure that application-level variables are not updated by more than one user simultaneously?
Use the HttpApplicationState's Lock and UnLock methods.

For more details refer : MSDN: Application State
6 . Why do I get the error message "System.InvalidOperationException: It is invalid to show a modal dialog or form when the application is not running in UserInteractive mode. Specify the ServiceNotification or DefaultDesktopOnly style to display a ...."?

You can't use MsgBox or MessageBox.Show in ASP.NET WebForm. You maybe use:
VB.NET

Response.Write("")

C#

Response.Write("") ;
7 . How to validate that a string is a valid date?
VB.NET

Dim blnValid As Boolean = False
Try
DateTime.Parse(MyString)
blnValid = True
Catch
blnValid = False
End Try

C#

bool blnValid=false;
try
{
DateTime.Parse(MyString);
blnValid=true;
}
catch
{
blnValid=false;
}
8 . Are namespaces and Class names Case Sensitive?
Namespaces and Class names are case Sensitive. Namespaces imported using the @ Import Directive will cause an error if the correct case is not used.
9 . How to convert string to a DateTime and compare it with another DateTime?
VB.NET
Dim blntimeIsOk As Boolean = DateTime.Parse("15:00") < DateTime.Parse("08:00")
Response.Write(blntimeIsOk)

C#

bool blntimeIsOk = (DateTime.Parse("15:00") < DateTime.Parse("08:00"));
Response.Write (blntimeIsOk);
10 . How to get the url of page dynamically?
Use Request.Url property
11 . How to convert user input in dMy format to Mdy?
VB.NET

Dim dt As DateTime = DateTime.ParseExact("0299", New String() {"My", "M/y"}, Nothing, System.Globalization.DateTimeStyles.None)

C#

DateTime dt = DateTime.ParseExact("0299", new string[] {"My","M/y"}, null,System.Globalization.DateTimeStyles.None);

or more details refer DateTime.ParseExact
12 . When the User is prompted a File Download dialogbox, if the user selects "Save" then the "Save as" dialog box is displayed. Is there any way for me to retrieve the filename and directory path specified by the user on the File Download dialog box?
Clients do not report information back about where the user selects to save the content, so there isn't an easy way to do this. Instead, you would need to ask the user before using the content-disposition for a file path, and then you could specify the filename parameter for the content-disposition header. Still, the user is free to change that path when actually downloading.
13 . How to hide or show Controls in server side code?
In any appropriate event write
VB.NET

TextBox1.Visible =not TextBox1.Visible

C#

TextBox1.Visible =!TextBox1.Visible ;
14 . How to check if the user is using a secure or non secure connection?

The Request Object defines a Property called IsSecureConnection, that will indicate whether http:// or https:// has been used.
15 . Is it possible to write code in many languages in one ASP.NET project?
You cannot write the code-behind files in different languages in the same project, but you can write the aspx pages and ascx controls in different languages.
16 . What is the difference between Response.Redirect() and Server.Transfer().
Response.Redirect

* Tranfers the page control to the other page, in other words it sends the request to the other page.
* Causes the client to navigate to the page you are redirecting to. In http terms it sends a 302 response to the client, and the client goes where it's told.
Server.Transfer
* Only transfers the execution to another page and during this you will see the URL of the old page since only execution is transfered to new page and not control.
* Occurs entirely on the server, no action is needed by the client
Sometimes for performance reasons, the server method is more desirable
17 . How to get the hostname or IP address of the server?
You can use either of these:

* HttpContext.Current.Server.MachineName
* HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"]

The first one should return the name of the machine, the second returns the local ip address.
Note that name of the machine could be different than host, since your site could be using host headers
18 . What is the meaning of validateRequest=true in .net framework1.1?
The value of validateRequest is set to 'true' by default, which means that the framework will automatically deny submission of the '<' and '>' characters.
19 . What is the different between <%# %> and <%= %>?
The <%# %> is used for databinding where as <%= %> is used to output the result of an expression. The expression inside <%# %> will be executed only when you call the page's or control's DataBind method. The expression inside <%= %> will be executed and displayed as and when it appears in the page.
20 . What permissions do ASP.NET applications posses by default?
By default ASP.NET Web applications run as ASP.NET user. This user has limited permissions equivalent to the User Group.
21 . How can I specify the relative path for a file?
Suppose you have following file hierarchy:

default.aspx
Admin/login.aspx
Misc/testpage.aspx


And you are on the login.aspx and want your user to navigate to the default.aspx (or testpage.aspx) file. Then you can use

* Response.Redirect ("../default.aspx")
* Response.Redirect ("../Misc/testpage.aspx")

22 . How can I specify the "upload a file" input textbox in a form to be read only so that the user can click on the browse button and pick a file but they cannot type anything into the textbox next to the browse button.

23 . How to change the Page Title dynamically?




VB.NET

'Declare
Protected WithEvents Title1 As System.Web.UI.HtmlControls.HtmlGenericControl

'In Page_Load
Title1.InnerText ="Page 1"


C#

//Declare
protected System.Web.UI.HtmlControls.HtmlGenericControl Title1 ;

//In Page_Load
Title1.InnerText ="Page 1" ;
24 . Why do I get the error message "Object must implement IConvertible". How can I resolve it?
The common cause for this error is specifying a control as a SqlParameter's Value instead of the control's text value.
For example, if you write code as below you'll get the above error:

VB.NET

Dim nameParameter As SqlParameter = command.Parameters.Add("@name", SqlDbType.NVarChar, 50)
nameParameter.Value = txtName

C#

SqlParameter nameParameter = command.Parameters.Add("@name", SqlDbType.NVarChar, 50);
nameParameter.Value = txtName ;


To resolve it, specify the control's Text property instead of the control itself.

VB.NET

nameParameter.Value = txtName.Text


C#

nameParameter.Value =txtName.Text;
25 . Why is default.aspx page not opened if i specify http://localhost. I am able to view this page if i hardcode it as http://localhost/default.aspx?
If some other default page comes higher in the list, adjust the default.aspx to be the number one entry inside the IIS configuration. If you have multiple websites inside IIS, make sure the configuration is applied on the right website (or on all websites by applying the configuration on the server-level using the properties dialog, configure WWW service).
26 . Can ASP.NET work on an NT server?
No. For more details refer ASP 1.1 version
27 . Is it possible to migrate Visual InterDev Design-Time Controls to ASP.NET?
Refer INFO: Migrating Visual InterDev Design-Time Controls to ASP.NET
28 . How to automatically get the latest version of all the asp.net solution items from Source Safe when opening the solution?
In VS.NET you can go to Tools > Options > Source Control > General and check the checkbox for Get everything when a solution opens.
This retrieves the latest version of all solution items when you open the solution.
29 . How to make VS.Net use FlowLayout as the default layout rather than the GridLayout?
For VB.NET, go to path C:\Program Files\Microsoft Visual Studio .NET\Vb7\VBWizards\WebForm\Templates\1033
Change the following line in the existing WebForm1.aspx




to
For C#, go to path C:\Program Files\Microsoft Visual Studio .NET 2003\VC#\VC#Wizards\CSharpWebAppWiz\Templates\1033
Change the following line in the existing WebForm1.aspx



to

Note:Before changing any templates it's a good idea to make backup copies of them
Or rather than above approach you can change the behavior for new files on a per project basis in Visual Studio by:

1. Right clicking on the project name (Ex: "WebApplication1)" in Solution Explorer, and select "Properties".
2. From project properties window, under Common Properties>Designer Defaults>Page Layout change "Grid" to "Flow".

30 . Can I use a DataReader to update/insert/delete a record?
No. DataReader provides a means of reading a forward-only stream of rows from a database.
31 . How to format a Telphone number in the xxx-xxx-xxxx format?
VB.NET
Dim Telno As Double = Double.Parse(ds.Tables(0).Rows(0)("TelNo").ToString())
Response.Write(Telno.ToString("###-###-####"))

C#

double Telno= double.Parse(ds.Tables[0].Rows[0]["TelNo"].ToString());
Response.Write(Telno.ToString("###-###-####"));
32 . Can two different programming languages be mixed in a single ASPX file?
No. ASP.NET uses parsers to strip the code from ASPX files and copy it to temporary files containing derived Page classes, and a given parser understands only one language
33 . Can I use custom .NET data types in a Web form?
Yes. Place the DLL containing the type in the application root's bin directory and ASP.NET will automatically load the DLL when the type is referenced. This is also what happens when you add a custom control from the toolbox to your web form.
34 . How can I have a particular Web page in an ASP.NET application which displays its own error page.

This can be done by setting the ErroPage attribute of Page Directive or ErrorPage property of Page Class to the desired Custom Error Page

<%@Page Language="C#" ErrorPage="specificerropage.htm"%>

In web.config

Dot Net - Asp.Net - Basic I

Dot Net - Asp.Net - Basic I
1 . What is ASP.NET?
ASP.NET is a programming framework built on the common language runtime that can be used on a server to build powerful Web applications.
2 . Why does my ASP.NET file have multiple tag with runat=server?
This means that ASP.Net is not properly registered with IIS.
.Net framework provides an Administration utility that manages the installation and uninstallation of multiple versions of ASP.NET on a single machine. You can find the file in C:\WINNT\Microsoft.NET\Framework\v**\aspnet_regiis.exe

use the command: aspnet_regiis.exe -u ---> to uninstall current asp.net version.
use the command: aspnet_regiis.exe -i ---> to install current asp.net version.


For Windows Server 2003, you must use aspnet_regiis -i -enable
This is because of the "Web Service Extensions" feature in IIS 6

(if you install VS.NET or the framework without IIS installed, and then go back in and install IIS afterwards, you have to re-register so that ASP.NET 'hooks' into IIS properly."
3 . How to find out what version of ASP.NET I am using on my machine?
VB.NET

Response.Write(System.Environment.Version.ToString() )

C#

Response.Write(System.Environment.Version.ToString() );
4 . Is it possible to pass a querystring from an .asp page to aspx page?
Yes you can pass querystring from .asp to ASP.NET page .asp
<%response.redirect "webform1.aspx?id=11"%>
.aspx
VB.NET
Response.Write (Request("id").ToString ())

C#
Response.Write (Request["id"].ToString ());
5 . How to comment out ASP.NET Tags?
Label
6 . What is a ViewState?
In classic ASP, when a form is submitted the form values are cleared. In some cases the form is submitted with huge information. In such cases if the server comes back with error, one has to re-enter correct information in the form. But submitting clears up all form values. This happens as the site does not maintain any state (ViewState).

In ASP .NET, when the form is submitted the form reappears in the browser with all form values. This is because ASP .NET maintains your ViewState. ViewState is a state management technique built in ASP.NET. Its purpose is to keep the state of controls during subsequent postbacks by the same user. The ViewState indicates the status of the page when submitted to the server. The status is defined through a hidden field placed on each page with a control.

If you want to NOT maintain the ViewState, include the directive <%@ Page EnableViewState="false"%> at the top of an .aspx page If you do not want to maintain Viewstate for any control add the attribute EnableViewState="false" to any control. For more details refer The ASP.NET View State
7 . Where can I get the details on Migration of existing projects using various technologies to ASP.NET?

Microsoft has designed Migration Assistants to help us convert existing pages and applications to ASP.NET. It does not make the conversion process completely automatic, but it will speed up project by automating some of the steps required for migration.
Below are the Code Migration Assistants

* ASP to ASP.NET Migration Assistant
* PHP to ASP.NET Migration Assistant
* JSP to ASP.NET Migration Assistant

Refer Migrating to ASP.Net
8 . What is the equivalent of date() and time() in ASP.NET?
VB.NET

System.DateTime.Now.ToShortDateString()
System.DateTime.Now.ToShortTimeString()

C#
System.DateTime.Now.ToShortDateString();
System.DateTime.Now.ToShortTimeString();
9 . How to prevent a button from validating it's form?
Set the CauseValidation property of the button control to False
10 . How to get the IP address of the host accessing my site?
VB.NET

Response.Write (Request.UserHostAddress.ToString ())

C#

Response.Write (Request.UserHostAddress.ToString ());
11 . How to access the Parameters passed in via the URL?

Call the Request.QueryStringmethod passing in the key. The method will return the parameter value associated with that key. VB.NET

Request.QueryString("id")


C#

Request.QueryString["id"];
12 . How to display a Wait page while a query is running?
Refer Asynchronous Wait State Pattern in ASP.NET
13 . How to implement Form based Authentication in ASP.NET application?

For
* VB.NET
* C#
14 . How to catch the 404 error in my web application and provide more useful information?

In the global.asax Application_error Event write the following code

VB.NET

Dim ex As Exception = Server.GetLastError().GetBaseException()
If TypeOf ex Is System.IO.FileNotFoundException Then
'your code
'Response.Redirect("err404.aspx")
Else
'your code
End If


C#

Exception ex = Server.GetLastError().GetBaseException();
if (ex.GetType() == typeof(System.IO.FileNotFoundException))
{
//your code
Response.Redirect ("err404.aspx");
}
else
{
//your code
}
15 . Is there a method similar to Response.Redirect that will send variables to the destination page other than using a query string or the post method?
Server.Transfer preserves the current page context, so that in the target page you can extract values and such. However, it can have side effects; because Server.Transfer doesnt' go through the browser, the browser doesn't update its history and if the user clicks Back, they go to the page previous to the source page.

Another way to pass values is to use something like a LinkButton. It posts back to the source page, where you can get the values you need, put them in Session, and then use Response.Redirect to transfer to the target page. (This does bounce off the browser.) In the target page you can read the Session values as required.

Refer to Passing Values Between Web Forms Pages for more information.
16 . What are the differences between HTML versus Server Control?
Refer

* ASP.NET Server Controls Recommendations
* Introduction to ASP.NET Server Controls
17 . How can I change the action of a form through code?
You can't change it. The action attribute is owned by ASP.NET. Handle Events and Transfer.

For work around refer to Paul Wilson's Multiple Forms and Non-PostBack Forms - Solution
18 . Is there any control that allows user to select a time from a clock - in other words is there a clock control?
Peter Blum has developed some controls. Check out Peter's Date Package: TimeOfDayTextBox and DurationTextBox Controls
19 . How to Compare time?
VB.NET

Dim t1 As String = DateTime.Parse("3:30 PM").ToString("t")
Dim t2 As String = DateTime.Now.ToString("t")
If DateTime.Compare(DateTime.Parse(t1), DateTime.Parse(t2)) < 0 Then
Response.Write(t1.ToString() & " is < than " & t2.ToString())
Else
Response.Write(t1.ToString() & " is > than " & t2.ToString())
End If


C#

string t1 = DateTime.Parse("3:30 PM").ToString("t");
string t2 = DateTime.Now.ToString("t");
if (DateTime.Compare(DateTime.Parse (t1), DateTime.Parse (t2)) < 0 )
{
Response.Write(t1.ToString() + " is < than " + t2.ToString());
}
else
{
Response.Write(t1.ToString() + " is > than " + t2.ToString());
}

20 . How To work with TimeSpan Class?
VB.NET

Dim adate As DateTime = DateTime.Parse("06/24/2003")
Dim bdate As DateTime = DateTime.Parse("06/28/2003")
Dim ts As New TimeSpan(bdate.Ticks - adate.Ticks)
Response.Write(ts.TotalDays & "
")
Response.Write(ts.TotalHours & ":" & ts.TotalMinutes & ":" & ts.TotalSeconds & ":" & ts.TotalMilliseconds)


C#

DateTime adate = DateTime.Parse("06/24/2003");
DateTime bdate = DateTime.Parse("06/28/2003");
TimeSpan ts = new TimeSpan (bdate.Ticks - adate.Ticks);
Response.Write(ts.TotalDays.ToString () + "
");
Response.Write(ts.TotalHours.ToString() + ":" + ts.TotalMinutes.ToString() + ":" + ts.TotalSeconds.ToString() + ":" + ts.TotalMilliseconds.ToString() );
21 . Where can I get information on Cookies in ASP.NET?
Refer Mike Pope's article Basics of Cookies in ASP.NET
22 . Does ASP.Net still recognize the global.asa file?
ASP.Net does not recognize the standard ASP global.asa file. Instead it uses a file named global.asax with the same - plus additional - functionality.
23 . How should I destroy my objects in ASP.Net?
ASP.Net actually has very solid internal garbage collection. So this is not an issue as it was in previous versions of Active Server Pages.
Link to more information: Element
24 . Are there resources online with tips on ASP to ASP.Net conversions?
Microsoft has deisnged The ASP to ASP.NET Migration Assistant help us convert ASP pages and applications to ASP.NET. It does not make the conversion process completely automatic, but it will speed up project by automating some of the steps required for migration.

The following Code Migration Assistants are discussed in the link below.

* ASP to ASP.NET Migration Assistant
* PHP to ASP.NET Migration Assistant
* JSP to ASP.NET Migration Assistant

Refer Migrating to ASP.Net

Also refer:

* Microsoft's ASP to ASP.NET Code Migration Assistant
* John Peterson's article Microsoft's ASP to ASP.NET Migration Assistant
* Paolo Cavone's article From ASP to ASP.NET... Painlessly!

25 . How do I publish my ASP.NET application to my ISP's web server?
Your ISP must first create an IIS application and apply the Front Page Server Extensions to it. Then in Visual Studio .NET, select the "Project Copy Project" menu. Then enter the URL and select the FrontPage web access method. The "Copy Project" feature copies all of the necessary files to your ISP's machine for your ASP.NET application to run.

You can also FTP your files to your ISP web server. But you must know which files to upload. For more details refer PRB: Remote ASP.NET Projects Require IIS on the Client Computer or FrontPage Server Extensions on the Server Computer
26 . Why do i get error message "Could not load type" whenever I browse to my ASP.NET web site?

Your code-behind files for either your .aspx or the global.aspx page have not been complied. Use Visual Studio .NET's "Build Build Solution" menu, or run the command line compiler.

For more details refer PRB: "Could not load type" error message when you browse to .aspx page
27 . Will the WebMatrix SqlDataSourceControl work with a MySQL connection?

SqlDataSourceControl lets you connect and work with MS SQL DB, while AccessDataSourceControl do the same thing but for MS Access DB. Therefore SqlDataSourceControl can't help you in your MySql connectivity .
For Connectivity with MySql refer Accessing MySQL Database with ASP.NET
28 . Can I combine classic ASP and ASP.NET pages?

No.
ASP pages can run in the same site as ASP.NET pages, but you can't mix in a page. Also ASP and ASP.NET won't share their session.
29 . What is the difference between src and Code-Behind?

Src attribute means you deploy the source code files and everything is compiled JIT (just-in-time) as needed. Many people prefer this since they don't have to manually worry about compiling and messing with dlls -- it just works. Of course, the source is now on the server, for anyone with access to the server -- but not just anyone on the web.

CodeBehind attribute doesn't really "do" anything, its just a helper for VS.NET to associate the code file with the aspx file. This is necessary since VS.NET automates the pre-compiling that is harder by hand, and therefore the Src attribute is also gone. Now there is only a dll to deploy, no source, so it is certainly better protected, although its always decompilable even then.
30 . How can I get the value of input box with type hidden in code-behind?

You can set the runat= server for the hidden control and you can use ControlName.Value to get its value in CodeBehind file

31 . I have created a .NET user control page (.ascx) but I cannot compile and run it.

User control (ascx) can't be run on it own, but you can drag it onto any web page (aspx) and then run it.
32 . What is a .resx file?

The .resx resource file format consists of XML entries, which specify objects and strings inside XML tags. This is useful for localization. For more details refer Resources in .resx files
33 . Is it possible to use a style sheet class directly on a control instead of using inline or page-level formatting ?

Every WebControl derived control has a CssClass property which allows you to set it's format to a style sheet.
34 . Can I recieve both HTML markup for page and code in the ASP.NET web page's source code portion in the Web browser?

No. The Web browser recieves only HTML markup.
No source code or web control syntax is passed back to the web browser.
35 . Why can't I put <%@ Page Language="C " %> where at the top of an ASPX file and write my server-side scripts in C ?

The parsers ASP.NET uses to extract code from ASPX files understand C#, Visual Basic.NET, and JScript.NET. You can write server-side scripts in any language supported by a .NET compiler.
36 . ASP pages that worked pefectly on Windows 2000 Server and IIS 5.0 do not work on Windows 2003 Server with IIS 6.0. ASP.NET pages work fine. Why?

Start -> Settings -> Control Panel -> Administrative Tools -> and double clicking IIS Manager.
Go to the Web Service Extensions tab, click Active Server Pages, then press the "Allow" button on the left
37 . Why do I get error message "Error creating assembly manifest: Error reading key file 'key.snk' -- The system cannot find the file specified"?

Check the location of the key.snk file relative to the assembly file. Provide an explicit path or a relative path.


38 . How to get URL without querystring?
VB.NET

Dim stringUri As String = "http://www.syncfusion.com/?id=1&auid=16"
Dim weburi As Uri = New Uri(stringUri)
Dim query As String = weburi.Query
Dim weburl As String = stringUri.Substring(0, stringUri.Length - query.Length)
Response.Write(weburl)


C#

string stringUri = "http://www.syncfusion.com/?id=1&auid=16";
Uri weburi = new Uri(stringUri);
string query = weburi.Query;
string weburl = stringUri.Substring(0, stringUri.Length - query.Length);
Response.Write (weburl);
39 . What is the best way to output only time and not Date?
Use DateTime as follows VB.NET

Response.Write(DateTime.Now.ToString("hh:mm:ss"))


C#

Response.Write(DateTime.Now.ToString("hh:mm:ss"));
40 . Do I have to compile code if I am changing the content of my aspx.cs file?
Yes if you have used Codebehind="my.aspx.cs".
Not if you used src="my.aspx.cs" in your page declaration.
41 . How to grab the referring URL?
VB.NET

Response.Write ( Request.UrlReferrer.ToString())

C#
Response.Write ( Request.UrlReferrer.ToString());
42 . My ASP code gives an error "Compiler Error Message: BC30289: Statement cannot appear within a method body. End of method assumed" when changed to .aspx?
Use a block instead of the <% %> syntax to define Subs.
Make sure you have proper events associated with the code and have start and end of procedure or function wirtten properly.
43 . How can I save images ?
You need a stream to read the response, WebResponse.GetResponseStream(), and a stream to write it to the hard drive. FileStream should do the trick. You'll have to write to the filestream what you read from the response stream.
44 . How can I logout when using FormsAuthentication?
FormsAuthentication.SignOut()
45 . Why do I get a blank page when I use Server.Transfer("page1.htm") to transfer to a different page?
Server.Transfer only works with .aspx pages
You can't use Transfer method with HTML pages
46 . How to detect the User's culture?
VB.NET
Dim sLang As String
sLang = Request.UserLanguages(0)
Response.Write(sLang)

C#
string sLang ;
sLang = Request.UserLanguages[0];
Response.Write (sLang);
47 . What is the difference between CurrentCulture property and the CurrentUICulture property?
# CurrentCulture property : affects how the .NET Framework handles dates, currencies, sorting and formatting issues
# CurrentUICulture property : determines which satellite assembly is used when loading resources
48 . Can I read the hard disk serial # of the client computer using ASP.NET?
No. Such information is not passed to the server with a http request.
49 . What is xxx(src As Object, e As EventArgs)?
xxx is an event handler
src is the object that fires the event
e is an event argument object that contains more information about the event
An event handler is used when one object wants to be notified when an event happens in another object
50 . What is the difference between Absolute vs Relative URLs?
Absolute /Fully Qualified URLs:
* Contain all information necessary for the browser(or other client program) to locate the resource named in the URL
o This includes protocol moniker used( i.e http://, ftp://..etc..), Server's Domain name or IP address and the file path
o Absolute URL looks as http://localhost/megasolutions/page1.aspx
Relative URLs:
* Only provide information necessary to locate a resource relative to the current document(document relative) or current server or domain(root relative)
o Document relative URL - page1.aspx
o Root Relative URL - /megasolutions/Admin/pagelog.aspx

Dot Net - Asp.Net

Dot Net - Asp.Net

1 . Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process.
inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a file with .aspx extension), the ISAPI filter aspnet_isapi.dll takes care of it by passing the request tothe actual worker process aspnet_wp.exe.
2 . What’s the difference between Response.Write() andResponse.Output.Write()?
Response.Output.Write() allows you to write formatted output.
3 . What methods are fired during the page load?
Init() - when the page is instantiated
Load() - when the page is loaded into server memory
PreRender() - the brief moment before the page is displayed to the user as HTML
Unload() - when page finishes loading.
4 . When during the page processing cycle is ViewState available?
After the Init() and before the Page_Load(), or OnLoad() for a control.
5 . What namespace does the Web page belong in the .NET Framework class hierarchy?
System.Web.UI.Page
6 . Where do you store the information about the user’s locale?
System.Web.UI.Page.Culture
7 . What’s the difference between Codebehind="MyCode.aspx.cs" andSrc="MyCode.aspx.cs"?
CodeBehind is relevant to Visual Studio.NET only.
8 . What’s a bubbled event?
When you have a complex control, like DataGrid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents.
9 . Suppose you want a certain ASP.NET function executed on MouseOver for a certain button. Where do you add an event handler?
Add an OnMouseOver attribute to the button. Example: btnSubmit.Attributes.Add("onmouseover","someClientCodeHere();");
10 . What data types do the RangeValidator control support?
Integer, String, and Date.
11 . Explain the differences between Server-side and Client-side code?
Server-side code executes on the server. Client-side code executes in the client's browser.
12 . What type of code (server or client) is found in a Code-Behind class?
The answer is server-side code since code-behind is executed on the server. However, during the code-behind's execution on the server, it can render client-side code such as JavaScript to be processed in the clients browser. But just to be clear, code-behind executes on the server, thus making it server-side code.
13 . Should user input data validation occur server-side or client-side? Why?
All user input data validation should occur on the server at a minimum. Additionally, client-side validation can be performed where deemed appropriate and feasable to provide a richer, more responsive experience for the user.
14 . What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?
Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client's browser. This provides a faster response with a little less overhead on the server. Server.Transfer does not update the clients url history list or current url. Response.Redirect is used to redirect the user's browser to another page or site. This performas a trip back to the client where the client's browser is redirected to the new page. The user's browser history list is updated to reflect the new address.
15 . Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?
Valid answers are:
· A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.
· A DataSet is designed to work without any continuing connection to the original data source.
· Data in a DataSet is bulk-loaded, rather than being loaded on demand.
· There's no concept of cursor types in a DataSet.
· DataSets have no current record pointer You can use For Each loops to move through the data.
· You can store many edits in a DataSet, and write them to the original data source in a single operation.
· Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources.
16 . What is the Global.asax used for?
The Global.asax (including the Global.asax.cs file) is used to implement application and session level events.
17 . What are the Application_Start and Session_Start subroutines used for?
This is where you can set the specific variables for the Application and Session objects.
18 . Can you explain what inheritance is and an example of when you might use it?
When you want to inherit (use the functionality of) another class. Example: With a base class named Employee, a Manager class could be derived from the Employee base class.
19 . Whats an assembly?
Assemblies are the building blocks of the .NET framework. Overview of assemblies from MSDN
20 . Describe the difference between inline and code behind.
Inline code written along side the html in a page. Code-behind is code written in a separate file and referenced by the .aspx page.
21 . Explain what a diffgram is, and a good use for one?
The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML. A good use is reading database data to an XML file to be sent to a Web Service.
22 . Whats MSIL, and why should my developers need an appreciation of it if at all?
MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL. MSIL also allows the .NET Framework to JIT compile the assembly on the installed computer.
23 . Which method do you invoke on the DataAdapter control to load your generated dataset with data?
The Fill() method.
24 . Can you edit data in the Repeater control?
No, it just reads the information from its data source.
25 . Which template must you provide, in order to display data in a Repeater control?
ItemTemplate.
26 . How can you provide an alternating color scheme in a Repeater control?
Use the AlternatingItemTemplate.
27 . What property must you set, and what method must you call in your code, in order to bind the data from a data source to the Repeater control?
You must set the DataSource property and call the DataBind method.
28 . What base class do all Web Forms inherit from?
The Page class.
29 . Name two properties common in every validation control?
ControlToValidate property and Text property.
30 . Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box?
DataTextField property.
31 . Which control would you use if you needed to make sure the values in two different controls matched?
CompareValidator control.
32 . How many classes can a single .NET DLL contain?
It can contain many classes.
Web Service Questions
33 . What is the transport protocol you use to call a Web service?
SOAP (Simple Object Access Protocol) is the preferred protocol.
34 . What does WSDL stand for?
Web Services Description Language.
35 . Where on the Internet would you look for Web services?
http://www.uddi.org
36 . True or False: To test a Web service you must create a Windows application or Web application to consume this service?
False, the web service comes with a test page and it provides HTTP-GET method to test.
37 . Can you give an example of when it would be appropriate to use a web service as opposed to a non-serviced .NET component
Webservice is one of main component in Service Oriented Architecture. You could use webservices when your clients and servers are running on different networks and also different platforms. This provides a loosely coupled system. And also if the client is behind the firewall it would be easy to use webserivce since it runs on port 80 (by default) instead of having some thing else in SOA apps

State Management Questions
38 . What is ViewState?
ViewState allows the state of objects (serializable) to be stored in a hidden field on the page. ViewState is transported to the client and back to the server, and is not stored on the server or any other external source. ViewState is used the retain the state of server-side objects between postabacks.
39 . What is the lifespan for items stored in ViewState?
Item stored in ViewState exist for the life of the current page. This includes postbacks (to the same page).
40 . What does the "EnableViewState" property do? Why would I want it on or off?
It allows the page to save the users input on a form across postbacks. It saves the server-side values for a given control into ViewState, which is stored as a hidden value on the page before sending the page to the clients browser. When the page is posted back to the server the server control is recreated with the state stored in viewstate.
41 . What are the different types of Session state management options available with ASP.NET?
ASP.NET provides In-Process and Out-of-Process state management. In-Process stores the session in memory on the web server. This requires the a "sticky-server" (or no load-balancing) so that the user is always reconnected to the same web server. Out-of-Process Session state management stores data in an external data source. The external data source may be either a SQL Server or a State Server service. Out-of-Process state management requires that all objects stored in session are serializable.
42 . Let's say I have an existing application written using Visual Studio 6 (VB 6, InterDev 6) and this application utilizes Windows 2000 COM+ transaction services. How would you approach migrating this application to .NET
You have to use System.EnterpriseServices namespace and also COMInterop the existing application
43 . Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines?
In the Application_Start event you could store the data, which is used throughout the life time of an application for example application name, where as Session_Start could be used to store the information, which is required for that session of the application say for example user id or user name.
44 . If I'm developing an application that must accomodate multiple security levels though secure login and my ASP.NET web appplication is spanned across three web-servers (using round-robbin load balancing) what would be the best approach to maintain login-in state for the users?
Use the state server or store the state in the database. This can be easily done through simple setting change in the web.config.
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=sa;password="
cookieless="false"
timeout="30"
/>
in the above one instead of mode="InProc", you specifiy stateserver or sqlserver.
45 . What are ASP.NET Web Forms? How is this technology different than what is available though ASP (1.0-3.0)?
ASP.NET webforms are analogous to Windows Forms which are available to most VB developers. A webform is essentially a core container in a Page. An empty webform is nothing but a HTML Form tag(control) running at server and posting form to itself by default, but you could change it to post it to something else. This is a container, and you could place the web controls, user controls and HTML Controls in that one and interact with user on a postback basis.
46 . How does VB.NET/C# achieve polymorphism?
Polymorphism is achieved through virtual, overloaded, overridden methods in C# and VB.NET
47 . Describe session handling in a webform, how does it work and what are the its limits
Sometimes it is necessary to carry a particular session data across pages.
And HTTP is a stateless protocol. In order to maintain state between
page calls, we could use cookies, hidden form fields etc. One of them is
using sessions. each sessions are maintain a unique key on the server and
serialize the data on it. Actually it is a hashtable and stores data on key/value
pair of combination. You could set a session using Session Object and retrieve the same data/state
by passing the key.
//Set
Session["abc"] = "Session Value";
// Get
string abc = Session["abc"].ToString();
The downside of sessions is scalability. Say your application gets more and more hits
and you though instead of one webserver handling it, have it in a webfarm (multiple web
servers working under one domain). You cannot transfer the session so easily across multiple
webservers. Reason is like I said, it physically serializes the state data to webserver hard disk.
.NET proposes a new way to handle this using a stateserver (actually a trimmed down sql server)
storing the web session data in a factory configured database schema or using Database with your own
schema defined to handle the sessions.
48 . How would you get ASP.NET running in Apache web servers - why would you even do this?
You need to create a CLRHost, which hosts the CLR (ASP.NET) on top of Apache.
Since Apache is #1 webserver used by many companies, this would allow more number of web site owners
to take advantage of ASP.NET and its richness.
49 . Whats MSIL, and why should my developers need an appreciation of it if at all?
MSIL is Microsoft Intermediate (Intermediary) Language. It is Microsoft's implementation of CIL (standard recognized
by ECMA and ISO) as part of CLI and C# Standardization.

.NET supports more than 21 language (I think 24 now). They compile to IL first and then this IL would get JITted to Native
code at runtime. Learning IL is advantageous in many terms. The important one is sometimes you need to optimize your
code, so you could disassemble your compile assembly using ILDASM and tweak your code and re assemble it using ILASM.
50 . In what order do the events of an ASPX page execute. As a developer is it important to undertsand these events?

This is the order of Page events
i. Page_Init
ii.Page_LoadViewState
iii. Page_LoadPostData
iv. Page_Load
v. Page_RaisePostDataChanged
vi. Page_RaisePostBackEvent
vii. Page_PreRender
viii. Page_SaveViewState
ix. Page_Render
x. Page_Dispose
xii. Page_Error (this is caused whenever there is an exception at the page level).

Out of all the Page_Load is the one where your code gets loaded and your magic should be written. page_init
occurs only once, i.e. when the page is initially created.

As a developer you need to know these, becuase your development activity is coding for these only.
51 . Which method do you invoke on the DataAdapter control to load your generated dataset with data?
Fill()
52 . Can you edit data in the Repeater control?
No. Only DataList and DataGrid provide you editing capabilities.
53 . What method do you use to explicitly kill a user s session?
Session.Abandon
54 . How do you turn off cookies for one page in your site?
Actually I never did this. But there should be a way to do this. May be need to
write your own code to do this using Response.Cookies collection and HTTPCookie class and
also SessionStateMode. Or there may be some simple way to do it. Need to do further research on this.
55 . Which two properties are on every validation control?
The common properties are:
i. IsValid (bool)
ii. ControlToValidate (string)
iii. ErrorMessage (string)
iv. ValidationDisplay (Display)
v. Text (string)
The common method is:
Validate()
56 . What tags do you need to add within the asp:datagrid tags to bind columns manually?
You need to set AutoGenerateColumns Property to false.
57 . How do you create a permanent cookie?
If you are developing web services and the cookies need to be travelled across multiple requests, then
you need to have permanent or persistant cookie.
In order to do this, you have to set the your webserivce CookieContainer to a newly created CookieContainer, and the
its cookie to a session value and then store the cookie(s) into the Service CookieCollection from that cookie container
if something is there othere wise add cookie to the container.
58 . What tag do you use to add a hyperlink column to the DataGrid?

HyperLinkColumn
59 . What is the standard you use to wrap up a call to a Web service
SOAP.
60 . Which method do you use to redirect the user to another page without performing a round trip to the client?
Server.Transfer
Response.Redirect also does that but it requires round trip between client and server.
61 . What does WSDL stand for?
Web Services Description Language.
62 . True or False: A Web service can only be written in .NET
False.
63 . What property do you have to set to tell the grid which page to go to when using the Pager object?
CurrentPageIndex. You need to set this one with the DataGridPageChangedEventArgs' NewPageIndex.
64 . Which control would you use if you needed to make sure the values in two different controls matched?
Use CompareValidator
65 . True or False: To test a Web service you must create a windows application or Web application to consume this service?
False. The webservice comes with a test page and it provides HTTP-GET method to test.
And if the web service turned off HTTP-GET for security purposes then you need to create
a web application or windows app as a client to this to test.
66 . How many classes can a single .NET DLL contain?
many is correct. Yes an assembly can contain one or more classes and an assembly can
be contained in one dll or could spread across multiple dlls. too. Take System.dll, it is
collections of so many classes.
67 . Why would you use an array vs linked-list ?
Linked List:
? They allow a new element to be inserted or deleted at any position in a constant number of operations (changing some references) O(1).
? Easy to delete a node (as it only has to rearrange the links to the different nodes)., O(1).
? To find the nth node, will need to recurse through the list till it finds [linked lists allow only sequential access to elements. ], O(n)

Array
? Insertion or deletion of element at any position require a linear (O(n)) number of operations.
? Poor at deleting nodes (or elements) as it cannot remove one node without individually shifting all the elements up the list by one., O(n)
? Poor at inserting as an array will eventually either fill up or need to be resized, an expensive operation that may not even be possible if memory is fragmented. Similarly, an array from which many elements are removed may become wastefully empty or need to be made smaller, O(n)

? easy to find the nth element in the array by directly referencing them by their position in the array.[ arrays allow random access ] , O(1)

Dotnet FrameWork

Dot Net - .Net Basic , Framework and Advanced
1 . What is .NET?
.NET is a general-purpose software development platform, similar to Java. At its core is a virtual machine that turns intermediate language (IL) into machine code. High-level language compilers for C#, VB.NET and C++ are provided to turn source code into IL. C# is a new programming language, very similar to Java. An extensive class library is included, featuring all the functionality one might expect from a contempory development platform - windows GUI development (Windows Forms), database access (ADO.NET), web development (ASP.NET), web services, XML etc
See also Microsoft's definition
2 . When was .NET announced?
Bill Gates delivered a keynote at Forum 2000, held June 22, 2000, outlining the .NET 'vision'. The July 2000 PDC had a number of sessions on .NET technology, and delegates were given CDs containing a pre-release version of the .NET framework/SDK and Visual Studio.NET.
3 . What versions of .NET are there?
The final versions of the 1.0 SDK and runtime were made publicly available around &6pm PST on 15-Jan-2002. At the same time, the final version of Visual Studio.NET was made available to MSDN subscribers.
.NET 1.1 was released in April 2003, and was mostly bug fixes for 1.0.
.NET 2.0 was released to MSDN subscribers in late October 2005, and was officially launched in early November.
4 . What operating systems does the .NET Framework run on?
The runtime supports Windows Server 2003, Windows XP, Windows 2000, NT4 SP6a and Windows ME/98. Windows 95 is not supported. Some parts of the framework do not work on all platforms - for example, ASP.NET is only supported on XP and Windows 2000/2003. Windows 98/ME cannot be used for development
IIS is not supported on Windows XP Home Edition, and so cannot be used to host ASP.NET. However, the ASP.NET Web Matrix web server does run on XP Home

The .NET Compact Framework is a version of the .NET Framework for mobile devices, running Windows CE or Windows Mobile.
The Mono project has a version of the .NET Framework that runs on Linux.
5 . What tools can I use to develop .NET applications?
There are a number of tools, described here in ascending order of cost:
* The .NET Framework SDK is free and includes command-line compilers for C++, C#, and VB.NET and various other utilities to aid development.
* SharpDevelop is a free IDE for C# and VB.NET.
* Microsoft Visual Studio Express editions are cut-down versions of Visual Studio, for hobbyist or novice developers.There are different versions for C#, VB, web development etc. Originally the plan was to charge $49, but MS has decided to offer them as free downloads instead, at least until November 2006.
* Microsoft Visual Studio Standard 2005 is around $300, or $200 for the upgrade.
* Microsoft VIsual Studio Professional 2005 is around $800, or $550 for the upgrade
* At the top end of the price range are the Microsoft Visual Studio Team Edition for Software Developers 2005 with MSDN Premium and Team Suite editions.
You can see the differences between the various Visual Studio versions here.
6 . Why did they call it .NET?
I don't know what they were thinking. They certainly weren't thinking of people using search tools. It's meaningless marketing nonsense.
7 . What is the CLI? Is it the same as the CLR?
The CLI (Common Language Infrastructure) is the definiton of the fundamentals of the .NET framework - the Common Type System (CTS), metadata, the Virtual Execution Environment (VES) and its use of intermediate language (IL), and the support of multiple programming languages via the Common Language Specification (CLS). The CLI is documented through ECMA - see http://msdn.microsoft.com/net/ecma/ for more details.
The CLR (Common Language Runtime) is Microsoft's primary implementation of the CLI. Microsoft also have a shared source implementation known as ROTOR, for educational purposes, as well as the .NET Compact Framework for mobile devices. Non-Microsoft CLI implementations include Mono and DotGNU Portable.NET.
8 . What is IL?
IL = Intermediate Language. Also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language). All .NET source code (of any language) is compiled to IL during development. The IL is then converted to machine code at the point where the software is installed, or (more commonly) at run-time by a Just-In-Time (JIT) compiler.
9 . What is C#?
C# is a new language designed by Microsoft to work with the .NET framework. In their "Introduction to C#" whitepaper, 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++."

Substitute 'Java' for 'C#' in the quote above, and you'll see that the statement still works pretty well :-).
10 . What does 'managed' mean in the .NET context?
The term 'managed' is the cause of much confusion. It is used in various places within .NET, meaning slightly different things.
Managed code: The .NET framework provides several core run-time services to the programs that run within it - for example exception handling and security. For these services to work, the code must provide a minimum level of information to the runtime. Such code is called managed code.
Managed data: This is data that is allocated and freed by the .NET runtime's garbage collector.

Managed classes: This is usually referred to in the context of Managed Extensions (ME) for C++. When using ME C++, a class can be marked with the __gc keyword. As the name suggests, this means that the memory for instances of the class is managed by the garbage collector, but it also means more than that. The class becomes a fully paid-up member of the .NET community with the benefits and restrictions that brings. An example of a benefit is proper interop with classes written in other languages - for example, a managed C++ class can inherit from a VB class. An example of a restriction is that a managed class can only inherit from one base class.
11 . What is an assembly?
An assembly is sometimes described as a logical .EXE or .DLL, and can be an application (with a main entry point) or a library. An assembly consists of one or more files (dlls, exes, html files etc), and represents a group of resources, type definitions, and implementations of those types. An assembly may also contain references to other assemblies. These resources, types and references are described in a block of data called a manifest. The manifest is part of the assembly, thus making the assembly self-describing.

An important aspect of assemblies is that they are part of the identity of a type. The identity of a type is the assembly that houses it combined with the type name. This means, for example, that if assembly A exports a type called T, and assembly B exports a type called T, the .NET runtime sees these as two completely different types. Furthermore, don't get confused between assemblies and namespaces - namespaces are merely a hierarchical way of organising type names. To the runtime, type names are type names, regardless of whether namespaces are used to organise the names. It's the assembly plus the typename (regardless of whether the type name belongs to a namespace) that uniquely indentifies a type to the runtime.
Assemblies are also important in .NET with respect to security - many of the security restrictions are enforced at the assembly boundary.
Finally, assemblies are the unit of versioning in .NET - more on this below.
12 . How can I produce an assembly?
The simplest way to produce an assembly is directly from a .NET compiler. For example, the following C# program:
public class CTest
{
public CTest() { System.Console.WriteLine( "Hello from CTest" ); }
}
can be compiled into a library assembly (dll) like this:
csc /t:library ctest.cs
You can then view the contents of the assembly by running the "IL Disassembler" tool that comes with the .NET SDK.
Alternatively you can compile your source into modules, and then combine the modules into an assembly using the assembly linker (al.exe). For the C# compiler, the /target:module switch is used to generate a module instead of an assembly.
13 . What is the difference between a private assembly and a shared assembly?
The terms 'private' and 'shared' refer to how an assembly is deployed, not any intrinsic attributes of the 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 intended to be used by multiple applications, and is normally stored in the global assembly cache (GAC), which is a central repository for assemblies. (A shared assembly can also be stored outside the GAC, in which case each application must be pointed to its location via a codebase entry in the application's configuration file.) The main advantage of deploying assemblies to the GAC is that the GAC can support multiple versions of the same assembly side-by-side.
Assemblies deployed to the GAC must be strong-named. Outside the GAC, strong-naming is optional.
14 . How do assemblies find each other?
By searching directory paths. There are several factors that can affect the path (such as the AppDomain host, and application configuration files), but for weakly named assemblies the search path is normally the application's directory and its sub-directories. For strongly named assemblies, the search path is the GAC followed by the private assembly path.
15 . How does assembly versioning work?
An assembly has a version number consisting of four parts, e.g. 1.0.350.1. These are typically interpreted as Major.Minor.Build.Revision, but this is just a convention.&
The CLR applies no version constraints on weakly named assemblies, so the assembly version has no real significance.
For strongly named assemblies, the version of a referenced assembly is stored in the referring assembly, and by default only this exact version will be loaded at run-time. If the exact version is not available, the referring assembly will fail to load. It is possible to override this behaviour in the config file for the referring assembly - references to a single version or a range of versions of the referenced assembly can be redirected to a specific version. For example, versions 1.0.0.0 to 2.0.0.0 can be redirected to version 3.0.125.3. However note that there is no way to specify a range of versions to be redirected to. Publisher policy files offer an alternative mechanism for redirecting to a different version for assemblies deployed to the GAC - a publisher policy file allows the publisher of the assembly to redirect all applications to a new version of an assembly in one operation, rather than having to modify all of the application configuration files.

The restrictions on version policy for strongly named assemblies can cause problems when providing patches or 'hot fixes' for individual assemblies within an application. To avoid having to deploy config file changes or publisher policy files along with the hot fix, it makes sense to reuse the same assembly version for the hot fix. If desired, the assemblies can be distinguised by altering the assembly file version, which is not used at all by the CLR for applying version policy. For more discussion, see Suzanne Cook's When to Change File/Assembly Versions blog entry.
Note that the versioning of strongly named assemblies applies whether the assemblies are deployed privately or to the GAC.
16 . How can I develop an application that automatically updates itself from the web?
For .NET 1.x, use the Updater Application Block. For .NET 2.x, use ClickOnce.
17 . What is an application domain?
An AppDomain can be thought of as a lightweight process. Multiple AppDomains can exist inside a Win32 process. The primary purpose of the AppDomain is to isolate applications from each other, and so it is particularly useful in hosting scenarios such as ASP.NET. An AppDomain can be destroyed by the host without affecting other AppDomains in the process.
Win32 processes provide isolation by having distinct memory address spaces. This is effective, but expensive. The .NET runtime enforces AppDomain isolation by keeping control over the use of memory - all memory in the AppDomain is managed by the .NET runtime, so the runtime can ensure that AppDomains do not access each other's memory.
One non-obvious use of AppDomains is for unloading types. Currently the only way to unload a .NET type is to destroy the AppDomain it is loaded into. This is particularly useful if you create and destroy types on-the-fly via reflection.
18 . Can I write my own .NET host?
Yes. For an example of how to do this, take a look at the source for the dm.net moniker developed by Jason Whittington and Don Box. There is also a code sample in the .NET SDK called CorHost.
19 . What is garbage collection?
Garbage collection is a heap-management strategy where a run-time component takes responsibility for managing the lifetime of the memory used by objects. This concept is not new to .NET - Java and many other languages/runtimes have used garbage collection for some time.
20 . Is it true that objects don't always get destroyed immediately when the last reference goes away?
Yes. The garbage collector offers no guarantees about the time when an object will be destroyed and its memory reclaimed.&
There was an interesting thread on the DOTNET list, started by Chris Sells, about the implications of non-deterministic destruction of objects in C#. In October 2000, Microsoft's Brian Harry posted a lengthy analysis of the problem. Chris Sells' response to Brian's posting is here
21 . Why doesn't the .NET runtime offer deterministic destruction?
Because of the garbage collection algorithm. The .NET garbage collector works by periodically running through a list of all the objects that are currently being referenced by an application. All the objects that it doesn't find during this search are ready to be destroyed and the memory reclaimed. The implication of this algorithm is that the runtime doesn't get notified immediately when the final reference on an object goes away - it only finds out during the next 'sweep' of the heap
Futhermore, this type of algorithm works best by performing the garbage collection sweep as rarely as possible. Normally heap exhaustion is the trigger for a collection sweep.
22 . Is the lack of deterministic destruction in .NET a problem?
It's certainly an issue that affects component design. If you have objects that maintain expensive or scarce resources (e.g. database locks), you need to provide some way to tell the object to release the resource when it is done. Microsoft recommend that you provide a method called Dispose() for this purpose. However, this causes problems for distributed objects - in a distributed system who calls the Dispose() method? Some form of reference-counting or ownership-management mechanism is needed to handle distributed objects - unfortunately the runtime offers no help with this
23 . Should I implement Finalize on my class? Should I implement IDisposable?
This issue is a little more complex than it first appears. There are really two categories of class that require deterministic destruction - the first category manipulate unmanaged types directly, whereas the second category manipulate managed types that require deterministic destruction. An example of the first category is a class with an IntPtr member representing an OS file handle. An example of the second category is a class with a System.IO.FileStream member
For the first category, it makes sense to implement IDisposable and override Finalize. This allows the object user to 'do the right thing' by calling Dispose, but also provides a fallback of freeing the unmanaged resource in the Finalizer, should the calling code fail in its duty. However this logic does not apply to the second category of class, with only managed resources. In this case implementing Finalize is pointless, as managed member objects cannot be accessed in the Finalizer. This is because there is no guarantee about the ordering of Finalizer execution. So only the Dispose method should be implemented. (If you think about it, it doesn't really make sense to call Dispose on member objects from a Finalizer anyway, as the member object's Finalizer will do the required cleanup.)
For classes that need to implement IDisposable and override Finalize, see Microsoft's documented pattern.
Note that some developers argue that implementing a Finalizer is always a bad idea, as it hides a bug in your code (i.e. the lack of a Dispose call). A less radical approach is to implement Finalize but include a Debug.Assert at the start, thus signalling the problem in developer builds but allowing the cleanup to occur in release builds.
24 . Do I have any control over the garbage collection algorithm?
A little. For example the System.GC class exposes a Collect method, which forces the garbage collector to collect all unreferenced objects immediately
Also there is a gcConcurrent setting that can be specified via the application configuration file. This specifies whether or not the garbage collector performs some of its collection activities on a separate thread. The setting only applies on multi-processor machines, and defaults to true.
25 . How can I find out what the garbage collector is doing?
Lots of interesting statistics are exported from the .NET runtime via the '.NET CLR xxx' performance counters. Use Performance Monitor to view them
26 . What is the lapsed listener problem?
The lapsed listener problem is one of the primary causes of leaks in .NET applications. It occurs when a subscriber (or 'listener') signs up for a publisher's event, but fails to unsubscribe. The failure to unsubscribe means that the publisher maintains a reference to the subscriber as long as the publisher is alive. For some publishers, this may be the duration of the application
This situation causes two problems. The obvious problem is the leakage of the subscriber object. The other problem is the performance degredation due to the publisher sending redundant notifications to 'zombie' subscribers.
There are at least a couple of solutions to the problem. The simplest is to make sure the subscriber is unsubscribed from the publisher, typically by adding an Unsubscribe() method to the subscriber. Another solution, documented here by Shawn Van Ness, is to change the publisher to use weak references in its subscriber list.
27 . What is serialization?
Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process, i.e. creating an object from a stream of bytes. Serialization/Deserialization is mostly used to transport objects (e.g. during remoting), or to persist objects (e.g. to a file or database).
28 . Does the .NET Framework have in-built support for serialization?
There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code
29 . I want to serialize instances of my class. Should I use XmlSerializer, SoapFormatter or BinaryFormatter?
It depends. XmlSerializer has severe limitations such as the requirement that the target class has a parameterless constructor, and only public read/write properties and fields can be serialized. However, on the plus side, XmlSerializer has good support for customising the XML document that is produced or consumed. XmlSerializer's features mean that it is most suitable for cross-platform work, or for constructing objects from existing XML documents
SoapFormatter and BinaryFormatter have fewer limitations than XmlSerializer. They can serialize private fields, for example. However they both require that the target class be marked with the [Serializable] attribute, so like XmlSerializer the class needs to be written with serialization in mind. Also there are some quirks to watch out for - for example on deserialization the constructor of the new object is not invoked.
The choice between SoapFormatter and BinaryFormatter depends on the application. BinaryFormatter makes sense where both serialization and deserialization will be performed on the .NET platform and where performance is important. SoapFormatter generally makes more sense in all other cases, for ease of debugging if nothing else.
30 . Can I customise the serialization process?
Yes. XmlSerializer supports a range of attributes that can be used to configure serialization for a particular class. For example, a field or property can be marked with the [XmlIgnore] attribute to exclude it from serialization. Another example is the [XmlElement] attribute, which can be used to specify the XML element name to be used for a particular property or field.
Serialization via SoapFormatter/BinaryFormatter can also be controlled to some extent by attributes. For example, the [NonSerialized] attribute is the equivalent of XmlSerializer's [XmlIgnore] attribute. Ultimate control of the serialization process can be acheived by implementing the the ISerializable interface on the class whose instances are to be serialized.
31 . Why is XmlSerializer so slow?
There is a once-per-process-per-type overhead with XmlSerializer. So the first time you serialize or deserialize an object of a given type in an application, there is a significant delay. This normally doesn't matter, but it may mean, for example, that XmlSerializer is a poor choice for loading configuration settings during startup of a GUI application
32 . Why do I get errors when I try to serialize a Hashtable?
XmlSerializer will refuse to serialize instances of any class that implements IDictionary, e.g. Hashtable. SoapFormatter and BinaryFormatter do not have this restriction.
33 . XmlSerializer is throwing a generic "There was an error reflecting MyClass" error. How do I find out what the problem is?
Look at the InnerException property of the exception that is thrown to get a more specific error message
34 . What are attributes?
There are at least two types of .NET attribute. The first type I will refer to as a metadata attribute - it allows some data to be attached to a class or method. This data becomes part of the metadata for the class, and (like other class metadata) can be accessed via reflection. An example of a metadata attribute is [serializable], which can be attached to a class and means that instances of the class can be serialized.
[serializable] public class CTest {}
The other type of attribute is a context attribute. Context attributes use a similar syntax to metadata attributes but they are fundamentally different. Context attributes provide an interception mechanism whereby instance activation and method calls can be pre- and/or post-processed. If you have encountered Keith Brown's universal delegator you'll be familiar with this idea.
35 . What is Code Access Security (CAS)?
CAS is the part of the .NET security model that determines whether or not code is allowed to run, and what resources it can use when it is running. For example, it is CAS that will prevent a .NET web applet from formatting your hard disk.
36 . How does CAS work?
The CAS security policy revolves around two key concepts - code groups and permissions. Each .NET assembly is a member of a particular code group, and each code group is granted the permissions specified in a named permission set.
For example, using the default security policy, a control downloaded from a web site belongs to the 'Zone - Internet' code group, which adheres to the permissions defined by the 'Internet' named permission set. (Naturally the 'Internet' named permission set represents a very restrictive range of permissions.)
37 . I'm having some trouble with CAS. How can I troubleshoot the problem?
Caspol has a couple of options that might help. First, you can ask caspol to tell you what code group an assembly belongs to, using caspol -rsg. Similarly, you can ask what permissions are being applied to a particular assembly using caspol -rsp
38 . I can't be bothered with CAS. Can I turn it off?
Yes, as long as you are an administrator. Just run:
caspol -s off
39 . Can I look at the IL for an assembly?
Yes. MS supply a tool called Ildasm that can be used to view the metadata and IL for an assembly.
40 . Can source code be reverse-engineered from IL?
Yes, it is often relatively straightforward to regenerate high-level source from IL. Lutz Roeder's Reflector does a very good job of turning IL into C# or VB.NET.
41 . How can I stop my code being reverse-engineered from IL?
You can buy an IL obfuscation tool. These tools work by 'optimising' the IL in such a way that reverse-engineering becomes much more difficult
Of course if you are writing web services then reverse-engineering is not a problem as clients do not have access to your IL.
42 . Can I write IL programs directly?
Yes. Peter Drayton posted this simple example to the DOTNET mailing list:
.assembly MyAssembly {}
.class MyApp {
.method static void Main() {
.entrypoint
ldstr "Hello, IL!"
call void System.Console::WriteLine(class System.Object)
ret
}
}
Just put this into a file called hello.il, and then run ilasm hello.il. An exe assembly will be generated.
43 . Can I do things in IL that I can't do in C#?
Yes. A couple of simple examples are that you can throw exceptions that are not derived from System.Exception, and you can have non-zero-based arrays.
44 . Does .NET replace COM?
This subject causes a lot of controversy, as you'll see if you read the mailing list archives. Take a look at the following two threads:
http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&D=0&P=68241
http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P=R60761
The bottom line is that .NET has its own mechanisms for type interaction, and they don't use COM. No IUnknown, no IDL, no typelibs, no registry-based activation. This is mostly good, as a lot of COM was ugly. Generally speaking, .NET allows you to package and use components in a similar way to COM, but makes the whole thing a bit easier.
45 . Is DCOM dead?
Pretty much, for .NET developers. The .NET Framework has a new remoting model which is not based on DCOM. DCOM was pretty much dead anyway, once firewalls became widespread and Microsoft got SOAP fever. Of course DCOM will still be used in interop scenarios.
46 . Is COM+ dead?
Not immediately. The approach for .NET 1.0 was to provide access to the existing COM+ services (through an interop layer) rather than replace the services with native .NET ones. Various tools and attributes were provided to make this as painless as possible. Over time it is expected that interop will become more seamless - this may mean that some services become a core part of the CLR, and/or it may mean that some services will be rewritten as managed code which runs on top of the CLR.
For more on this topic, search for postings by Joe Long in the archives - Joe is the MS group manager for COM+. Start with this message:
http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P=R68370
47 . Can I use COM components from .NET programs?
Yes. COM components are accessed from the .NET runtime via a Runtime Callable Wrapper (RCW). This wrapper turns the COM interfaces exposed by the COM component into .NET-compatible interfaces. For oleautomation interfaces, the RCW can be generated automatically from a type library. For non-oleautomation interfaces, it may be necessary to develop a custom RCW which manually maps the types exposed by the COM interface to .NET-compatible types.
48 . Can I use .NET components from COM programs?
Yes. .NET components are accessed from COM via a COM Callable Wrapper (CCW). This is similar to a RCW (see previous question), but works in the opposite direction. Again, if the wrapper cannot be automatically generated by the .NET development tools, or if the automatic behaviour is not desirable, a custom CCW can be developed. Also, for COM to 'see' the .NET component, the .NET component must be registered in the registry.
49 . Is ATL redundant in the .NET world?
Yes. ATL will continue to be valuable for writing COM components for some time, but it has no place in the .NET world.
50 . How do I spawn a thread?
Create an instance of a System.Threading.Thread object, passing it an instance of a ThreadStart delegate that will be executed on the new thread. For example:
class MyThread
{
public MyThread( string initData )
{
m_data = initData;
m_thread = new Thread( new ThreadStart(ThreadMain) );
m_thread.Start();
}
// ThreadMain() is executed on the new thread.
private void ThreadMain()
{
Console.WriteLine( m_data );
}
public void WaitUntilFinished()
{
m_thread.Join();
}
private Thread m_thread;
private string m_data;
}
In this case creating an instance of the MyThread class is sufficient to spawn the thread and execute the MyThread.ThreadMain() method:
MyThread t = new MyThread( "Hello, world." );
t.WaitUntilFinished();
51 . How do I stop a thread?
There are several options. First, you can use your own communication mechanism to tell the ThreadStart method to finish. Alternatively the Thread class has in-built support for instructing the thread to stop. The two principle methods are Thread.Interrupt() and Thread.Abort(). The former will cause a ThreadInterruptedException to be thrown on the thread when it next goes into a WaitJoinSleep state. In other words, Thread.Interrupt is a polite way of asking the thread to stop when it is no longer doing any useful work. In contrast, Thread.Abort() throws a ThreadAbortException regardless of what the thread is doing. Furthermore, the ThreadAbortException cannot normally be caught (though the ThreadStart's finally method will be executed). Thread.Abort() is a heavy-handed mechanism which should not normally be required.
52 . How do I use the thread pool?
By passing an instance of a WaitCallback delegate to the ThreadPool.QueueUserWorkItem() method
class CApp
{
static void Main()
{
string s = "Hello, World";
ThreadPool.QueueUserWorkItem( new WaitCallback( DoWork ), s );

Thread.Sleep( 1000 ); // Give time for work item to be executed
}

// DoWork is executed on a thread from the thread pool.
static void DoWork( object state )
{
Console.WriteLine( state );
}
}
53 . How do I know when my thread pool work item has completed?
There is no way to query the thread pool for this information. You must put code into the WaitCallback method to signal that it has completed. Events are useful for this.
54 . Should I use ReaderWriterLock instead of Monitor.Enter/Exit?
Maybe, but be careful. ReaderWriterLock is used to allow multiple threads to read from a data source, while still granting exclusive access to a single writer thread. This makes sense for data access that is mostly read-only, but there are some caveats. First, ReaderWriterLock is relatively poor performing compared to Monitor.Enter/Exit, which offsets some of the benefits. Second, you need to be very sure that the data structures you are accessing fully support multithreaded read access. Finally, there is apparently a bug in the v1.1 ReaderWriterLock that can cause starvation for writers when there are a large number of readers.
Ian Griffiths has some interesting discussion on ReaderWriterLock here and here.
55 . Tracing . Is there built-in support for tracing/logging?
Yes, in the System.Diagnostics namespace. There are two main classes that deal with tracing - Debug and Trace. They both work in a similar way - the difference is that tracing from the Debug class only works in builds that have the DEBUG symbol defined, whereas tracing from the Trace class only works in builds that have the TRACE symbol defined. Typically this means that you should use System.Diagnostics.Trace.WriteLine for tracing that you want to work in debug and release builds, and System.Diagnostics.Debug.WriteLine for tracing that you want to work only in debug builds.
56 . Can I redirect tracing to a file?
Yes. The Debug and Trace classes both have a Listeners property, which is a collection of sinks that receive the tracing that you send via Debug.WriteLine and Trace.WriteLine respectively. By default the Listeners collection contains a single sink, which is an instance of the DefaultTraceListener class. This sends output to the Win32 OutputDebugString() function and also the System.Diagnostics.Debugger.Log() method. This is useful when debugging, but if you're trying to trace a problem at a customer site, redirecting the output to a file is more appropriate. Fortunately, the TextWriterTraceListener class is provided for this purpose.
Here's how to use the TextWriterTraceListener class to redirect Trace output to a file:
Trace.Listeners.Clear();
FileStream fs = new FileStream( @"c:\log.txt", FileMode.Create, FileAccess.Write );
Trace.Listeners.Add( new TextWriterTraceListener( fs ) );

Trace.WriteLine( @"This will be writen to c:\log.txt!" );
Trace.Flush();
Note the use of Trace.Listeners.Clear() to remove the default listener. If you don't do this, the output will go to the file and OutputDebugString(). Typically this is not what you want, because OutputDebugString() imposes a big performance hit.
57 . Can I customise the trace output?
Yes. You can write your own TraceListener-derived class, and direct all output through it. Here's a simple example, which derives from TextWriterTraceListener (and therefore has in-built support for writing to files, as shown above) and adds timing information and the thread ID for each trace line:
class MyListener : TextWriterTraceListener
{
public MyListener( Stream s ) : base(s)
{
}
public override void WriteLine( string s )
{
Writer.WriteLine( "{0:D8} [{1:D4}] {2}",
Environment.TickCount - m_startTickCount,
AppDomain.GetCurrentThreadId(),
s );
}
protected int m_startTickCount = Environment.TickCount;
}
(Note that this implementation is not complete - the TraceListener.Write method is not overridden for example.)
The beauty of this approach is that when an instance of MyListener is added to the Trace.Listeners collection, all calls to Trace.WriteLine() go through MyListener, including calls made by referenced assemblies that know nothing about the MyListener class.
58 . Are there any third party logging components available?
Log4net is a port of the established log4j Java logging component.
59 . Miscellaneous . How does .NET remoting work?
.NET remoting involves sending messages along channels. Two of the standard channels are HTTP and TCP. TCP is intended for LANs only - HTTP can be used for LANs or WANs (internet).
Support is provided for multiple message serializarion formats. Examples are SOAP (XML-based) and binary. By default, the HTTP channel uses SOAP (via the .NET runtime Serialization SOAP Formatter), and the TCP channel uses binary (via the .NET runtime Serialization Binary Formatter). But either channel can use either serialization format.
There are a number of styles of remote access:
• SingleCall. Each incoming request from a client is serviced by a new object. The object is thrown away when the request has finished.
• Singleton. All incoming requests from clients are processed by a single server object.
• Client-activated object. This is the old stateful (D)COM model whereby the client receives a reference to the remote object and holds that reference (thus keeping the remote object alive) until it is finished with it.
Distributed garbage collection of objects is managed by a system called 'leased based lifetime'. Each object has a lease time, and when that time expires the object is disconnected from the .NET runtime remoting infrastructure. Objects have a default renew time - the lease is renewed when a successful call is made from the client to the object. The client can also explicitly renew the lease.
If you're interested in using XML-RPC as an alternative to SOAP, take a look at Charles Cook's XML-RPC.Net.
60 . How can I get at the Win32 API from a .NET program?
Use P/Invoke. This uses similar technology to COM Interop, but is used to access static DLL entry points instead of COM objects. Here is an example of C# calling the Win32 MessageBox function:
using System;
using System.Runtime.InteropServices;

class MainApp
{
[DllImport("user32.dll", EntryPoint="MessageBox", SetLastError=true, CharSet=CharSet.Auto)]
public static extern int MessageBox(int hWnd, String strMessage, String strCaption, uint uiType);
public static void Main()
{
MessageBox( 0, "Hello, this is PInvoke in operation!", ".NET", 0 );
}
}
Pinvoke.net is a great resource for off-the-shelf P/Invoke signatures.
61 . How do I write to the application configuration file at runtime?
You don't. See http://www.interact-sw.co.uk/iangblog/2004/11/25/savingconfig.
62 . What is the difference between an event and a delegate?
An event is just a wrapper for a multicast delegate. Adding a public event to a class is almost the same as adding a public multicast delegate field. In both cases, subscriber objects can register for notifications, and in both cases the publisher object can send notifications to the subscribers. However, a public multicast delegate has the undesirable property that external objects can invoke the delegate, something we'd normally want to restrict to the publisher. Hence events - an event adds public methods to the containing class to add and remove receivers, but does not make the invocation mechanism public.
See this post by Julien Couvreur for more discussion.
63 . What size is a .NET object?
Each instance of a reference type has two fields maintained by the runtime - a method table pointer and a sync block. These are 4 bytes each on a 32-bit system, making a total of 8 bytes per object overhead. Obviously the instance data for the type must be added to this to get the overall size of the object. So, for example, instances of the following class are 12 bytes each:
class MyInt
{
...
private int x;
}
However, note that with the current implementation of the CLR there seems to be a minimum object size of 12 bytes, even for classes with no data (e.g. System.Object).
Values types have no equivalent overhead.
64 . Will my .NET app run on 64-bit Windows?
64-bit (x64) versions of Windows support both 32-bit and 64-bit processes, and corresponding 32-bit and 64-bit versions of .NET 2.0. (.NET 1.1 is 32-bit only).
.NET 1.x apps automatically run as 32-bit processes on 64-bit Windows.
.NET 2.0 apps can either run as 32-bit processes or as 64-bit processes. The OS decides which to use based on the PE header of the executable. The flags in the PE header are controlled via the compiler /platform switch, which allows the target of the app to be specified as 'x86', 'x64' or 'any cpu'. Normally you specify 'any cpu', and your app will run as 32-bit on 32-bit Windows and 64-bit on 64-bit Windows. However if you have some 32-bit native code in your app (loaded via COM interop, for example), you will need to specify 'x86', which will force 64-bit Windows to load your app in a 32-bit process. You can also tweak the 32-bit flag in the PE header using the SDK corflags utility.
Some more explanation here:
http://blogs.msdn.com/gauravseth/archive/2006/03/07/545104.aspx
http://blogs.msdn.com/joshwil/archive/2005/04/08/406567.aspx
http://msdn.microsoft.com/netframework/programming/64bit/gettingstarted/
65 . What is reflection?
All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection. The System.Reflection namespace contains classes that can be used to interrogate the types for a module/assembly.
Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo to access type library data in COM, and it is used for similar purposes - e.g. determining data type sizes for marshaling data across context/process/machine boundaries.
Reflection can also be used to dynamically invoke methods (see System.Type.InvokeMember), or even create types dynamically at run-time (see System.Reflection.Emit.TypeBuilder).
66 . .NET 2.0 What are the new features of .NET 2.0?
Generics, anonymous methods, partial classes, iterators, property visibility (separate visibility for get and set) and static classes. See http://msdn.microsoft.com/msdnmag/issues/04/05/C20/default.aspx for more information about these features.
67 . What are the new 2.0 features useful for?
Generics are useful for writing efficient type-independent code, particularly where the types might include value types. The obvious application is container classes, and the .NET 2.0 class library includes a suite of generic container classes in the System.Collections.Generic namespace. Here's a simple example of a generic container class being used:
List myList = new List();
myList.Add( 10 );
Anonymous methods reduce the amount of code you have to write when using delegates, and are therefore especially useful for GUI programming. Here's an example
AppDomain.CurrentDomain.ProcessExit += delegate { Console.WriteLine("Process ending ..."); };
Partial classes is a useful feature for separating machine-generated code from hand-written code in the same class, and will therefore be heavily used by development tools such as Visual Studio.
Iterators reduce the amount of code you need to write to implement IEnumerable/IEnumerator. Here's some sample code:
static void Main()
{
RandomEnumerator re = new RandomEnumerator( 5 );
foreach( double r in re )
Console.WriteLine( r );
Console.Read();
}
class RandomEnumerator : IEnumerable
{
public RandomEnumerator(int size) { m_size = size; }

public IEnumerator GetEnumerator()
{
Random rand = new Random();
for( int i=0; i < m_size =" 0;">
{
public static void Dispose(T obj) { obj.Dispose(); }
}
The C# compiler will refuse to compile this code, as the type T has not been constrained, and therefore only supports the methods of System.Object. Dispose is not a method on System.Object, so the compilation fails. To fix this code, we need to add a where clause, to reassure the compiler that our type T does indeed have a Dispose method
static class Disposer where T : IDisposable
{
public static void Dispose(T obj) { obj.Dispose(); }
}
The problem is that the requirement for explicit contraints is very limiting. We can use constraints to say that T implements a particular interface, but we can't dilute that to simply say that T implements a particular method. Contrast this with C++ templates (for example), where no constraint at all is required - it is assumed (and verified at compile time) that if the code invokes the Dispose() method on a type, then the type will support the method.
In fact, after writing generic code with interface constraints, we quickly see that we haven't gained much over non-generic interface-based programming. For example, we can easily rewrite the Disposer class without generics:
static class Disposer
{
public static void Dispose( IDisposable obj ) { obj.Dispose(); }
}
For more on this topic, start by reading the following articles:
Bruce Eckel: http://www.mindview.net/WebLog/log-0050
Ian Griffiths: http://www.interact-sw.co.uk/iangblog/2004/03/14/generics
Charles Cook: http://www.cookcomputing.com/blog/archives/000425.html
69 . What's new in the .NET 2.0 class library?
Here is a selection of new features in the .NET 2.0 class library:
• Generic collections in the System.Collections.Generic namespace.
• The System.Nullable type. (Note that C# has special syntax for this type, e.g. int? is equivalent to Nullable)
• The GZipStream and DeflateStream classes in the System.IO.Compression namespace.
• The Semaphore class in the System.Threading namespace.
• Wrappers for DPAPI in the form of the ProtectedData and ProtectedMemory classes in the System.Security.Cryptography namespace.
• The IPC remoting channel in the System.Runtime.Remoting.Channels.Ipc namespace, for optimised intra-machine communication.
and many, many more. See http://msdn2.microsoft.com/en-us/library/t357fb32(en-US,VS.80).aspx for a comprehensive list of changes.