Faqs on asp.net,c#,vb.net and sqlserver2005

this blog covers all the Faqs related to .net technologies like asp.net,vb.net,c#.net,ajax,javascript and sqlserver2005.

Jan 30, 2008

UPnP Application Development Using C#

Did you hear about the refrigerator of the future that not only chills your food but also includes a connection to the Internet? Or the microwave that lets you read your e-mail as it heats your Pop-Tart? What? No appeal?

Well, how about a network-enabled alarm clock that knows your appointments, checks traffic and weather, calculates when you need to wake, and in the morning tells you the time of your flight, the weather at your destination, and when you need to leave. On your way to the airport, your UPnP-enabled personal digital assistant (PDA) finds the best place to park and orders a latte to be ready for you in the concourse. As you travel, your PDA tracks your appointments, makes restaurant and hotel reservations, confirms flights, and orders groceries to be delivered the day you arrive home. As far as I can tell, these oddities and cool devices don't exist yet, but they've become possible due to the existence of Universal Plug and Play (UPnP).

What is UPnP?

UPnP technology extends Plug and Play to simplify the networking of intelligent devices in homes and businesses. When devices incorporating UPnP technology are physically connected to the network, they'll connect automatically to one another over the network, without the need for user configuration or centralized servers.
The UPnP specification is based on TCP/IP and Internet protocols that let devices communicate with each other. That's why it's called universal—UPnP technology doesn't rely on specific device drivers, using instead these standard protocols. UPnP devices can automatically configure network addressing, announce their presence on a network subnet, and permit the exchange of device and service descriptions. A Windows XP-based computer can act as a UPnP control point, discovering and controlling devices through a program interface.
This might not sound all that revolutionary when compared to regular old Plug and Play that's been around for some time. Adding Plug and Play technology to the operating system has made it easier to setup, configure, and add peripherals to a single computer. But the big deal about UPnP is what it can do for the home or small business user who isn't a networking professional, but who wants to be able to reliably play multi-player games, use real-time communications (Internet telephony, teleconferencing), and other technologies such as Remote Assistance in Windows XP. Until now, only big corporations with fully-staffed IT departments could do these things easily (though I doubt that multi-player gaming, much less a Web-surfing refrigerator, is a big part of their emphasis).

Network Address Translation


The addressing system on the Internet was designed long before the active presence of millions of home networks, with more being added daily. In fact, it's nothing short of miraculous that an addressing system thought up when the Internet was in its infancy still works.

Because the stock of Internet addresses is rapidly depleting, most home networks employ a gateway using Network Address Translation (NAT). NAT is an Internet Engineering Task Force standard that allows multiple PCs or devices on a private network to share a single, globally unique, public address (using private address ranges such as 10.0.x.x, 192.168.x.x, 172.x.x.x). As a temporary fix for the shortage of addresses, NAT works nicely for most things—Internet Connection Sharing in Windows XP uses NAT, as do many gateway devices such as DSL and cable modems.

The problem is that NAT expects each network application to communicate in a standard fashion using IP addresses in packet headers, but some network applications do not anticipate the existence of NAT. They use embedded IP addresses that the NAT cannot translate.

NAT Traversal Technology

NAT traversal technology allows network applications to detect that they are behind a UPnP-enabled NAT device. Then the applications can learn the shared, globally-routable IP address, and configure port mappings to forward packets from the external port of the NAT to the internal port used by the application—and all automatically so the user doesn't have to manually configure port mappings or other such rigmarole. NAT traversal allows network devices or peer-to-peer applications to traverse a NAT gateway by dynamically opening and closings ports for communication with outside services.

Enabling the UPnP User Interface

In some cases, Windows XP will discover UPnP devices and provide its own user interface to control them. An example is the user interface (UI) for UPnP residential gateway devices in the Network Connections folder. The popular Linksys BEFSR41W wireless router shows up automatically in the Network Connections folder after it's installed because an application is included in Windows XP.

In addition, you can install the optional UI component using the steps below. This UI component displays a balloon tip for newly discovered devices and places an icon for each device in the My Network Places folder. To enable the UPnP UI, follow these steps:

1.

Click Start, click Control Panel, and then click Add or Remove Programs.

2.

In the Add or Remove Programs dialog box, click Add/Remove Windows Components.

3.

In the Windows Components Wizard, click Networking Services, click Details, and then select the Universal Plug and Play check box.

4.

Click OK, and then click Next in the Windows Components Wizard. You may need to provide your Windows XP installation CD


You can now see if any UPnP-enabled devices exist on your network by opening My Network Places. If there are UPnP devices on your local network, they will appear here with a generic icon based on the device type. In the future when a UPnP device is installed on the network, a notifying icon will appear briefly in the System Tray. When you see this icon, go to My Network Places to view the new device.

Support for UPnP technology and NAT traversal is an important feature to look for in an Internet gateway device. If you're purchasing or leasing an Internet gateway device, consider only those devices that support UPnP for NAT traversal because this feature can make such a difference to the home network.

For more information about UPnP and NAT traversal, visit the UPnP Forum of which Microsoft was a founding member and now consists of more than 488 vendors.

UPnP Security Concerns

UPnP technology has been adopted by a wide range of device vendors due to its simplicity and adherence to open standards. The initial implementation of UPnP technology in Windows XP, however, had some security vulnerabilities, which an attacker could have used to slow the operation of your PC or, under very rare circumstances, obtain elevated privileges on your system. However, none of these issues would surface if you install a firewall on Windows XP. Windows XP, in fact, ships with the Internet Connection Firewall (ICF), which is installed by default on your Internet connection, thereby protecting you from attackers on the Internet. The security vulnerabilities found have since been fixed. Microsoft Security Bulletin MS01-059 discusses these issues and provides links to more information in Knowledge Base articles and to the patch download.

Jan 29, 2008

Socket Programming using C# - Part I

If you have dealt with sockets in the past, you may be interested in learning how it is done using C# technology. Read more ...The purpose of this article is to show you how you can do socket programming in C#. This article assumes some familiarity with the socket programming, though you need not to be expert in socket programming. There are several flavors to socket programming - like client side , server side , blocking or synchronous , non-blocking or asynchronous etc.

With all these flavors in mind , I have decided to break this subject into two parts. In the part 1 I will start with the client side blocking socket. Later on in the second part I will show you how to create server side and non-blocking.

Network programming in windows is possible with sockets. A socket is like a handle to a file. Socket programming resembles the file IO as does the Serial Communication. You can use sockets programming to have two applications communicate with each other. The application are typically on the different computers but they can be on same computer. For the two applications to talk to each either on the same or different computers using sockets one application is generally a server that keeps listening to the incoming requests and the other application acts as a client and makes the connection to the server application.

The server application can either accept or reject the connection. If the server accepts the connection, a dialog can begin with between the client and the server. Once the client is done with whatever it needs to do it can close the connection with the server. Connections are expensive in the sense that servers allow finite connections to occur. During the time client has an active connection it can send the data to the server and/or receive the data.

The complexity begins here. When either side (client or server) sends data the other side is supposed to read the data. But how will the other side know when data has arrived. There are two options - either the application needs to poll for the data at regular intervals or there needs to be some sort of mechanism that would enable application to get notifications and application can read the data at that time. Well , after all Windows is an event driven system and the notification system seems an obvious and best choice and it in fact is.

As I said the two applications that need to communicate with each other need to make a connection first. In order for the two application to make connections the two applications need to identify each other ( or each other's computer ). Computers on network have a unique identifier called I.P. address which is represented in dot-notation like 10.20.120.127 etc. Lets see how all this works in .NET.

System.Net.Sockets Namespace

Before we go any further, download the source code attached with this article. Extract the zip file to a folder say c:\Temp you will see following two folders :

  • Server
  • Client

In the Server folder there will be one EXE . And in the client there will be the source code in C# that is our client. There will be one file called SocketClient.sln which the solution file . If you double click that your VS.NET will be launched and you will see the project SocketClientProj in the solution. Under this project you will have SocketClientForm.cs file.

Also there is a field where you can specify port number at which the Server is listening. The server app I have provided here listens at port 8221. So I have specified port to be 8221.


After specifying these parameters we need to connect to the server. So pressing Connect will connect to the server and to close the connection press Close. To send some data to the server type some data in the field near the button name Tx and if you press Rx the application will block unless there is some data to read.
With this info lets now try to check the code behind this:

Socket programming in .NET is made possible by Socket class present inside the System.Net.Sockets namespace.
Socket class has several method and properties and a constructor.
The first step is to create an object of this class.
Since there is only one constructor we have no choice but to use it.

Here is how to create the socket:

m_socListener = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.IP);

The first parameter is the address family which we will use interNetwork - other options include Banyan NetBios etc.
AddressFamily is an enum defined in Sockets namespace.
Next we need to specify socket type: and we would use reliable two way connection-based sockets (stream) instead of un-reliable Connectionless sockets ( datagrams) . So we obviously specify stream as the socket type and finally we are using TCP/IP so we would specify protocol type as Tcp.

Once we have created a Socket we need to make a connection to the server since we are using connection-based communication.
To connect to the remote computer we need to know the IP Address and port at which to connect.
In .NET there is a class under System.Net namespace called IPEndPoint which represents a network computer as an IP address and a port number.

The IPEndPoint has two constructors - one that takes a IP Address and Port number and one that takes long and port number. Since we have computer IP address we would use the former

public IPEndPoint(System.Net.IPAddress address, int port);

As you can see the first parameter takes a IPAddress object. If you examine the IPAddress class you will see that it has a static method called Parse that returns IPAddress given a string ( of dot notation ) and second parameter will be the port number. Once we have endpoint ready we can use Connect method of Socket class to connect to the end point ( remote server computer ).
Here is the code:

System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse("10.10.101.200");
System.Net.IPEndPoint remoteEP = new IPEndPoint (iAdd,8221);
m_socClient.Connect (remoteEP);

These three lines of code will make a connection to the remote host running on computer with IP 10.10.101.200 and listening at port 8221. If the Server is running and started ( listening ), the connection will succeed. If however the server is not running an exception called SocketException will be thrown. If you catch the exception and check the Message property of the exception in this case you see following text:

"No connection could be made because the target machine actively refused it."

Similarly if you already have made a connection and the server somehow dies , you will get following exception if you try to send data.

"An existing connection was forcibly closed by the remote host"

Assuming that the connection is made, you can send data to other side using the Send method of the Socket class.
Send method has several overloads. All of them take a byte array . For example if you want to send "Hello There" to host you can use following call:

try
{
String szData = "Hello There";
byte[] byData = System.Text.Encoding.ASCII.GetBytes(szData);
m_socClient.Send(byData);
}
catch (SocketException se)
{
MessageBox.Show ( se.Message );
}

Note that the Send method is blocking. What it means the call will block till the data has been sent or an exception has been thrown. There is an non-blocking version of the send which we will discuss in the next part of this article.
Similar to Send there is a Receive method on the Socket class. You can receive data using following call:

byte [] buffer = new byte[1024];
int iRx = m_socClient.Receive (buffer);

The Receive method again is blocking. It means that if there is no data available the call will block until some data arrives or an exception is thrown.

Non-blocking version of Receive method is more useful than the non-blocking version of Send because if we opt for block Receive , we are effectively doing polling. There is no events about data arrival. This model does not work well for serious applications. But all that is the subject of our next part of this article. For now we will settle with the blocking version.

When you launch the Server, click Start to start listening. The Server listens at port 8221. So make sure you specify the port number 8221 in the port field of our client application. And in the IPAddress field of Client App enter the IP Address of the machine on which the Server is running. If you send some data to server from the client by pressing Tx button, you will see that data in the grayed out edit box.

New features in C# 2.0



There are dozens (hundreds, probably) of pages listing the new features of C# 2.0. However,
I never know where to find a good one quickly, and they don't always tell me what I need to
know at the time. I figured if I added my own set of pages, I could update them whenever
I wanted to, and point other people at them when answering questions. Without further ado then,
here are the new features of C# 2.0:



Partial types



Code generators have existed for a long time. In the past, they usually (depending on the
language) either "owned" a whole type/module (creating a whole file which shouldn't or couldn't
be edited) or reserved sections of files which shouldn't be edited manually. In some cases, where
code was generated by a separate tool from something like a database schema, it could be very hard to
make changes to the schema and regenerate the code without losing any additions made by hand.



C# 2.0 introduces the concept of a partial type declaration. This is quite simply a single type
which spans multiple files, where each file declares the same type using the partial modifier.
The files may refer to members declared within one another without problem (just as forward references within
C# is already not a problem). Here's an example (which in itself is a complete program). This allows all the
auto-generated code which either mustn't be touched on pain of brokenness or shouldn't be touched because you'll
lose all your changes anyway to live in a completely separate file to the code you wish to add. It doesn't help
much if you want to tweak the generated code, of course, but that's a less common issue.



Test1.cs:



partial class Test
{
string name;

static void Main()
{
Test t =
new Test("C# 2.0");
t.SayHello();
}
}

Test2.cs:



using System;

partial class Test
{
Test(
string name)
{
this.name = name;
}

void SayHello()
{
Console.WriteLine (
"Hi there. My name is {0}.", name);
}
}


Compile with:



csc Test1.cs Test2.cs

Results:



Hi there. My name is C# 2.0.

A few little things to be aware of:




  • using directives are only applied to the source file they occur in.


  • Variable initializers (both instance and static) are executed in textual order, but there's no more guarantee made than that.
    Given four fields (a1, a2, b1, b2) appearing in files A.cs and B.cs (in the obvious files, with the
    obvious order), all that is guaranteed is that the initializer for a1 will be executed before the initializer for
    a2 and b1 before b2. A sequence of a1 b1 b2 a2 is acceptable, although I'd
    imagine that either a1 a2 b1 b2 or b1 b2 a1 a2 would be more likely.


  • If a type has a modifier (abstract, public, static etc)
    applied to it in one place, it has effectively been applied everywhere. In particular, the modifiers on each
    part of the type definition must not clash - a class cannot be declared as protected in one place
    and public in another, for example.



Aliases



In previous versions of C#, it was impossible to use two different types which had the same name (including namespace)
within the same assembly. (The types themselves would have to be defined in different assemblies anyway, of course, but
you might want to use them both from the same assembly.)



C# 2.0 introduces the concept of an "alias". This allows you to effectively name an assembly reference when you compile
the code, and use that name to disambiguate between names. As well as disambiguating between identical namespace-qualified
names, aliases allow you to disambiguate between names which have been declared within an already used namespace and
names which belong to the "root" namespace. This is achieved with the predefined alias of global. Here's an
example of aliases at work:


Lib.cs




using System;

namespace Foo.Bar
{
public class Baz
{
public static void SayHiLib()
{
Console.WriteLine (
"Hello Lib");
}
}
}


Baz.cs:



using System;

namespace Foo.Bar
{
public class Baz
{
public static void SayHiNested()
{
Console.WriteLine (
"Hello Nested");
}
}
}


class Baz
{
public static void SayHiBaz()
{
Console.WriteLine (
"Hello Baz");
}
}

Test.cs:




extern alias X;

namespace Foo.Bar
{
class Test
{
static void Main()
{
// Default to using the definition within the same assembly
// and namespace
Baz.SayHiNested();

// Disambiguate to use the definition in the root namespace
global::Baz.SayHiBaz();

// Disambiguate to use the definition in the aliased assembly
X::Foo.Bar.Baz.SayHiLib();
}
}
}

Compile:



csc /target:library Lib.cs
csc /r:X=lib.dll Baz.cs Test.cs

(The results are exactly what you'd expect.)



There are, I suspect, various subtleties to do with aliases. However, I don't know them and I don't want to
know them at the moment - because I think aliases should be avoided wherever possible. In a very few cases they'll
be absolutely invaluable, but you should really try to avoid the situation where they're needed from cropping up
in the first place.



Static classes



Prior to version 2.0, it was impossible to create a class with no instance constructors in C#. If you didn't declare
one, the compiler provided a default constructor for you (a public parameterless constructor which called the
parameterless constructor of the base type). For classes which were never meant to be instantiated (usually utility
classes such as System.Math), this meant you needed to include a private constructor which you didn't
call yourself in order to prevent instantiation.



In C# 2.0, there are static classes. These are simply declared using the static modifier. They
cannot be derived from or instantiated, and they have no constructors (it is a compile-time error to provide any
yourself, and the compiler won't add one for you). Their members must all be static. Here's an example:




using System;

public static class UtilityClass
{
public static void Foo()
{
Console.WriteLine (
"Hello");
}

// Uncommenting this creates a compile-time error,

// as static classes can't have instance members
// int x;
}

// Uncommenting this creates a compile-time error,
// as static classes can't be derived from
// public class DerivationAttempt : UtilityClass{}

class Test
{
static void Main()
{
// Uncommenting this creates a compile-time error,

// as static classes cannot be instantiated.
// new UtilityClass();

// You can use static classes in the normal
// way in terms of static members though:
UtilityClass.Foo();
}
}

Property access modifiers




This is a feature which is long, long overdue. Prior to 2.0, it was impossible to declare
a property with one access level for the "getter" and a different access level for the "setter".
This has meant that people have written separate SetXXX methods if they wanted a
public getter but a more limited setter. Fortunately, this glaring omission has been fixed in
2.0. It's very straightforward - you just add the access modifier to the get or
set as desired:



public class Test
{
string someProperty;

public string SomeProperty
{
get
{
return someProperty;
}

private set
{
someProperty = value;
}
}
}



The basic rules are that you can't specify an access modifier for both the getter and the setter,
and you have to use the "extra" modifier to make access more restrictive than the rest
of the property.


Nullable types and the null coalescing operator

For as long as I can remember, people have been asking why they can't set an int
variable to null, or why they can't return null from a method declared to return DateTime.
Many who understand why they couldn't do so still wished they could, particularly when working
with databases.



.NET 2.0 provides the generic struct System.Nullable<T> with the constraint that T

must be a value type. (If you know absolutely nothing about generics, now might
be a good time to learn about the basics before reading further. You don't need to know a lot of the details
however, and the basic concept is a lot simpler than full-blown generics sometimes gets, which is why I've
put this page before the one on generics.) Nullable<T> itself is still a value type, but
it represents the same set of values as T plus the "null" value. It maintains a separate
member in memory, which is exposed through the HasValue property. When this is true, the
Value property represents the overall value. When it's false, the overall value is null.




C# provides language support for nullable types using a question mark as a suffix. For example,
int? is the same type as Nullable<int> (which is also the same
type as Nullable<System.Int32> in the normal way). C# then allows you to compare
a nullable value with null, or set it to null, and these work in the obvious way. There's an implicit
conversion (no cast required) from a non-nullable type to its equivalent nullable type, and there's
an explicit conversion (cast requried) from a nullable type to its equivalent non-nullable type.
The cast is compiled into a call to the Value property, and an InvalidOperationException

is thrown if the value is null at that point. A nullable type can also be used as the right hand side of
the as operator, with the natural consequences.



The boxed type of a nullable value is the boxed type of the equivalent non-nullable value. If you box a value
which is already null (i.e. HasValue is false), the result is null. This was a late change
to the behaviour, as it required CLR changes which Microsoft were hoping to avoid - you may therefore see
some beta documentation which disagrees with this.



Note that unlike in SQL, two null values of the same type are equal. In other words, the following:




int? x = null;
int? y = null;
Console.WriteLine (x==y);


prints "True".




As well as the System.Nullable<T> struct, there's the non-generic
static class System.Nullable. This merely provides
support for the System.Nullable<T> struct, in terms of finding out the non-nullable
type of a nullable type and performing comparisons.



Nullable logic



bool? has various binary logic operators, but not all of the ones available on bool.
Importantly, the "shortcut" operators (&& and ||) aren't defined for
bool?. A null value represents a sort of "don't know" value - so for instance, null | true

is true, but null | false is null; similarly null & false
is false but null & true is null.



The null coalescing operator



This is a really simple little operator which I suspect will come in quite handy -
if it's widely known about. (It was a long time before I saw anything about it.)
Basically, a ?? b is similar to a==null ? b : a. The type of
a has to be a nullable type or a reference type, and the type of b

has to be a suitable type, the details of which are best left to the spec.
The result is the value of a if that's non-null, otherwise it takes the value of
b. a is only evaluated once (contrary to the version presented
above using the conditional operator), and b is only evaluated
at all if a evaluates to null.




The operator is right-associative, so a ?? b ?? c is equivalent to
a ?? (b ?? c) - in other words, if you provide a string of
a1 ?? a2 ?? ... ?? an then the result is the first non-null one (or null if
all of them are null).



One nice feature is that if the type of a is a nullable type and the type of
b is the equivalent "non-nullable" type, the result of the expression is
that non-nullable type. For example, you can do:




// GetSomeValueMaybe() is a method returning an int? value
int? possible = GetSomeValueMaybe();
int definite = possible ?? 5; // Default to 5

// Alternatively, just:
int value = GetSomeValueMaybe() ?? 5;



This is possible because the compiler knows that if the first expression evaluates to null it
will use the second expression. In this case, we're effectively using GetSomeValueMaybe()
with a kind of "default value" of 5.



The usual details about conversions and the precise rules which are applied can be found
in the spec.


Delegate changes




C# 2.0 has made delegates even easier to work with, using delegate inference,
covariance/contravariance and anonymous methods.
All of these changes are useful today, but many will become even more important in C# 3.0.
This article assumes a reasonable knowledge of delegates. If you are new to the subject, please read
my article on delegates and events first.



Delegate inference




This is actually a smaller topic than anonymous methods, but it'll make the topic of
anonymous methods easier to understand, by keeping the code smaller. Basically,
delegate inference lets you create a delegate instance without the new DelegateType
part wherever the compiler can work out which delegate you mean. Here's an example:



using System;

delegate void SomeAction();

class Test
{
static void Main(string[] args)
{
// Without using delegate inference

SomeAction oldStyle =
new SomeAction (SayHello);

// Now using delegate inference
SomeAction newStyle = SayHello;
}

static void SayHello()
{
Console.WriteLine (
"Hello");
}
}



This can be used with events (e.g. button.Click += ClickHandler;) and
anonymous methods. Occasionally you will need to tell the compiler
what kind of delegate you're trying to build, in which case the old syntax is the way to go.



Covariance and contra-variance



In earlier versions of C#, the signature of the method used to implement a delegate
had to match the delegate signature exactly, including return type. In C# 2.0,
return types can be covariant and parameter types can be contra-variant. Now, these
are big words which basically mean "you're allowed to use any method which is guaranteed
not to muck things up". To be specific:




Return type covariance means that if a delegate is declared to return a base type,
an instance can be created using a method which is declared to return a type derived from it.



Parameter type contra-variance means that if a delegate parameter is declared to be
a derived type, an instance can be created using a method which has a base type for that
parameter.



The reason this works is that any caller of the delegate must provide arguments matching
the delegate's signature (and those arguments will always be compatible with base types of the
parameters), and the implementation just has to guarantee that it will return something which
can be treated as a value of the declared return type of the delegate.




Here's an example of both covariance and contra-variance:



using System;
using System.Text;

public class Test
{
delegate Encoding MyDelegate (string parameter);

static UTF8Encoding SomeMethod (object p)
{
return new UTF8Encoding();
}

static void Main()
{
MyDelegate d = SomeMethod;
}

}



Any string argument which could be passed into the delegate is fine to be treated
as an object reference by SomeMethod, and any UTF8Encoding
returned by SomeMethod can be treated as an Encoding reference by the
caller.




Anonymous methods



Delegates are a wonderful idea. They make eventing models simpler, and get away
from a lot of single method interfaces (or worse, multiple method interfaces with adapters
which do nothing until they're overridden) which afflict Java. Java came up with a way to
make it slightly less painful to override a single method than it would be otherwise:
anonymous inner classes. These allow you to derive from a class or implement an interface
"inline" in the middle of a method. They allow you to use local variables from the method
you're running in (with restrictions) and even private variables and methods from the class
you're running in. As you're deriving from one class and have implicit access to an instance
of another, it's almost as if you get multiple inheritance. Almost. Unfortunately, they
look pretty ugly. Here's an example:



// Warning! Java code! Don't get confused by it!
interface SomeActionable
{
void doSomeAction();
}


public class Test
{
public static void main (String[] args)
{
// Only final (readonly) local variables can be
// used in an anonymous inner class

final String arg = args[0];

// Anonymous inner class
SomeActionable instance =
new SomeActionable()
{
public void doSomeAction()
{
// Equivalent to Console.WriteLine

System.out.println (arg);
}
};

// Now we've defined our implementation, use it
instance.doSomeAction();
}
}


This creates an implementation of the SomeActionable interface inline - it just prints out the
first command line parameter specified. It's often better than having a whole class just for the sake
of doing something (especially if you have lots of different implementations, each of which is really
just a line of code), but it's ugly to look at and gets worse if you need to distinguish between
accessing the class you're actually deriving from and the class you're declaring the anonymous inner class in.




Now, back to C#. In versions prior to 2.0, you couldn't create a delegate instance unless you had a normal method
which had the code you wanted to run. When the delegate only needs to do one thing (e.g. pass on the call to
another component, with some different parameters) this can be a bit of a pain - it's often much more readable to
see the code you're going to execute at the point you use the delegate, and all those extra methods usually do
nothing outside their use for constructing delegates. In addition, if you need to use some context which isn't already
in your object within a delegate implementation (e.g. a local variable), you sometimes need to create a whole extra class to
encapsulate that context. Yuk. Fortunately C# 2.0 has a delegate equivalent to Java's anonymous inner classes - but without
as much mess.



Here's a rough equivalent of the Java code above, this time in C# 2.0:



using System;

delegate void SomeAction();


class Test
{
static void Main(string[] args)
{
SomeAction instance =
delegate { Console.WriteLine(args[0]); };
instance();
}
}


Now, admittedly part of the reason this is so much shorter is the lack of comments and the way I've included the inline
code without putting line breaks before/after the braces. However, because there's so little to
definition, I could afford to do that without losing readability.
the delegate




Similar to Java and anonymous classes, when the C# compiler encounters an anonymous method, it either creates an extra (nested) type
or an extra method within the current type behind the scenes to contain the delegate implementation. It's easy to see
why an extra method would be required - but why would an extra type be needed? It's all to do with captured variables...


Captured variables



This is where things can become slightly difficult. Like many things, captured variables are fabulously useful,
but to start with they can be hard to understand, and they can change some of what you may think you already know about C#.
The purpose of them is very simple though - they're there to make local variables from the method declaring an anonymous method
available within the delegate itself.



Static and instance variables of the class don't need to be captured - normal instance and static methods can be created by the
compiler to access those. However, look at the example given above. How can the delegate "see" the value of args

to print out args[0]? In the code above, it's fairly simple - the delegate is only invoked within the method - but
the delegate could be returned from the method, or passed to another method, or stored in a variable somewhere. Just to
make things concrete, here's an example which does just that:



using System;

delegate void SomeAction();


class Test
{
static void Main(string[] args)
{
SomeAction instance = MakeDelegate();
instance();
instance();
}

static SomeAction MakeDelegate()
{
Random rng =
new Random();

return delegate { Console.WriteLine (rng.Next()); };
}
}



Here, a local variable is available in MakeDelegate, and the delegate uses that local variable
to print a new random number every time it's invoked. But what's the scope of that variable? Does the variable even
exist outside MakeDelegate? Well, the answer is yes - because the compiler compiles it into an instance
variable in a new type behind the scenes. If you compile the above and look at it with ildasm, you'll see
that there actually isn't a Random local variable in MakeDelegate at all, as far as
the runtime is concerned! Instead, there's a local variable of a nested type with some compiler-generated name (the time I
compiled it, the name was <>c__DisplayClass1). That type has a Random instance variable,
and when rng is assigned or used within MakeDelegate, it's that variable which is actually
used. The method used to implement the delegate signature is a member of the nested type, so it is able to get at
the Random instance even after MakeDelegate has finished executing.




Things become really tricky when there are multiple local variables being used in the delegate, in particular when
some of them are effectively created several times. This is best demonstrated with an example:



using System;

delegate void SomeAction();

class Test
{
static void Main(string[] args)
{
SomeAction[] instances =
new SomeAction[10];

int x;
for (int i=0; i < 10; i++)
{
x=0;
int y=0;
instances[i] =
delegate

{
Console.WriteLine (
"{0}, {1}", x, y);
x++;
y++;
};
}

instances[0]();
// Prints 0, 0
instances[0]();
// Prints 1, 1
instances[0]();
// Prints 2, 2
instances[1]();
// Prints 3, 0

x=10;
instances[2]();
// Prints 10, 0
}
}


Don't worry if it takes you a while to understand the output - it certainly threw me! Look carefully at
where x and y are declared. There's only one x variable for the whole method,
but there's a "new" y variable each time we go through the loop. That means that all the
delegate instances share the same x variable, but each one has a different y

variable. That's why the first number printed keeps going up, but the second number printed only goes up when the same
delegate instance is called again. (If another instance of the delegate was created inside the loop, then each pair
of delegate instances would share the same y variable.) Any access to the variable within the main body
of the method uses the "current" set of variables - so any change to y within the loop itself would
affect just the instance created in that iteration of the loop.



The reason this is contrary to intuition is that usually it doesn't really matter where a variable is declared
within a method (assuming you don't want to use the same name elsewhere in the method, and that you've made the scope
large enough to access it everywhere you want to). The location of the assignments matters, of course, but the actual
declarations have previously only affected the scope of the variable. They now affect the behaviour, as seen above -
the way the values of x and y behave in the delegate instances are very different.




In case you're wondering how some variables are shared and some aren't, in the above code two
are created - one with an x variable, and one with a y variable and another variable
referring to an instance of the first extra type. The delegate implementation is a member of the second type,
and each instance of the second type has a reference to the same instance of the first type. You can imagine
how complicated things must get when even more variables are involved!
extra types



As I said before, captured variables are very useful - but they come at the price of readability. Examples like
the code above, where different variables are shared or not shared, should be rare in real code. Anything where
the reader has to work out just where a variable came from and which variables will be associated with which
delegates is going to be a pain at maintenance time.

Threading

(1)What is Multi-tasking ?
Its a feature of modern operating systems with which we can run multiple programs at
same time example Word,Excel etc.
(2)What is Multi-threading ?
Multi-threading forms subset of Multi-tasking instead of having to switch between programs
this feature switches between different parts of the same program.Example you are writing
in word and at the same time word is doing a spell check in background.
(3)What is a Thread ?
A thread is the basic unit to which the operating system allocates processor time.
(4)Did VB6 support multi-threading ?
While VB6 supports multiple single-threaded apartments, it does not support a freethreading
model, which allows multiple threads to run against the same set of data.
(5)Can we have multiple threads in one App domain ?
One or more threads run in an AppDomain. An AppDomain is a runtime representation
of a logical process within a physical process.Each AppDomain is started with a single
thread, but can create additional threads from any of its threads.
Note :- All threading classes are defined in System.Threading namespace.
(6)Which namespace has threading ?
Systems.Threading has all the classes related to implement threading.Any .NET application
who wants to implement threading has to import this namespace.
Note :- .NET program always has atleast two threads running one the main program and
second the garbage collector.
(7)Can you explain in brief how can we implement threading ?
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim pthread1 As New Thread(AddressOf Thread1)
Dim pthread2 As New Thread(AddressOf Thread2)
pthread1.Start()
pthread2.Start()
End Sub
Public Sub Thread1()
Dim pintcount As Integer
Dim pstr As String
pstr = “This is first thread”
Do Until pintcount > 5
lstThreadDisplay.Items.Add(pstr)
pintcount = pintcount + 1
Loop
End Sub
Public Sub Thread2()
Dim pintcount As Integer
Dim pstr As String
pstr = “This is second thread”
Do Until pintcount > 5
lstThreadDisplay.Items.Add(pstr)
pintcount = pintcount + 1
Loop
End Sub
Above is a sample code which shows simple sample code for threading..Above sample
code can be found in “Threading” folder in CD provided.Above sample has two methods
“Thread1()” and “Thread2()” which are started in multi-threaded mode in Form load
event of the sample.
Note :- If you run the sample you will see that sometimes the first thread runs first and
then the second thread.This happens because of thread priorities .The first thread is run
with highest priority.

Jan 28, 2008

C# .NET interview questions

  1. Are private class-level variables inherited? - Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.
  2. Why does DllImport not work for me? - All methods marked with the DllImport attribute must be marked as public static extern.
  3. Why does my Windows application pop up a console window every time I run it? - Make sure that the target type set in the project properties setting is set to Windows Application, and not Console Application. If you’re using the command line, compile with /target:winexe, not /target:exe.
  4. Why do I get an error (CS1006) when trying to declare a method without specifying a return type? - If you leave off the return type on a method declaration, the compiler thinks you are trying to declare a constructor. So if you are trying to declare a method that returns nothing, use void. The following is an example: // This results in a CS1006 error public static staticMethod (mainStatic obj) // This will work as wanted public static void staticMethod (mainStatic obj)
  5. Why do I get a syntax error when trying to declare a variable called checked? - The word checked is a keyword in C#.
  6. Why do I get a security exception when I try to run my C# app? - Some security exceptions are thrown if you are working on a network share. There are some parts of the frameworks that will not run if being run off a share (roaming profile, mapped drives, etc.). To see if this is what’s happening, just move the executable over to your local drive and see if it runs without the exceptions. One of the common exceptions thrown under these conditions is System.Security.SecurityException. To get around this, you can change your security policy for the intranet zone, code group 1.2, (the zone that running off shared folders falls into) by using the caspol.exe tool.
  7. Why do I get a CS5001: does not have an entry point defined error when compiling? - The most common problem is that you used a lowercase ‘m’ when defining the Main method. The correct way to implement the entry point is as follows: class test { static void Main(string[] args) {} }
  8. What optimizations does the C# compiler perform when you use the /optimize+ compiler option? - The following is a response from a developer on the C# compiler team: We get rid of unused locals (i.e., locals that are never read, even if assigned). We get rid of unreachable code. We get rid of try-catch with an empty try. We get rid of try-finally with an empty try. We get rid of try-finally with an empty finally. We optimize branches over branches: gotoif A, lab1 goto lab2: lab1: turns into: gotoif !A, lab2 lab1: We optimize branches to ret, branches to next instruction, and branches to branches.
  9. What is the syntax for calling an overloaded constructor within a constructor (this() and constructorname() does not compile)? - The syntax for calling another constructor is as follows: class B { B(int i) { } } class C : B { C() : base(5) // call base constructor B(5) { } C(int i) : this() // call C() { } public static void Main() {} }
  10. What is the equivalent to regsvr32 and regsvr32 /u a file in .NET development? - Try using RegAsm.exe. Search MSDN on Assembly Registration Tool.
  11. What is the difference between a struct and a class in C#? - From language spec: The list of similarities between classes and structs is as follows. Longstructs can implement interfaces and can have the same kinds of members as classes. Structs differ from classes in several important ways; however, structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored on the stack or in-line. Careful programmers can sometimes enhance performance through judicious use of structs. For example, the use of a struct rather than a class for a Point can make a large difference in the number of memory allocations performed at runtime. The program below creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated-one for the array and one each for the 100 elements.
  12. My switch statement works differently than in C++! Why? - C# does not support an explicit fall through for case blocks. The following code is not legal and will not compile in C#:
    switch(x)
    {
    case 0: // do something
    case 1: // do something as continuation of case 0
    default: // do something in common with
    //0, 1 and everything else
    break;
    }

    To achieve the same effect in C#, the code must be modified as shown below (notice how the control flows are explicit):

    class Test
    {
    public static void Main() {
    int x = 3;
    switch(x)
    {
    case 0: // do something
    goto case 1;
    case 1: // do something in common with 0
    goto default;
    default: // do something in common with 0, 1, and anything else
    break;
    }
    }
    }
  13. Is there regular expression (regex) support available to C# developers? - Yes. The .NET class libraries provide support for regular expressions. Look at the System.Text.RegularExpressions namespace.
  14. Is there any sample C# code for simple threading? - Yes:
    using System;
    using System.Threading;
    class ThreadTest
    {
    public void runme()
    {
    Console.WriteLine("Runme Called");
    }
    public static void Main(String[] args)
    {
    ThreadTest b = new ThreadTest();
    Thread t = new Thread(new ThreadStart(b.runme));
    t.Start();
    }
    }
  15. Is there an equivalent of exit() for quitting a C# .NET application? - Yes, you can use System.Environment.Exit(int exitCode) to exit the application or Application.Exit() if it’s a Windows Forms app.
  16. Is there a way to force garbage collection? - Yes. Set all references to null and then call System.GC.Collect(). If you need to have some objects destructed, and System.GC.Collect() doesn’t seem to be doing it for you, you can force finalizers to be run by setting all the references to the object to null and then calling System.GC.RunFinalizers().
  17. Is there a way of specifying which block or loop to break out of when working with nested loops? - The easiest way is to use goto:
    using System;
    class BreakExample
    {
    public static void Main(String[] args) {
    for(int i=0; i<3; j="0" j ="=">
  18. Is it possible to restrict the scope of a field/method of a class to the classes in the same namespace? - There is no way to restrict to a namespace. Namespaces are never units of protection. But if you’re using assemblies, you can use the ‘internal’ access modifier to restrict access to only within the assembly.