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)