Search This Blog

Saturday, August 28, 2010

Using & Dispose

Using Statement : Provides a convenient syntax that ensures the correct use of IDisposable objects.
IDisposable Interface : The primary use of this interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams. Use the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed.
When you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

Classes with finalizers require a minimum of two garbage collection cycles to be reclaimed. This prolongs the use of memory and can contribute to memory pressure. When the garbage collector encounters an unused object that requires finalization, it moves it to the "ready-to-be-finalized" list. Cleanup of the object's memory is deferred until after the single specialized finalizer thread can execute the registered finalizer method on the object. After the finalizer runs, the object is removed from the queue and literally dies a second death. At that point, it is collected along with any other objects. Use a finalizer only on objects that hold unmanaged resources across client calls.

Thursday, August 26, 2010

Provider Model in ASP.NET

The ASP.NET 1.x session state model is based on the mode attribute, which is a closed enumerated type—the SessionStateMode enum. To support a new mode (for example, the Oracle table), you need to extend the enum type and modify the code of the session state module. These changes must be repeated each time you need a new extension.

 
ASP.NET provider model is an evolution of the ASP.NET 1.x session state managers inspired by the Adapter design pattern.
A provider is a software module that provides a uniform interface between a service and a data source. Providers abstract physical storage media, in much the same way that device drivers abstract physical hardware devices.

 
Two key aspects differentiate the ASP.NET 1.x session state model from the ASP.NET 2.0 provider model:
  • First is that ASP.NET 2.0 model is based on a richer and more flexible extensibility mechanism.
  • Secondly, it makes use of base classes instead of interfaces.

 
ASP.NET 2.0's Adapter design pattern offers a better and more flexible code design. An Adapter class implements an interface known to its clients and provides access to an instance of a class not known to its clients. An Adapter object provides an interface's functionality without having to assume which class is being used to implement that interface. The only variation to the Adapter pattern is that a base class is used instead of an interface.

 
In ASP.NET 2.0, you use the provider model to achieve several tasks, the most important of which are:
  • The implementation of a read/write mechanism to persist the user profile
  • The creation of a user-defined repository of user credentials that supports most common operations, such as verifying the existence of a user, adding and deleting users, and so forth
  • The creation of a user-defined repository for user roles
  • The definition of the site map
  • The introduction of newer types of data storage for the session state

 
Provider Model Implementation
The implementation of the provider model consists of two distinct elements: the configuration layer and the storage layer. The configuration layer provides information for identifying and instantiating the physical provider object that manages the stored data. The storage layer is the physical entity that stores and manages the data. Depending on the feature, it can be Active Directory, an Oracle or SQL Server table, or an XML file.

 
The configuration layer provides a strongly typed model to get and set property values for the user profile object. The user profile object is represented with a collection of typed properties expressed in the web.config. The HTTP runtime parses the information above and creates a class. The class is compiled on the fly and added to the application's AppDomain. An instance of the class is also exposed through the Profile property on the HttpContext class. The user profile object is filled with stored data when the request starts, and any modified values are restored upon exit. Reading and writing are operations the user profile providers perform.

 
ASP.NET 2.0 comes with two user profile providers. Each uses a different data engine. The default provider uses an Access database; the other provider is for SQL Server. You also can write custom providers. The provider writes data into the database of choice and is responsible for the final schema of the data. A user profile provider must be able to either serialize the type (by using XML serialization and binary object serialization, for example) or know how to extract significant information from it.

 
Provider Model in ASP.NET 2.0:
At its core, the ASP.NET 2.0 provider infrastructure allows customers to extend some of the out-of-the-box system functionality and change the underlying implementation while keeping the top-level interface intact. Providers are relatively simple components with as few methods and properties as possible.

 
Other providers (for example, the membership provider) perform different tasks, such as creating a new user, deleting existing users, or validating a given user. However, no matter the operations performed, the provider supplies a common and immutable programming interface for tasks that helper classes perform—tasks that the client doesn't know in advance and that can work with any sort of storage medium.

 
THe provider model in ASP.NET 2.0 has two key benefits:
  • It makes the whole infrastructure much more resilient and flexible.
  • It enables developers to port ASP.NET 2.0 into portions of their existing infrastructures that were developed for version 1.x easily. In this sense, it promotes reusability and smoothes migration.

 
All providers have certain characteristics in common. All, for example, initialize themselves when the ASP.NET run-time calls the Initialize method that they inherit from ProviderBase, and all must be thread-safe.

 
Providers are loaded when the application using them first accesses a feature of the corresponding service, and they're instanced just once per application (that is, per application domain).

Monday, August 16, 2010

Generics

Most algorithms are encapsulated in a type, and the CLR allows the creation of generic reference types as well as generic value types, but it does not allow the creation of generic enumerated types. CLR allows the creation of generic interfaces and generic delegates.

When defining a generic type or method, any variables it specifies for types (such as T) are called type parameters. Example is the List class definition, indexer method.

Source code protection - The developer using a generic algorithm doesn’t need to have access to the algorithm’s source code. With C++ templates or Java’s generics, however, the algorithm’s source code must be available to the developer who is using the algorithm.

Type safety - When a generic algorithm is used with a specific type, the compiler and the CLR understand this and ensure that only objects compatible with the specified data type are used with the algorithm. Attempting to use an object of an incompatible type will result in either a compiler error or a runtime exception being thrown.

Cleaner code - Since the compiler enforces type safety, fewer casts are required in your source code, meaning that your code is easier to write and maintain.

Better performance - Before generics, the way to define a generalized algorithm was to define all of its members to work with the Object data type. If you wanted to use the algorithm with value type instances, the CLR had to box the value type instance prior to calling the members of the algorithm. Since a generic algorithm can now be created to work with a specific value type, the instances of the value type can be passed by value, and the CLR no longer has to do any boxing. In addition, since casts are not necessary the CLR doesn’t have to check the type safety of the attempted cast, and this results in faster code too.

using the generic List algorithm with the Int32 type is much. faster than using the non-generic ArrayList algorithm with Int32. List algorithm required 0 garbage collections. Generic List algorithm is of any benefit here. Using reference types you do need to realize that the CLR generates native code for each method the first time the method is called for a particular data type.

CLR creates an internal data structure for each and every type in use by an application. These data structures are called type objects. A type with generic type parameters is called an open type, and the CLR does not allow any instance of an open type to be constructed (similar to how the CLR prevents an instance of an interface type from being constructed)

When a method that uses generic type parameters is JIT-compiled, the CLR takes the method’s IL, substitutes the specified type arguments, and then creates native code that is specific to that method operating on the specified data types. This is exactly what you want and is one of the main features of generics. However, there is a downside to this: the CLR keeps

generating native code for every method/type combination. This is referred to as code explosion. CLR has some optimizations - the CLR will compile the code for this method/type combination just once.

The following are the key differences between C# Generics and C++ templates:
•C# generics do not provide the same amount of flexibility as C++ templates. For example, it is not possible to call arithmetic operators in a C# generic class, although it is possible to call user defined operators.
•C# does not allow non-type template parameters, such as template C {}.
•C# does not support explicit specialization; that is, a custom implementation of a template for a specific type.
•C# does not support partial specialization: a custom implementation for a subset of the type arguments.
•C# does not allow the type parameter to be used as the base class for the generic type.
•C# does not allow type parameters to have default types.
•In C#, a generic type parameter cannot itself be a generic, although constructed types can be used as generics. C++ does allow template parameters.
•C++ allows code that might not be valid for all type parameters in the template, which is then checked for the specific type used as the type parameter. C# requires code in a class to be written in such a way that it will work with any type that satisfies the constraints.

You can think of templates as a fancy-pants search-and-replace mechanism. When you say DoIt in a template, the compiler conceptually searches out all uses of “T”, replaces them with “string”, and then compiles the resulting source code. Overload resolution proceeds with the substituted type arguments known, and the generated code then reflects the results of that overload resolution.

That’s not how generic types work; generic types are, well, generic. We do the overload resolution once and bake in the result. We do not change it at runtime when someone, possibly in an entirely different assembly, uses string as a type argument to the method. The IL we’ve generated for the generic type already has the method its going to call picked out.

Tuesday, August 10, 2010

Strategy pattern

Strategy pattern (also known as the policy pattern) is a particular software design pattern, whereby algorithms can be selected at runtime. The essential requirement in the programming language is the ability to store a reference to some code in a data structure and retrieve it. This can be achieved by mechanisms such as the native function pointer, the first-class function, classes or class instances in object oriented programming languages, or accessing the language implementation's internal storage of code via reflection. Delegates in C# follow the strategy pattern, where the delegate definition defines the strategy interface and the delegate instance represents the concrete strategy. .NET 3.5 defines the Func<,> delegate which can be used to quickly implement the strategy pattern. You can use this delegate to represent a method that can be passed as a parameter without explicitly declaring a custom delegate. By using anonymous methods, you reduce the coding overhead in instantiating delegates because you do not have to create a separate method.

The UML class diagram for the Strategy pattern is the same as the diagram for the Bridge pattern. However, these two design patterns aren't the same in their intent. While the Strategy pattern is meant for behavior, the Bridge pattern is meant for structure.

The coupling between the context and the strategies is tighter than the coupling between the abstraction and the implementation in the Bridge pattern.

Monday, August 02, 2010

Software Development Practices

Behavior driven development (or BDD) is an agile software development technique that encourages collaboration between developers, QA and non-technical or business participants in a software project. BDD focuses on obtaining a clear understanding of desired software behaviour through discussion with stakeholders. It extends TDD by writing test cases in a natural language that non-programmers can read.

Lean programming is a concept that emphasizes optimizing efficiency and minimizing waste in the development of a computer program. The concept is that efficiencies can be applied and waste managed at all levels: each individual, every department, interdepartmental operations, the organization as a whole, and the relationships of the organization with customers and suppliers. Lean Programming teaches you to eliminate wasted effort in development projects by favoring "pull" design over "push" design. This means infrastructure concerns like persistence should only be designed and built to satisfy the needs of business requirements (pulled on demand) instead of building the data access layer code that you think the application will need later (pushed).

Continuous integration (CI) implements continuous processes of applying quality control - small pieces of effort, applied frequently. Continuous integration aims to improve the quality of software, and to reduce the time taken to deliver it, by replacing the traditional practice of applying quality control after completing all development.

Continuous design is a software development practice of creating and modifying the design of a system as it is developed, rather than specifying the system completely before development starts, (as in the waterfall model) or in bursts at the beginning of each iteration (as in the iterative model). Also called "evolutionary design" or "incremental design", continuous design was popularized by extreme programming. Continuous design also uses test driven development and refactoring. It is similar to, and generally used with, continuous integration.

Convention over configuration is a design philosophy and technique that seeks to apply defaults that can be implied from the structure of the code instead of requiring explicit code. The idea is to simplify development by allowing the developer to worry only about the unconventional parts of the application and architecture.

Persistence Patterns

A domain model is an object model of the domain that incorporates both behavior and data. A Domain Model creates a web of interconnected objects, where each object represents some meaningful individual, whether as large as a corporation or as small as a single line on an order form. The business objects in the middle tier and the user interface or service layer are the application, and the database is a means to reliably persist the state of the business objects between sessions.

An Active Record approach puts persistence methods directly onto the entity object. In this case, the Address class would probably have methods like Save, Update, and Delete, as well as a static Load method that queries the database for an Address object. Active Record is best for systems with simpler domain logic, CRUD-intensive applications.


The Data Mapper pattern strips most of the responsibility of persistence from the entity objects in favor of classes external to the entities. With a Data Mapper pattern, you access, query, and save entity objects with some kind of repository.

Repository pattern mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects. Repository pattern put a façade over your persistence system so that you can shield the rest of your application code from having to know how persistence works.

In persistence tooling, preventing duplicate logical references is the job of the Identity Map pattern. An Identity Map ensures that each object gets loaded only once by keeping every loaded object in a map and looks up objects using the map when referring to them.

According to Martin Fowler, the Unit of Work pattern "maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.”. Your Unit of Work class will have methods to mark entities as changed, new, or deleted. The Unit of Work will also have methods to commit or roll back all of the changes. One of the best ways to use the Unit of Work pattern is to allow disparate classes and services to take part in a single logical transaction.