Saturday 10 September 2011

What is strong-typing versus weak-typing? Which is preferred? Why? Post title

Strong type is checking the types of variables as soon as possible, usually at compile time. While weak typing is delaying checking the types of the system as late as possible, usually to run-time. Which is preferred depends on what you want. For scripts & quick stuff you’ll usually want weak typing, because you want to write as much less code as possible. In big programs, strong typing can reduce errors at compile time.



In strongly-typed programming languages you usually have to declare variables prior to using them. Strong-typing is the strict enforcement of [type] rules. All types (int, short, long, string) are know at compile time and are statically bound. So C# is a strongly-typed language because variables must be assigned a type before you use them. If you came from the ASP world then you will remember having to use either Javascript or VBScript. Variables that you declare in either of those languages can hold any data type which makes it weakly-typed.
But lets take this up a level. Instead to talking about programming languages, lets talk about strongly-typed/weakly-typed objects. The DataSet object is a great example. If we use a weakly-typed dataset, the developer needs to know the name of the table and the name of the field being requested. Since we are just passing strings, this code will compile and will not show any possible problems (like typing the name of the table wrong) until run time.
  string s = (string) myDataSet.Tables["Customers"].Rows[0]["CustomerID"];
If our Dataset is Strongly-Typed, we are able to access the names of the tables and columns directly. Any errors are caught at compile time.
  string s = myDataSet.Customers[0].CustomerID;
I am not really going to argue which is better, I will leave that up to you. I will leave you with this question though; would you rather catch your errors at compile time, or run-time?

Implementing the Basic Patterns in ASP.NET


The previous sections briefly describe five common and simple types of design pattern. These are all applicable to ASP.NET, and reasonably easy to implement. In fact, ASP.NET and the .NET Framework automatically implement several of them. Figure 5 shows schematically how these patterns relate to ASP.NET applications; you will see descriptions of their implementation or use in the subsequent sections of this article.
Figure 5 - How ASP.NET implements some basic design patterns
Figure 5 - How ASP.NET implements some basic design patterns

Implementation of the Model-View-Presenter Pattern

For example, a page might use a separate class that exposes methods to read and update a database table. This class can use the SqlClient, OleDb, or another data provider to connect to the database, and execute SELECT and UPDATE queries or stored procedures. The code in the code-behind file uses this class to retrieve the data, and populates the controls defined in the ASPX file that generates the user interface. When the user interacts with controls in the page, perhaps changing values in the data, code in the code-behind file executes during the postback and uses the data access class to push the changes back into the database.
The ASP.NET code-behind technology, which uses partial classes, provides a natural implementation of the MVP pattern. The code-behind file (the Presenter) contains all the logic and processing code, and populates the page (the View). Event handlers within the code-behind file handle events raised by controls, or by the page itself, to perform actions when a postback to the server occurs. To complete this pattern, the code-behind file can use a separate data access layer or component (the Model) to read from, write to, and expose the source data - usually accessed through built-in providers that are part of the .NET Framework.
The sample application uses the code-behind model throughout, thereby implementing the MVP pattern on each page. The default page (Default.aspx) demonstrates the ASP.NET application of the MVP pattern by displaying a View that contains a series of controls that allow users to execute any of a range of functions that fetch and display data (see Figure 6).
Figure 6 - Finding a customer name in the Default page of the sample application
Clicking one of the buttons causes a postback to the server and raises the event that corresponds to that button. For example, the interface component for the second button shown in Figure 6 is an ASP.NET Button control, declared within the View (the ASPX page), which initiates an event handler named btnCustModelClick in the Presenter (the code-behind file) to handle the Click event:
<asp:Button ID="btn_CustModel" runat="server" Text="&nbsp;&nbsp;&nbsp;"
            OnClick="btn_CustModel_Click" />
Get name for customer
<asp:Button ID="btn_CustModel" runat="server" Text="&nbsp;&nbsp;&nbsp;"
            OnClick="btn_CustModel_Click" />
Get name for customer
<asp:TextBox ID="txtID_CustModel" runat="server" Text="ALFKI" Columns="3" /> 
from CustomerModel
In the Presenter (the code-behind file) is the declaration of the btnCustModelClick method, which creates an instance of the Model (a class named CustomerModel.cs in the App_Code folder) and calls one of its methods to get the name of the customer identified by the customer ID in the text box next to that button:
protected void btn_CustModel_Click(object sender, EventArgs e)
// display the name of the specified customer
{
  try
  {
    // use method of the CustomerModel class
    CustomerModel customers = new CustomerModel();
    Label1.Text += "Customer Name from CustomerModel class: ";
    Label1.Text += customers.GetCustomerName(txtID_CustModel.Text);
  }
  catch (Exception ex)
  {
    Label1.Text += "PAGE ERROR: " + ex.Message;
  }
  Label1.Text += "<p />";
}
You can view the contents of the files Default.aspx (the View), Default.aspx.cs (the Presenter), and CustomerModel.cs (the Model) that implement the MVP pattern in this example to see all of the UI control declarations and code they contain. As you saw in Figure 6, there are buttons to execute a range of methods of the CustomerModel class, as well as methods of the Repository, Web Reference, and Service Agent implementations discussed in the following sections.
Notice that the Default.aspx page (in Figure 6) contains a drop-down list where you can select a page or view you want to see, loaded using an implementation of the Front Controller pattern. You will see details of this in the section "Implementation of the Front Controller Pattern" later in the next article. You can use this drop-down list to navigate to other pages to see the examples, for example the Use Case Controller example page or the Publish-Subscribe example page.

Implementation of the Provider Pattern

ASP.NET uses the Provider pattern in a number of places. These include providers for the Membership and Role Management system (such as the SqlMembershipProvider and SqlRoleProvider), the Site Navigation system (the XmlSiteMapProvider), and the user profile management system (such as the SqlProfileProvider). The data access components in ASP.NET, such as SqlDataSource, also rely on providers. These providers are part of the .NET Framework data-access namespaces, including SqlClient, OleDb, Odbc, and OracleClient. Each provider is configured in the Web.config file, with the default settings configured in the server's root Web.config file. Developers can create their own providers based on an interface that defines the requirements, or by inheriting from a base class containing common functionality for that type of provider. For example, developers can extend the DataSourceControl class to create their own data source controls that interface with a non-supported or custom data store.

Implementation of the Adapter Pattern

ASP.NET uses adapters to generate the output from server controls. By default, server controls use adapters such as the WebControlAdapter or DataBoundControlAdapter to generate the markup (such as HTML) and other content output by the control. Each adapter provides methods such as Render and CreateChildControls that the server controls call to create the appropriate output. Alternative adapters are available, for example the CSS Friendly Control Adapters that provide more flexibility for customizing the rendered HTML. Developers can also create their own adapters to provide custom output from the built-in controls, and from their own custom controls.

Implementation of the Service Agent and Proxy Patterns

The Proxy and Broker patterns provide a natural technique for connecting to and using remote services without forcing the use of O/S or application-specific protocols such as DCOM. In particular, they are ideal for use with Web Services. In Visual Studio, developers add a Web Reference to a project, which automatically collects the web service description (including a WSDL contract file). This lets the code generate a suitable proxy class that exposes the methods of the remote service to code in the application.
Code in the application can then use the remote service by creating an instance of the proxy class and calling the exposed methods defined in the contract. This is the code used in the sample application to call the CustomerName method of the DemoService service:
protected void btn_WSProxy_Click(object sender, EventArgs e)
// display name of specified customer using the Web Service 
{
  try
  {
    // get details from Web Service
    // use 'using' construct to ensure disposal after use
    using (LocalDemoService.Service svc = new LocalDemoService.Service())
    {
      Label1.Text += "Customer name from Web Service: " 
                  + svc.CustomerName(txtID_WSProxy.Text);
    }
  }
  catch (Exception ex)
  {
    Label1.Text += "PAGE ERROR: " + ex.Message;
  }
  Label1.Text += "<p />";
}
One issue with using a Web Service is the difficulty in raising exceptions that the client can handle. The usual approach is to return a specific value that indicates the occurrence of an exception or failure. Therefore, one useful feature that a Service Agent, which wraps the Web Reference to add extra functionality, can offer is detecting exceptions by examining the returned value and raising a local exception to the calling code.
The following code, from the ServiceAgent.cs class in the sample application, contains a constructor that instantiates the local proxy for the service and stores a reference to it. Then the GetCustomerName method can call the CustomerName method of the Web Service and examine the returned value. If it starts with the text "ERROR:" the code raises an exception that the calling routine can handle.
The GetCustomerName method also performs additional processing on the value submitted to it. The Web Service only matches on a complete customer ID (five characters in the example), and does not automatically support partial matches. The GetCustomerName method in the Service Agent checks for partial customer ID values and adds the wildcard character so that the service will return a match on this partial value:
// wraps the Web Reference and calls to Web Service
// to perform auxiliary processing
public class ServiceAgent
{
  LocalDemoService.Service svc = null;

  public ServiceAgent()
  {
    // create instance of remote Web service
    try
    {
      svc = new LocalDemoService.Service();
    }
    catch (Exception ex)
    {
      throw new Exception("Cannot create instance of remote service", ex); 
    }
  }

  public String GetCustomerName(String custID)
  {
    // add '*' to customer ID if required
    if (custID.Length < 5)
    {
      custID = String.Concat(custID, "*");
    }
    // call Web Service and raise a local exception
    // if an error occurs (i.e. when the returned
    // value string starts with "ERROR:")
    String custName = svc.CustomerName(custID);
    if (custName.Substring(0,6) == "ERROR:")
    {
      throw new Exception("Cannot retrieve customer name - " + custName);       
    }
    return custName;
  }
}
To use this simple example of a Service Agent, code in the Default.aspx page of the sample application instantiates the Service Agent class and calls the GetCustomerName method. It also traps any exception that the Service Agent might generate, displaying the message from the InnerException generated by the agent.
protected void btn_WSAgent_Click(object sender, EventArgs e)
// display name of specified customer using the Service Agent
// extra processing in Agent allows for match on partial ID
{
  try
  {
    // get details from Service Agent
    ServiceAgent agent = new ServiceAgent();
    Label1.Text += "Customer name from Service Agent: " 
                + agent.GetCustomerName(txtID_WSAgent.Text);
  }
  catch (Exception ex)
  {
    Label1.Text += "PAGE ERROR: " + ex.Message + "<br />";
    if (ex.InnerException != null)
    {
      Label1.Text += "INNER EXCEPTION: " + ex.InnerException.Message;
    }
  }
  Label1.Text += "<p />";
}

Implementation of the Repository Pattern

A data repository that implements the Repository pattern can provide dependency-free access to data of any type. For example, developers might create a class that reads user information from Active Directory, and exposes it as a series of User objects - each having properties such as Alias, EmailAddress, and PhoneNumber. The repository may also provide features to iterate over the contents, find individual users, and manipulate the contents.
Third-party tools are available to help developers build repositories, such as the CodeSmith tools library (seehttp://www.codesmithtools.com/). Visual Studio includes the tools to generate a typed DataSet that can expose values as properties, rather than as data rows, and this can form the basis for building a repository.
As a simple example, the sample application uses a typed DataSet (CustomerRepository.xsd in the App_Code folder), which is populated from the Customers table in the Northwind database. The DataSet Designer in Visual Studio automatically implements the Fill and GetData methods within the class, and exposes objects for each customer (CustomersRow) and for the whole set of customers (CustomersDataTable).
The class CustomerRepositoryModel.cs in the App_Code folder exposes data from the typed DataSet, such as the GetCustomerList method that returns a populated CustomersDataTable instance, and the GetCustomerName method that takes a customer ID and returns that customer's name as a String:
public class CustomerRepositoryModel
{

  public CustomerRepository.CustomersDataTable GetCustomerList()
  {
    // get details from CustomerRepository typed DataSet
    try
    {
      CustomersTableAdapter adapter = new CustomersTableAdapter();
      return adapter.GetData();
    }
    catch (Exception ex)
    {
      throw new Exception("ERROR: Cannot access typed DataSet", ex);
    }
  }

  public String GetCustomerName(String custID)
  {
    // get details from CustomerRepository typed DataSet
    try
    {
      if (custID.Length < 5)
      {
        custID = String.Concat(custID, "*");
      }
      CustomerRepository.CustomersDataTable customers = GetCustomerList();
      // select row(s) for this customer ID
      CustomerRepository.CustomersRow[] rows 
        = (CustomerRepository.CustomersRow[])customers.Select(
                                "CustomerID LIKE '" + custID + "'");
      // return the value of the CompanyName property
      return rows[0].CompanyName;
    }
    catch (Exception ex)
    {
      throw new Exception("ERROR: Cannot access typed DataSet", ex);
    }
  }
}

Implementation of the Singleton Pattern

The sample application uses the Front Controller pattern to allow users to specify the required View using a short and memorable name. The Front Controller, described in detail in a later section, relies on an XML file that contains the mappings between the memorable name and the actual URL for this view. To expose this XML document content to the Front Controller code, the application uses a Singleton instance of the class named TransferUrlList.cs (in the App_Code folder).
This approach provides good performance, because the class is loaded at all times and the Front Controller just has to call a static method to get a reference to the single instance, and call the method that translates the memorable name into a URL.
To implement the Singleton pattern, the class contains a private default constructor (a constructor that takes no parameters), which prevents the compiler from adding a default public constructor. This also prevents any classes or code from calling the constructor to create an instance.
Note that this implementation does not perform locking while it creates the instance. In reality, in this specific scenario, if a second thread should create a second instance it will not affect operation because the content is read-only and is the same for all instances. If you absolutely need to confirm that only one instance can ever exist, you should apply locks while checking for and creating the instance. For more details, see Implementing the Singleton Pattern in C# and Data & Object Factory Singleton Pattern
The TransferUrlList class also contains a static method that returns the single instance, creating and populating it from the XML file if there is no current instance. The class uses static local variables to store a reference to the instance, and - in this example - to hold a StringDictionary containing the list of URLs loaded from the XML file:
// Singleton class to expose a list of URLs for
// Front Controller to use to transfer to when 
// special strings occur in requested URL
public class TransferUrlList
{
  private static TransferUrlList instance = null;
  private static StringDictionary urls;

  private TransferUrlList()
  // prevent code using the default constructor by making it private
  { }

  public static TransferUrlList GetInstance()
  // public static method to return single instance of class
  {
    // see if instance already created
    if (instance == null)
    {
      // create the instance
      instance = new TransferUrlList();
      urls = new StringDictionary();
      String xmlFilePath = HttpContext.Current.Request.MapPath(
                                        @"~/xmldata/TransferURLs.xml");
      // read list of transfer URLs from XML file
      try
      {
        using (XmlReader reader = XmlReader.Create(xmlFilePath))
        {
          while (reader.Read())
          {
            if (reader.LocalName == "item")
            {
              // populate StringDictionary
              urls.Add(reader.GetAttribute("name"), reader.GetAttribute("url"));
            }
          }
        }
      }
      catch (Exception ex)
      {
        throw new Exception("Cannot load URL transfer list", ex);
      }
    }
    return instance;
  }
  ...
}
A StringDictionary provides good performance, as the method that searches for a matching name and URL in the list can use the ContainsKey method, and then access the matching value using an indexer. If there is no match, the code returns the original value without translating it. This listing shows the GetTransferUrl method that performs the URL translation:
public String GetTransferUrl(String urlPathName)
// public method to return URL for a specified name
// returns original URL if not found
{
  if (urls.ContainsKey(urlPathName))
  {
    return urls[urlPathName];
  }
  else
  {
    return urlPathName;
  }
}
To use the TransferUrlList Singleton class, code in the Front Controller just has to get a reference to the instance, and then call the GetTransferUrl method with the URL to translate as the value of the single parameter:
...
// get Singleton list of transfer URLs 
TransferUrlList urlList = TransferUrlList.GetInstance();
// see if target value matches a transfer URL
// by querying the list of transfer URLs
// method returns the original value if no match 
String transferTo = urlList.GetTransferUrl(reqTarget);
...

ASP.NET Patterns every developer should know


Introduction

For the past year or so, I've been involved in documentation of frameworks that help developers to write better code, and to create applications that are more efficient and easier to test, debug, maintain, and extend. During that time, it has been interesting to see the continuing development of best practice techniques and tools at one of the leading software companies in our industry. Most of the work was outside my usual sphere of ASP.NET and Web development, concentrating mainly on Windows Forms applications built using .NET 2.0. This is an area where the standard design patterns that have evolved over many years are increasingly being refined and put into practice.
However, I regularly found myself wondering just how many of these patterns are equally applicable and advantageous within ASP.NET applications, where we now have the ability to write "real code" in .NET languages such as Visual Basic .NET and C# - rather than the awkward mix of script and COM components upon which classic ASP depended. Surely, out of the 250+ patterns listed on sites such as the PatternShare Community, some must be useful in ASP.NET applications. Yet a search of the Web revealed that - while there is plenty of material out there on design patterns in general, and their use in executable and Windows Forms applications - there is little that concentrates directly on the use of standard design patterns within ASP.NET.
One very useful document that is available is "Enterprise Solution Patterns Using Microsoft .NET". This discusses what design patterns are, how they are documented, and their usage in .NET Enterprise applications. It does not aim solely at ASP.NET, but has plenty of ASP.NET coverage.

About Design Patterns

Because there is so much general material available on the aims and the documentation of design patterns for executable applications, I will restrict this discussion to a few basic points before moving on to look at the patterns I find most useful in ASP.NET. The References section at the end of Part 3 of this series of articles contains links to many useful resources and Web sites related to design patterns in general.
While many people (myself included) find the term "design patterns" just a little scary - due not least to the way that they are usually described and documented - most developers use informal patterns every day when writing code. Constructs such as try...catch, using, and switch (Select Case) statements all follow standard patterns that developers have learned over time. In fact, patterns can be:
  • Informal Design Patterns - such as the use of standard code constructs, best practice, well structured code, common sense, the accepted approach, and evolution over time
  • Formal Design Patterns - documented with sections such as "Context", "Problem", "Solution", and a UML diagram
Formal patterns usually have specific aims and solve specific issues, whereas informal patterns tend to provide guidance that is more general. Formal patterns usually have specific aims and solve specific issues, whereas informal patterns tend to provide guidance that is more general. Brad Appleton, author of the book "Software Configuration Management Patterns: Effective Teamwork, Practical Integration", describes design patterns, pattern languages, and the need for them in software engineering and development, like this:
"Fundamental to any science or engineering discipline is a common vocabulary for expressing its concepts, and a language for relating them together."
"... a body of literature to help software developers resolve recurring problems encountered throughout all of software development."
"... a shared language for communicating insight and experience about these problems and their solutions."
"A pattern is a named nugget of insight that conveys the essence of a proven solution to a recurring problem within a certain context amidst competing concerns."
The following sections of this article and the following two articles aim to demonstrate how you can use some of the common formal patterns (some with minor adaptations to suit ASP.NET requirements) in your Web applications to achieve the aims set out so succinctly by the Hillside Group. You can download the reasonably simple example application and open it in Visual Studio 2005, or install it to run under Internet Information Services (IIS). The download file includes a ~readme.txt file that describes the setup requirements.

Basic Design Patterns and Groups

Design patterns fall into groups, based on the type and aims of the pattern. For example, some patterns provide presentation logic for displaying specific views that make up the user interface. Others control the way that the application behaves as the user interacts with it. There are also groups of patterns that specify techniques for persisting data, define best practices for data access, and indicate optimum approaches for creating instances of objects that the application uses. The following list shows some of the most common design patterns within these groups:
  • Presentation Logic
    • Model-View-Controller (MVC)
    • Model-View-Presenter (MVP)
    • Use Case Controller
  • Host or Behavioral
    • Command
    • Publish-Subscribe / Observer
    • Plug-in / Module / Intercepting Filter
  • Structural
    • Service Agent / Proxy / Broker
    • Provider / Adapter
  • Creational
    • Factory / Builder / Injection
    • Singleton
  • Persistence
    • Repository
The remaining sections of this and the two following articles discuss the patterns that are most suitable for use in ASP.NET, or which ASP.NET implements automatically and allows you to extend to adapt the behavior to suit your own requirements. See the index at the start of each article for a list of the patterns described.

The Model-View-Controller and Model-View-Presenter Patterns

The Model-View-Controller (MVC) and Model-View-Presenter (MVP) Patterns improve reusability of business logic by separating the three components required to generate and manage a specific user interface (such as a single Web page). The Model contains the data that the View (the Web page) will display and allow the user to manipulate. The Controller or Presenter links the Model and the View, and manages all interaction and processing of the data in the Model (see Figure 1).
Figure 1 - the MVC and MVP Patterns
Figure 1 - The Model-View-Controller and Model-View-Presenter Patterns
In the MVC pattern, user interaction with the View raises events in the Controller, which updates the Model. The Model then raises events to update the View. However, this introduces a dependency between the Model and the View. To avoid this, the MVP pattern uses a Presenter that both updates the Model and receives update events from it, using these updates to update the View. The MVP pattern improves testability, as all the logic and processing occurs within the Presenter, but it does add some complexity to the implementation because updates must pass from the Presenter to the View.

The Provider and Adapter Patterns

The Provider and Adapter patterns allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the other. In more practical terms, these patterns provide separation between components that allows behavioral changes to occur without prior knowledge of requirements. The application and any data sources it uses, outputs it generates, or classes it must interact with, can be created independently yet still work together (see Figure 2).
Figure 2 - The Provider and Adapter Patterns
Figure 2 - The Provider and Adapter Patterns
The Provider pattern separates the data processing objects, and the application, from the source data. It allows the code in the application to be independent of the type of data source and the format of the data. A Provider component or service exposes standard methods that the application can call to read and write data. Internally, it converts these calls to the equivalents that match the data source. This means that the application can work with any source data type (such as any kind of database, XML document, disk file, or data repository) for which a suitable provider is available.
The Adapter pattern has the same advantages, and works in a similar way. Often, the target of an Adapter is some kind of output. For example, a printer driver is an example of an Adapter. ASP.NET itself, and other frameworks such as Enterprise Library, make widespread use of the Provider and Adapter patterns.

The Service Agent, Proxy, and Broker Patterns

Various patterns exist that remove dependencies between a client and a service by using intermediate brokers. There are many different implementations of the basic pattern, some of which use an extra service-agent logic component to connect the client with the local proxy or gateway interface (see Figure 3).
Figure 3 - The Service Agent, Proxy, and Broker Patterns
Figure 3 - The Service Agent, Proxy, and Broker Patterns
The aim of all these patterns is to allow remote connection to, and use of, a service without the client having to know how the service works. The service exposes a Contract that defines its interface, such as the Web Service Description Language (WSDL) document for a Web Service. A client-side proxy or gateway interface uses the Contract to create a suitably formatted request, and passes this to the service interface. The service sends the formatted response back through its gateway interface to the client proxy, which exposes it to the client. In effect, the client just calls the service methods on the client proxy, which returns the results just as if the service itself was a local component.
In the Service Agent pattern, an extra component on the client can perform additional processing and logic operations to further separate the client from the remote service. For example, the Service Agent may perform service address lookup, manipulate or format the client data to match the proxy requirements, or carry out any other kind of processing requirements common to different clients that use the service.

The Repository Pattern

The Repository pattern virtualizes storage of entities in a persistent medium, such as a database or as XML. For example, a repository may expose data held in the tables of a database as strongly typed Customer and Order objects rather than data sets or data rows. It effectively hides the storage implementation from the application code, and allows the use of a common set of methods in the application without requiring knowledge of the storage mechanism or format. Often, the repository uses a series of providers to connect to the source data (see Figure 4).
Figure 4 - The Repository Pattern
Figure 4 - The Repository Pattern

The Singleton Pattern

The Singleton pattern defines the creation of a class for which only a single instance can exist. It is useful for exposing read-only data, and static methods that do not rely on instance data. Rather than creating an instance of the class each time, the application obtains a reference to an existing instance using a static method of the class that implements the Singleton pattern.
If this is the first call to the method that returns the instance, the Singleton creates an instance, populates it with any required data, and returns that instance. Subsequent calls to the method simply return this instance. The instance lifetime is that of the application domain - in ASP.NET this is usually the lifetime of the domain Application object.

The maximum amount of memory any single process on Windows can address.


Processes access virtual memory space, not physical memory. Applications never access RAM directly but only through the memory management interface of the processor.
Depending on which version of Windows you are using, and how the program was compiled there is a differnt maximum ammount of addressable memory.
All 32 bit processes on 32bit Windows have a 4GB virtual address space. The upper 2GB is common to all processes and is used by the system. The lower 2GB is private to each process and is inaccessable to all others. Unless the program was compiled as large address aware, in which case it will have 3GB of private address space.
For 32bit processes on 64bit Windows, each process has 2GB private address space, unless compiled large address aware in which case it has 4GB private adress space.
For 64bit processes on 64bit windows each process has 8TB of private address space whilst compiled as large address aware. The 2GB address space limit remains for programs not compiled as large address aware.
This is completely independent of the size of RAM or the pagefile. The system maps physical memory into this virtual address space according to both need and availability.
At any given time the data in virtual memory space might be stored in RAM, on disk, or both. All of this is totally transparent to all applications. Frequently accessed data will be kept in RAM with the remainder left on disk.


Read more: http://wiki.answers.com/Q/What_is_the_maximum_amount_of_memory_any_single_process_on_Windows_can_address_and_is_this_different_from_the_maximum_virtual_memory_for_the_system#ixzz1XYaEzREU

Difference Between Thread and Process


Thread vs Process
Process
In the world of computer programming, a process is an instance or execution of a program. Every process contains a program code and the existing activity. There can be more than one thread that may make up a particular process. Instructions may be executed concurrently. However, it will depend on the operating system being used.
Basically, processes are heavily substantial programs. They consume considerable amounts of memory. Therefore, they are greatly dependent on the resources available for execution. Having said all of these, a process is known to be a “heavyweight process”.
Every process occurs at a different memory location. Therefore, if there are more processes present, the switching between each process is heavily expensive as it will take time from each memory allocation to switch to another allocation. Each process has its own address space which may gobble substantial amounts of supply.
A process is independent of other processes. So, when a parent process is modified it won’t necessarily affect other processes. Because of this behavior, processes require inter-process communication so they can communicate with their siblings.
Furthermore, processes, due to their much more complex nature, are not created with ease. This may require some duplication of processes, typically parent process, to achieve construction.
Thread
Even with minimal system resources, threads are able to be executed simultaneously to attain a specified task. The reason is the fact that a thread is only an execution sequence. It is merely within a process and that is why it is also referred to as a “lightweight process”.
It is considered as the smallest part of a program as it is an independent sequential path of execution within a program. The context switching between threads requires minimal amounts of resource unlike processes. Threads, in essence, share address spaces and they are also easily created.
It should also be mentioned that changes made into the main thread may have an effect on the behavior of the other threads within the same process. Apparently, communication between threads in the same process is direct and seamless.
Summary:
1. A process can contain more than one thread.
2. A process is considered as “heavyweight” while a thread is deemed as “lightweight”.
3. Processes are heavily dependent on system resources available while threads require minimal amounts of resource.
4. Modifying a main thread may affect subsequent threads while changes on a parent process will not necessarily affect child processes.
5. Threads within a process communicate directly while processes do not communicate so easily.
6. Threads are easy to create while processes are not that straightforward.
Ref: http://www.differencebetween.net/miscellaneous/difference-between-thread-and-process/