Google

Wednesday, May 31, 2006

Page Events Summry

Listing 1: Page Events Summary

MethodPostBack Controls

ConstructorAlwaysAll
AddParsedSubObjectAlwaysAll
DeterminePostBackModeAlways Page
OnInitAlwaysAll

LoadPageStateFromPersistenceMediumPostBackPage
LoadViewStatePostBack All
ProcessPostData1PostBackPage
OnLoadAlwaysAll

ProcessPostData2PostBack Page
RaiseChangedEventsPostBackPage
RaisePostBackEventPostBackPage
OnPreRenderAlwaysAll

SaveViewStateAlwaysAll
SavePageStateToPersistenceMediumAlwaysPage
RenderAlwaysAll
OnUnload AlwaysAll

Google

Thursday, May 18, 2006

Some REAL tough interview questions

Everyone who writes code

  • Describe the difference between a Thread and a Process?
  • What is a Windows Service and how does its lifecycle differ from a "standard" EXE?
  • What is the maximum amount of memory any single process on Windows can address? Is this different than the maximum virtual memory for the system? How would this affect a system design?
  • What is the difference between an EXE and a DLL?
  • What is strong-typing versus weak-typing? Which is preferred? Why?
  • Corillian's product is a "Component Container." Name at least 3 component containers that ship now with the Windows Server Family.
  • What is a PID? How is it useful when troubleshooting a system?
  • How many processes can listen on a single TCP/IP port?
  • What is the GAC? What problem does it solve?

Mid-Level .NET Developer

  • Describe the difference between Interface-oriented, Object-oriented and Aspect-oriented programming.
  • Describe what an Interface is and how it's different from a Class.
  • What is Reflection?
  • What is the difference between XML Web Services using ASMX and .NET Remoting using SOAP?
  • Are the type system represented by XmlSchema and the CLS isomorphic?
  • Conceptually, what is the difference between early-binding and late-binding?
  • Is using Assembly.Load a static reference or dynamic reference?
  • When would using Assembly.LoadFrom or Assembly.LoadFile be appropriate?
  • What is an Asssembly Qualified Name? Is it a filename? How is it different?
  • Is this valid? Assembly.Load("foo.dll");
  • How is a strongly-named assembly different from one that isn't strongly-named?
  • Can DateTimes be null?
  • What is the JIT? What is NGEN? What are limitations and benefits of each?
  • How does the generational garbage collector in the .NET CLR manage object lifetime? What is non-deterministic finalization?
  • What is the difference between Finalize() and Dispose()?
  • How is the using() pattern useful? What is IDisposable? How does it support deterministic finalization?
  • What does this useful command line do? tasklist /m "mscor*"
  • What is the difference between in-proc and out-of-proc?
  • What technology enables out-of-proc communication in .NET?
  • When you're running a component within ASP.NET, what process is it running within on Windows XP? Windows 2000? Windows 2003?

Senior Developers/Architects

  • What's wrong with a line like this? DateTime.Parse(myString);
  • What are PDBs? Where must they be located for debugging to work?
  • What is cyclomatic complexity and why is it important?
  • Write a standard lock() plus "double check" to create a critical section around a variable access.
  • What is FullTrust? Do GAC'ed assemblies have FullTrust?
  • What benefit does your code receive if you decorate it with attributes demanding specific Security permissions?
  • What does this do? gacutil /l | find /i "Corillian"
  • What does this do? sn -t foo.dll
  • What ports must be open for DCOM over a firewall? What is the purpose of Port 135?
  • Contrast OOP and SOA. What are tenets of each?
  • How does the XmlSerializer work? What ACL permissions does a process using it require?
  • Why is catch(Exception) almost always a bad idea?
  • What is the difference between Debug.Write and Trace.Write? When should each be used?
  • What is the difference between a Debug and Release build? Is there a significant speed difference? Why or why not?
  • Does JITting occur per-assembly or per-method? How does this affect the working set?
  • Contrast the use of an abstract base class against an interface?
  • What is the difference between a.Equals(b) and a == b?
  • In the context of a comparison, what is object identity versus object equivalence?
  • How would one do a deep copy in .NET?
  • Explain current thinking around IClonable.
  • What is boxing?
  • Is string a value type or a reference type?
  • What is the significance of the "PropertySpecified" pattern used by the XmlSerializer? What problem does it attempt to solve?
  • Why are out parameters a bad idea in .NET? Are they?
  • Can attributes be placed on specific parameters to a method? Why is this useful?

C# Component Developers

  • Juxtapose the use of override with new. What is shadowing?
  • Explain the use of virtual, sealed, override, and abstract.
  • Explain the importance and use of each component of this string: Foo.Bar, Version=2.0.205.0, Culture=neutral, PublicKeyToken=593777ae2d274679d
  • Explain the differences between public, protected, private and internal.
  • What benefit do you get from using a Primary Interop Assembly (PIA)?
  • By what mechanism does NUnit know what methods to test?
  • What is the difference between: catch(Exception e){throw e;} and catch(Exception e){throw;}
  • What is the difference between typeof(foo) and myFoo.GetType()?
  • Explain what's happening in the first constructor: public class c{ public c(string a) : this() {;}; public c() {;} } How is this construct useful?
  • What is this? Can this be used within a static method?

ASP.NET (UI) Developers

  • Describe how a browser-based Form POST becomes a Server-Side event like Button1_OnClick.
  • What is a PostBack?
  • What is ViewState? How is it encoded? Is it encrypted? Who uses ViewState?
  • What is the <machinekey> element and what two ASP.NET technologies is it used for?
  • What three Session State providers are available in ASP.NET 1.1? What are the pros and cons of each?
  • What is Web Gardening? How would using it affect a design?
  • Given one ASP.NET application, how many application objects does it have on a single proc box? A dual? A dual with Web Gardening enabled? How would this affect a design?
  • Are threads reused in ASP.NET between reqeusts? Does every HttpRequest get its own thread? Should you use Thread Local storage with ASP.NET?
  • Is the [ThreadStatic] attribute useful in ASP.NET? Are there side effects? Good or bad?
  • Give an example of how using an HttpHandler could simplify an existing design that serves Check Images from an .aspx page.
  • What kinds of events can an HttpModule subscribe to? What influence can they have on an implementation? What can be done without recompiling the ASP.NET Application?
  • Describe ways to present an arbitrary endpoint (URL) and route requests to that endpoint to ASP.NET.
  • Explain how cookies work. Give an example of Cookie abuse.
  • Explain the importance of HttpRequest.ValidateInput()?
  • What kind of data is passed via HTTP Headers?
  • Juxtapose the HTTP verbs GET and POST. What is HEAD?
  • Name and describe at least a half dozen HTTP Status Codes and what they express to the requesting client.
  • How does if-not-modified-since work? How can it be programmatically implemented with ASP.NET?
    Explain <@OutputCache%> and the usage of VaryByParam, VaryByHeader.
  • How does VaryByCustom work?
  • How would one implement ASP.NET HTML output caching, caching outgoing versions of pages generated via all values of q= except where q=5 (as in http://localhost/page.aspx?q=5)?

Developers using XML

  • What is the purpose of XML Namespaces?
  • When is the DOM appropriate for use? When is it not? Are there size limitations?
  • What is the WS-I Basic Profile and why is it important?
  • Write a small XML document that uses a default namespace and a qualified (prefixed) namespace. Include elements from both namespace.
  • What is the one fundamental difference between Elements and Attributes?
  • What is the difference between Well-Formed XML and Valid XML?
  • How would you validate XML using .NET?
  • Why is this almost always a bad idea? When is it a good idea? myXmlDocument.SelectNodes("//mynode");
  • Describe the difference between pull-style parsers (XmlReader) and eventing-readers (Sax)
  • What is the difference between XPathDocument and XmlDocument? Describe situations where one should be used over the other.
  • What is the difference between an XML "Fragment" and an XML "Document."
  • What does it meant to say "the canonical" form of XML?
  • Why is the XML InfoSet specification different from the Xml DOM? What does the InfoSet attempt to solve?
  • Contrast DTDs versus XSDs. What are their similarities and differences? Which is preferred and why?
  • Does System.Xml support DTDs? How?
  • Can any XML Schema be represented as an object graph? Vice versa?


--
Thanks and Regards
_________________
Utsav Verma

Assistant Software Engineer
UBICS Enterprise Solutions Private Limited

http://utsav-verma.blogspot.com/

Google

Wednesday, May 17, 2006

.NET Remoting

The last two Nuts and Bolts articles focused on database related topics. This month we'll change gears and focus on something different. The focus of this month's article will be .NET remoting. We'll discuss what is .NET Remoting, how it compares to DCOM and Web services, and go through an example.

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.

Channels

Remote objects are accessed through Channels. Channels physically transport the messages to and from remote objects. There are two existing channels TcpChannel and HttpChannel. Their names give away the protocols that they use. In addition, the TcpChannel or HttpChannel can be extended, or a new channel created if you determine the existing channels do not meet your needs.

Create a Remotable Object

A remotable object is nothing more than an object that inherits from MarshalByRefObject. The following sample demonstrates a simple class to expose the omnipresent hello world. This object exposes a single method HelloWorld that will return a string. The only values that can be returned from methods are the classes in the .NET Framework that are serializable such as string and DataSet. In addition, if you need to return a user-defined object then the object needs to be marked as serializable.

Create a new C# class library project. Add a class called SampleObject and put in the following code. Add a reference to System.Runtime.Remoting in the project, otherwise the TcpChannel will not be found. Compile the class to make sure you have everything correct.

using System;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp; 

namespace CodeGuru.Remoting

{

  /// <remarks>

  /// Sample object to demonstrate the use of .NET Remoting.

  /// </remarks>

  public class SampleObject : MarshalByRefObject

  {

   /// <summary>

   /// Constructor

   /// </summary>

   public SampleObject()

   {

   } 

   /// <summary>

   /// Return a hello message

   /// </summary>

   /// <returns>Hello world message</returns>

   public string HelloWorld()

   {

     return "Hello World!";

   }

  }

}

Create a Server To Expose the Remotable Object

We need to create a server object that will act as a listener to accept remote object requests. For this example we will use the TCP/IP channel. We first create an instance of the channel and then register it for use by clients at a specific port. The service can be registered as WellKnownObjectMode.SingleCall, which results in a new instance of the object for each client, or as WellKnownObjectMode.Singleton, which results in one instance of the object used for all clients.

It is not necessary to create the server listener if you are planning to use IIS. For obvious reasons, IIS only supports the use of the HttpChannel. Create a virtual directory for your application and then put code to register your service in the Application_Start event.

For our example, we'll go ahead and create a server listener in case you don't have IIS. Since the service needs to be bound to an available port, for our example I chose 8080, which is a port that I know to be unused on my computer. You may need to choose a different port depending upon what ports you have available. To see a list of the used ports on your computer open a command prompt and issue the command "netstat --a". It may produce a long listing so make sure the command prompt buffer sizes are set to allow scrolling. Compile the class to make sure you have everything correct.

Create a new C# console application project. Add a class called SampleServer and paste in the following code. Add a reference to System.Runtime.Remoting in the project, otherwise the TcpChannel will not be found. In addition, add a reference to the project containing the SampleObject, otherwise the code will not compile because it won't know how to find a reference to SampleObject.

using System;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp; 

namespace CodeGuru.Remoting

{

  /// <remarks>

/// Sample server to demonstrate the use of .NET Remoting.

  /// </remarks>

  public class SampleServer

  {

   public static int Main(string [] args)

   {

    // Create an instance of a channel

     TcpChannel channel = new TcpChannel(8080);

     ChannelServices.RegisterChannel(channel); 

     // Register as an available service with the name HelloWorld

     RemotingConfiguration.RegisterWellKnownServiceType(

         typeof(SampleObject),

         "HelloWorld",

         WellKnownObjectMode.SingleCall ); 

     System.Console.WriteLine("Press the enter key to exit...");

     System.Console.ReadLine();

     return 0;

   } 

  }

}

Create a Client To Use the Remotable Object

Now that we have our remotable object and a server object to listen for requests, let's create a client to use it. Our client will be very simple. It will connect to the server, create an instance of the object using the server, and then execute the HelloWorld method.

Create a new C# console application project. Add a class called SampleClient and paste in the following code. Add a reference to System.Runtime.Remoting in the project, otherwise the TcpChannel will not be found. In addition, add a reference to the project containing the SampleObject, otherwise the code will not compile because it won't know how to find a reference to SampleObject. Compile the class to make sure you have everything correct.

using System;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp; 

namespace CodeGuru.Remoting

{

  /// <remarks>

  /// Sample client to demonstrate the use of .NET Remoting.

  /// </remarks>

  public class SampleClient

  {

   public static int Main(string [] args)

   {

     // Create a channel for communicating w/ the remote object

     // Notice no port is specified on the client

     TcpChannel chan = new TcpChannel();

     ChannelServices.RegisterChannel(chan); 

     // Create an instance of the remote object

     SampleObject obj = (SampleObject) Activator.GetObject(

         typeof(CodeGuru.Remoting.SampleObject),

         "tcp://localhost:8080/HelloWorld" ); 

     // Use the object

     if( obj.Equals(null) )

     {

       System.Console.WriteLine("Error: unable to locate server");

     }

     else

     {

       Console.WriteLine(obj.HelloWorld());

     }

     return 0;

   }

  }

}

Test the Remoting Sample

Once you have created the projects and successfully compiled each of them you are ready to try it out. Assuming you chose a free TCP/IP port for the service, start the server executable. After the server successfully starts it will result in a console window being displayed with the message "Press the enter key to exit". The server is listening so you are now ready to run the client. Executing the client should result in "Hello World!" being displayed in a separate console window. The client window will then close while the server remains open and available.

If you have multiple computers available to you on a network you could execute the server on one machine and the client on another just to prove to yourself that it really is remoting. In order to run on separate machines you would need to change the reference to localhost in the sample client to point to the appropriate location.

Summary

.NET Remoting is a powerful way to enable interprocess communication. It is more complicated to program against than Web services. You need to decide for yourself whether your standard architecture is to use .NET Remoting or Web services.

Parallel Computing with .NET Remoting

Eric Bergman-Terrell

.NET Remoting allows you to distribute computing across multiple machines with ease, with a surprisingly small amount of programming. In this article, Eric Bergman-Terrell creates an application called Digits of Pi, which calculates π to a ludicrously high precision using multiple machines computing in parallel. He's managed to calculate 10,000 digits in just under 12 hours with a modest amount of computing power. That's about 300 percent faster than one machine alone could have managed by itself.

After downloading the sample application source code (available in the Download file), open the Everything.sln solution. This solution contains the three projects needed to run the Digits of Pi application (Client, Server, and ServerLoader). The solution also contains a project named SimpleClient that I'll discuss later. Once Everything.sln is loaded, select Build | Batch Build... Press the Select All button and then press Build. After everything is built, it's time to install the software on your local machine, as well as the remote machines on your LAN.

On your local machine, create a folder and copy the following files into it:

Server\bin\Release\Plouffe_Bellard.dll

Client\bin\Release\DigitsOfPi.exe

On each remote machine, and the local machine, create a folder and copy the following files into that folder:

Server\bin\Release\Plouffe_Bellard.dll

ServerLoader\bin\Release\ServerLoader.exe

ServerLoader\ServerLoader.exe.config

Then run the ServerLoader.exe program. Needless to say, each machine will need to have the .NET Framework installed before running the ServerLoader and the Digits of Pi program.

After the ServerLoader program is running on all remote machines and the local machine, run the Digits of Pi program. Press Configure... (see Figure 1) and add the machine names of the local and remote machines. If you're not sure what a machine is named, look at the ServerLoader program—it displays its machine name on its form. If you're lucky enough to have a multiple-CPU system, you can enter that machine name once for each CPU. Just type the machine name followed by an @ sign, followed by a number. For example, if you have a two-CPU system named "Brainiac", type in the following machine names: " Brainiac@1" and "Brainiac@2". You don't have to enter multiple machine names for multiple CPU systems, but doing so will ensure that all the machine's CPUs are used to calculate π. After you've entered all the machine names, press OK.

Then specify the number of digits (see Figure 2 ) to calculate and press Calculate. Start with a small number of digits—the program takes more and more time to compute digits of π further and further to the right of the decimal point.

Figure 3 shows how the Digits of Pi program distributes the workload to the local and remote machines, using TCP/IP port 9000 to send requests and receive results. We'll explore the details of Remoting, the Plouffe_Bellard server object, the ServerLoader program, the SimpleClient program, and the Digits of Pi program next.

Remoting basics

.NET Remoting enables an object to communicate with other objects, regardless of whether they're running on the same computer or on remote computers. .NET Remoting is superficially similar to Web Services, but .NET Remoting is the better technology for applications like Digits of Pi that are entirely written in .NET programming languages, and run exclusively on machines running the .NET Framework. See " ASP.NET Web Services or .NET Remoting: How to Choose" in the "Resources" sidebar near the end of this article for a comparison of the two technologies.

You can access a remote object with .NET Remoting by following these steps:

  1. Create a .NET server object (DLL) that inherits from System.MarshalByRefObject. The server object will be run on the remote machines and the local machine too.
  2. Create a server loader program that loads the server object by calling RemotingConfiguration.Configure. The server loader program will also be run on the remote and local machines.
  3. Create a client program that accesses the server object with Activator.GetObject. You'll need to add a reference to the server object to compile this program. This client program will only be run on the local machine.

The server object

The server object calculates the specified nine digits of π. It's named Plouffe_Bellard because it uses Fabrice Bellard's enhanced version of Simon Plouffe's algorithm. While faster algorithms are available, the Plouffe-Bellard algorithm is very simple (less than 300 lines of source code), uses a small amount of memory, and is ideal for parallel execution because each set of nine digits can be computed independently. The Plouffe_Bellard.CalculatePiDigits method calculates the nine digits of π that start at the specified position. For example, CalculatePiDigits(1) returns the nine digits starting with the first digit: 141592653. CalculatePiDigits(10) returns the next nine digits starting with the tenth digit, and so on.

The ServerLoader

The ServerLoader program loads the server object, specifies the protocol and port used to access the server object over the LAN, listens for incoming calls from the client program, processes calls, and returns the results. Remarkably, all of this can be accomplished with just one line of code, by calling the RemotingConfiguration.Configure method with the path to a configuration file. The ServerLoader program loads a configuration file named ServerLoader.exe.config (see Listing 1). This configuration file specifies that the server object is loaded in SingleCall mode, which means that every incoming call is serviced by a new instance of the server object. If the server object were loaded in Singleton mode, every incoming call would be serviced by the same instance. The type attribute specifies the full type name of the server object (including the PB namespace) and the name of its assembly. The objectUri attribute specifies the endpoint of the object's Uniform Resource Identifier (URI). The <channel> element specifies that the server object will be accessed using the TCP protocol, port 9000.

Listing 1. ServerLoader.exe.config.

<configuration>

  <system.runtime.remoting> 

    <application name = "ServerLoader"> 

      <service>

        <wellknown

          mode="SingleCall"

          type="PB.Plouffe_Bellard,Plouffe_Bellard"

          objectUri="Plouffe_Bellard"/>

      </service>

      <channels>

        <channel ref="tcp server" port="9000"/>

      </channels>

    </application>

  </system.runtime.remoting>

</configuration>

SimpleClient

I created a program named SimpleClient to demonstrate how easy it is for a client program to access a server object on a remote machine. To run SimpleClient, first run the ServerLoader on a remote machine and run the SimpleClient.exe program on the local machine. Enter the remote machine name in the Remote Machine text box and press the Calculate button to compute the first nine digits of π . SimpleClient's CalculateButton_Click method contains all the code that the client needs to access the remote server (see Listing 2). The remote server is accessed with a URL made up of the remote machine name, the protocol (TCP), and the port number (9000). For example, the URL to access the server on my "Pentium 200" machine is tcp://Pentium 200:9000/ServerLoader/Plouffe_Bellard. After creating the URL, Activator.GetObject is called with the type of the server (Plouffe_Bellard) and the URL. Then the return value is cast to a Plouffe_Bellard object and it's ready for use. When its CalculatePiDigits method is called, the request is sent to the ServerLoader on the remote machine. Then the server object computes the digits. Finally, when the results come back to the client program, they're displayed in a text box.

Listing 2. SimpleClient code to access the remote server.

private void CalculateButton_Click(object sender,

                              System.EventArgs e)

{

  Cursor.Current = Cursors.WaitCursor; 

  Plouffe_Bellard PiCalculator = null; 

  String MachineName = RemoteMachineTextBox.Text; 

  try

  {

    int port = 9000; 

    String URL = "tcp://" + MachineName + ":" +

       port + "/ServerLoader/Plouffe_Bellard";

    PiCalculator = (Plouffe_Bellard)

       Activator.GetObject(typeof(Plouffe_Bellard), URL);

    ResultsTextBox.Text = "3." +

       PiCalculator.CalculatePiDigits(1);

  }

  catch(Exception)

  {

    MessageBox.Show(

       "Need to run ServerLoader.exe on machine " +

       MachineName, "Simple Client",

       MessageBoxButtons.OK, MessageBoxIcon.Error);

  } 

  Cursor.Current = Cursors.Arrow;

}

The Digits of Pi client

The Digits of Pi client program is much more elaborate than SimpleClient. SimpleClient only computes the first nine digits of π by accessing the server object on one remote machine. Digits of Pi, on the other hand, computes the user-specified number of digits in parallel, using all of the remote and local machines specified in the Configure dialog (shown in Figure 1). The server objects are accessed in separate threads in order to keep the Digits of Pi GUI responsive to user interaction during the potentially lengthy calculation process.

Digits of Pi distributes the workload among all the available machines by using an array that breaks the job into nine-digit chunks. After the user presses the Calculate button, it creates a SolutionArray (see Figure 4). The SolutionArray has a SolutionItem element for each group of nine digits of π that will be calculated. When a server object has computed the group of nine digits specified by the m_Digit field, the digits are stored in the m_Results member. The m_MachineName member contains the name of the machine on which the server is running. The machine name is stored so that Digits of Pi can display the total number of digits calculated by each machine (see Figure 2).

In order to have the server objects calculate in parallel, Digits of Pi creates a thread for each server object and starts the thread calculating. Then it must wait for all the threads to finish calculating before the final results can be displayed. WaitHandles are useful for waiting for multiple threads. Digits of Pi uses a WaitHandle for each thread in order to wait for all threads to complete.

CalculationThread.Calculate (see Listing 3) is called to create a thread for each server object. It starts the thread running and then returns an AutoResetEvent, which is derived from WaitHandle. Each thread's AutoResetEvent is stored in an array, which is passed to WaitHandle.WaitAll. When a thread completes its calculations, it calls the Set method on its AutoResetEvent. When the last thread calls the Set method, the WaitAll call returns, and the digits of π are displayed.

Listing 3. CalculationThread.

public static WaitHandle Calculate(

SolutionArray solutionArray, String machineName)

{

  CalculationThread calculationThread = new

    CalculationThread(solutionArray, machineName);

  Thread thread = new Thread(new

    ThreadStart(calculationThread.Calculate));

  thread.Start();

  return calculationThread.calculationDone;

}

Each thread follows the same algorithm: While there's more work to do, the thread grabs the next SolutionItem, stores its server object's machine name in the SolutionItem, calculates the specified nine digits, and stores the result in the SolutionItem. This process continues until all the SolutionItems have been filled with results. See Listing 4 for the details.

Listing 4. CalculationThread.Calculate.

public void Calculate()

{

  Plouffe_Bellard PiCalculator =

    RemotePiCalculator.GetPiCalculator(

      GetRealMachineName(machineName)); 

  if (PiCalculator != null)

  {

    SolutionItem Item = null;

    bool Abort; 

    do

    {

      Abort = solutionArray.Abort; 

      if (!Abort)

      {

        Item = solutionArray.GetNextItem(); 

        if (Item != null)

        {

          Item.MachineName = machineName; 

          try

          {

            Item.Results =

           PiCalculator.CalculatePiDigits(Item.Digit);

          }

          catch (Exception e)

          {

            Abort = true;

            MessageBox.Show(

              "Cannot access remote object on host " +

              machineName + Environment.NewLine +

              Environment.NewLine + "Message:  " +

              e.Message, Globals.ProgramName,

              MessageBoxButtons.OK,

              MessageBoxIcon.Error);

          } 

          UpdateStatisticsDelegate USD = new

            UpdateStatisticsDelegate(

              MF.UpdateStatistics); 

          MF.Invoke(USD, new Object[] {} );

        }

      }

    } while (Item != null && !Abort); 

    calculationDone.Set();

  }

}

Here's a blow-by-blow description:

  1. The GetRealMachineName removes the @1 pattern from multi-CPU machine names. For example, GetRealMachineName("Brainiac@1") returns "Brainiac". See the text in the dialog box in Figure 1 for an explanation of multi-CPU machine names.
  2. Once the real machine name is known, it's passed to RemotePiCalculator.GetPiCalculator, and the server object on that machine is then accessible via the PiCalculator variable.
  3. The Abort property is set if the user has pressed the Cancel button. If the Abort property is true, the thread stops calculating.
  4. The call to MF.Invoke allows the thread to safely update the statistics in the ListView (see Figure 2) even though that ListView was created by a different thread. In 32-bit Windows programming, it's a big no-no to manipulate controls in a thread other than the one that created them.
  5. Once the loop is complete (meaning that all specified digits of π have been computed, or the user pressed the Cancel button), the Set function of the thread's AutoResetEvent is called.
  6. When each thread has called its AutoResetEvent's Set function, the call to WaitHandle.WaitAll will return and the results will be displayed.

Thread synchronization

There are several places in Digits of Pi's code where errors would occur if the code were accessed simultaneously by multiple threads. For example, if two threads called SolutionArray.GetNextItem at precisely the same time, they might both end with the same item. That's why the GetNextItem method has the [MethodImpl(MethodImplOptions.Synchronized)] attribute, which ensures that only one thread can call it at a time. Making a method synchronized is a good strategy when every line of the method shouldn't be accessible by more than one thread at a time.

Since the MainForm.Calculate method has only one line that can't be accessed simultaneously by multiple threads, it calls Monitor.Enter before the line, and Monitor.Exit after the line. Monitor.Enter will block if the line is already running in another thread. While the entire function could have been made synchronized, protecting only the lines that need to be protected from multi-thread access will tend to result in better performance.

Objects derived from System.Windows.Forms.Control (for example, Buttons, TextBoxes, RichTextBoxes, Labels, ListBoxes, ListViews, and so on) should only be manipulated by the thread that created them. To safely manipulate a Control derivative from a thread that didn't create it, first put the manipulation code in a method and declare a delegate for that method:

delegate void SetResultsTextDelegate(String Text); 

private void SetResultsText(String Text)

{

  ResultsRichTextBox.Text = Text;

}

Then call the method indirectly, using Form.Invoke:

SetResultsTextDelegate SRTD = new

  SetResultsTextDelegate(SetResultsText); 

Invoke(SRTD, new object[] { "" } );

The Invoke method calls the method from the thread that created it, with parameters corresponding to the elements in the object array.

Summary

.NET Remoting is a simple and convenient mechanism for executing code on remote (and local) machines. All that's necessary is to package the code in a .NET object, write a program to load the object and listen for requests, and call Activator.GetObject in the client program. If you have some idle machines on your LAN, it's easy to put them to work to solve a problem in parallel. Just remember to use the proper thread synchronization mechanisms to keep one thread from stepping on another thread's toes.

Google

Tuesday, May 16, 2006

Pin pointed articles on Isolation, locks et al

 
Beauty of this article is that it contains exact, interview like, answer ro the isolation and stuff

--
Thanks and Regards
_________________
Utsav Verma

Assistant Software Engineer
UBICS Enterprise Solutions Private Limited

http://utsav-verma.blogspot.com/

Google

Monday, May 15, 2006

Impersonation


What is impersonation

Dictionary meaning of impersonation is - Pretending to be another person.

 

Through this definition we should have and idea (in light of asp.net) that impersonation loosely has to do something with identity interchange. Means, one user id is pretending to be another user id

 

Definition of impersonation from MSDN is –

 

"Impersonation is a means by which you can have the ASP.NET engine operates under the authenticated user's user account."

 

And

 

            "Impersonation is when ASP.NET executes code in the context of an authenticated and authorized client."

 

Why impersonation

 

By default, the ASP.NET engine operates under the ASPNET user account. But this account has limited access over the resources available on server

 

Sometimes you need to access network resources such as a file on a shared drive, which requires additional permissions.

 

Suppose, I have added following lines in my web.config file (my purpose in this article is to clear concept not the code, please refer to the links given blow for full blown coding examples)

 

<identity impersonate="true"

          userName="utsav"

          password="utsav123" />

 

now whenever a request to the IIS will be made for given app, my app can access all resources which account 'utsav' can access!

 

Following flow chart can clear few things –
 

 

Some twists

  • In asp, impersonation is enabled by default. Many times you use impersonation in asp.net just for the sake of backward compatibility.

Google

Authorization, authentication and impersonation...

http://aspnet.4guysfromrolla.com/demos/printPage.aspx?path=/articles/031204-1.aspx

Google

Answers upto question 13

Q - Explain the differences between Server-side and Client-side code?

 

Server side scripting means that all the script will be executed by the server and interpreted as needed. Client side scripting means that the script will be executed immediately in the browser such as form field validation, clock, email validation, etc. Client side scripting is usually done in VBScript or JavaScript. Since the code is included in the HTML page, anyone can see the code by viewing the page source. It also poses as a possible security hazard for the client computer.

 

Q - What type of code (server or client) is found in a Code-Behind Class?

 

Server side

 

Q - Should validation (did the user enter a real date) occur server-side or client-side? Why?

 

http://www.lhotka.net/WeBlog/CommentView,guid,8fa07593-a357-49a4-9b86-1ee82a58f2b9.aspx

 

Validation must be placed on server side, client side validations are welcome if placed. Lot of Web apps is that the validation is only put into the browser - which is horrible, because it is too easy to bypass. That is simply a flawed approach to development.

 

Another point is that UI technologies are changed too frequently (asp.net 2.0 is out and you never know when'd be next JavaScript version will be out!) but same is not the case with your business logic, that remains consistent for longer time.

 

At least with ASP.NET there are the validation controls, which simplify the process of creating and maintaining the duplicate validation logic in the browser. You are still left to manually keep the logic in sync, but at least it doesn't require hand-coding JavaScript in most cases.

 

Q - What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?

 

Response.Redirect simply sends a message down to the browser, telling it to move to another page. So, you may run code like:

 

Response.Redirect("WebForm2.aspx")

or

 

Response.Redirect("http://www.karlmoore.com/")

to send the user to another page.

 

Server.Transfer is similar in that it sends the user to another page with a statement such as Server.Transfer("WebForm2.aspx"). However, the statement has a number of distinct advantages and disadvantages.

 

Firstly, transferring to another page using Server.Transfer conserves server resources. Instead of telling the browser to redirect, it simply changes the "focus" on the Web server and transfers the request. This means you don't get quite as many HTTP requests coming through, which therefore eases the pressure on your Web server and makes your applications run faster.

 

But watch out: because the "transfer" process can work on only those sites running on the server, you can't use Server.Transfer to send the user to an external site. Only Response.Redirect can do that.

 

Secondly, Server.Transfer maintains the original URL in the browser. This can really help streamline data entry techniques, although it may make for confusion when debugging.

 

That's not all: The Server.Transfer method also has a second parameter—"preserveForm". If you set this to True, using a statement such as Server.Transfer("WebForm2.aspx", True), the existing query string and any form variables will still be available to the page you are transferring to.

 

For example, if your WebForm1.aspx has a TextBox control called TextBox1 and you transferred to WebForm2.aspx with the preserveForm parameter set to True, you'd be able to retrieve the value of the original page TextBox control by referencing Request.Form("TextBox1").

 

This technique is great for wizard-style input forms split over multiple pages. But there's another thing you'll want to watch out for when using the preserveForm parameter. ASP.NET has a bug whereby, in certain situations, an error will occur when attempting to transfer the form and query string values. You'll find this documented at http://support.microsoft.com/default.aspx?id=kb;en-us;Q316920.

 

The unofficial solution is to set the enableViewStateMac property to True on the page you'll be transferring to, then set it back to False. This records that you want a definitive False value for this property and resolves the bug.

 

So, in brief: Response.Redirect simply tells the browser to visit another page. Server.Transfer helps reduce server requests, keeps the URL the same and, with a little bug-bashing, allows you to transfer the query string and form variables.

 

 

Q - Can you give an example of when it would be appropriate to use a web service as opposed to a non-serviced .NET component.

 

(http://www.oreilly.com/catalog/comdotnetsvs/chapter/ch10.html )

 

A .NET component that uses COM+ services is called a serviced component to distinguish it from the standard managed components in .NET.

 

One imp point which I get is web services are not restricted through firewalls and stuffs, since it uses text based protocols, but non serviced components can be stopped.

 

Another point (I dunno whether I m correct or not) web services can be device independent, i.e., same web service can be called from cell phone as well as your program.

 

Q Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?

 

1. ASP.NET DataSet is Designed for connected access (through connection object).

2. Dataset is a data structure which represents the complete table data at same time.

3. Dataset is just a data store and manipulation is done through DataAdapters in .NET.

4. DataSet can contain multiple tables Retrieving data from more than one table or source does not require a JOIN.

5. XML, like HTML, is plaintext: "Firewall friendly"

 

About RecordSet:

 

1. ADO RecordSet is disconnected Architecture.

2. Recordset provides data one row at a time.

3. Recordset has the logic to update and manipulate data

4. The RecordSet is the central data container

RecordSet is one (1) table that contains all the data

Retrieving data from more than one table or source requires a database JOIN.

5. Problems marshalling through firewalls (DCOM, binary)

 

Q Can you give an example of what might be best suited to place in

the Application_Start and Session_Start subroutines?

 

We may initialize site visit counter variable in Application start.

In session start, we may initialize time spent by user variable

 

Q 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-robin load balancing) what would be the best approach to maintain login-in state for the users?

 

OutProc or SqlServer mode, since given condition is web farm condition in which inProc mode of storing session doesn't work

 

Q - How does VB.NET/C# achieve polymorphism?

Polymorphism is one of the crucial features of OOP. It means  "one name, multiple forms". It is also called as Overloading which means the use of same thing for different purposes. Using Polymorphism we can create as many functions we want with one function name but with different argument list. The function performs different operations based on the argument list in the function call. The exact function to be invoked will be determined by checking the type and number of arguments in the function.

 

The following code demonstrates the implementation of Polymorphism.

 

Module Module1

 

Sub Main()

Dim two As New One()

WriteLine(two.add(10))

'calls the function with one argument

WriteLine(two.add(10, 20))

'calls the function with two arguments

WriteLine(two.add(10, 20, 30))

'calls the function with three arguments

Read()

End Sub

 

End Module

 

Public Class One

Public i, j, k As Integer

 

Public Function add(ByVal i As Integer) As Integer

'function with one argument

Return i

End Function

 

Public Function add(ByVal i As Integer, ByVal j As Integer) As Integer

'function with two arguments

Return i + j

End Function

 

Public Function add(ByVal i As Integer, ByVal j As Integer, ByVal k As Integer) As Integer

'function with three arguments

Return i + j + k

End Function

 

End Class 

 

(I hope it'd not be pain in you're a** to convert this tiny code in c#)

 

Q - Can you explain what inheritance is and an example of when you might use it?

Q - How would you implement inheritance using VB.NET/C#?

 

Defining inheritance should not be a big thing, visit http://www.codeproject.com/aspnet/AspNetInheritance.asp for a practical scenario where inheritance can be used.

 

In this article, author has tried to create a simple role management framework. A common page does all security check and load data according to user and that common page is inherited by all the pages in the app.


Google

Reactions!

Well, here is one of the reaction on our blog!

Google

Friday, May 12, 2006

Helpful Link

Hi
 
Visist this site for some good collection of links regarding .net
(contributed by : Anil Sir)

--
Thanks and Regards
_________________
Utsav Verma

Assistant Software Engineer
UBICS Enterprise Solutions Private Limited

http://utsav-verma.blogspot.com/

Google

Difference between C# and VB.net - Imp Points

This entry is based on the following link - http://www.willydev.net/descargas/VBCSharpWP.pdf

• C# supports following data types while vb.net doesn’t –
o Signed byte
o Unsigned short
o Unsigned int
o Unsigned long

• Left and right shift are not available in vb.net

• Postfix and prefix increment/decrement are not available in vb.net

• Pointer to member are not available in vb.net, in C# they are available in unsafe mode only

• Vb.net supports both structured and unstructured error handling while c# supports only structured one

• VB.net has a project level setting to check for overflow while C# worked under a checked or unchecked context (So far I am not very clear what exactly does it mean and how to use it). In unchecked context, overflow error are ignored.

• C# can’t pass objects by value at all…!

• To pass a parameter by reference c# uses ref keyword void ABC (ref int x)

• Vb.net has a provision for optional argument while c# doesn’t.

• Implementing Late Binding is easier in vb.net then c#, vb.net compiler calls a helper method behind the scene to implement reflection, in c# we have to code reflection to implement late binding.

• C# permits you to write unmanaged code while vb.net don’t.