Search This Blog

Showing posts with label Advanced .Net Programming. Show all posts
Showing posts with label Advanced .Net Programming. Show all posts

Saturday, April 12, 2014

The Concept Of Generics In .Net With C# And VB.Net

The Detailed Description Of Generics In .Net

Generic Type : A generic type is a type that uses generic type parameters. For example, the type LinkedList, defined as:

C#
public class LinkedList
{...}
VB.Net
Public Class LinkedList(Of K, T)
    ...
End Class

Generic Type Parameter : A generic type parameter is the place holder a generic type uses. For example, the generic type LinkedList, defined as:

C#
public class LinkedList
{...}
VB.Net
Public Class LinkedList(Of K, T)
    ...
End Class

Some more description about generics:
Constructed Type : A constructed type is any generic type that has at least one type argument.

Open Constructed Type : A open constructed type is any generic type that which contains at least one type parameter used as a type argument

Closed Constructed Type : A closed constructed type is a generic type that which contains no type parameters as type arguments.

Initialize a Generic Type Parameter

When declaring a generic type, you need to specify the types that will replace the type parameters in the declaration. These are known as type arguments to the generic type. Type arguments are simply types. 
You need to specify which types to use for K, the list's key, and T, the data items stored in the list. You specify the types in two places: when declaring the list's variable and when instantiating it:
C#
LinkedList list = new LinkedList();
list.AddHead(123,"ABC");
VB.Net
Dim list As New LinkedList(Of Integer, String)
list.AddHead(123, "ABC")

Constraints in Generics:

Constraints allow additional contextual information to be added to the type parameters of generic types. The constraints limit the range of types that are allowed to be used as type arguments, but at the same time, they add information about those type parameters. Constraints ensure that the type arguments specified by the client code are compatible with the generic type parameters the generic type itself uses. Meaning, constraints prevent the client from specifying types as type arguments that do not offer the methods, properties, or members of the generic type parameters that the generic type relies upon.
After applying a constraint you get IntelliSense reflecting the constraints when using the generic type parameter, such as suggesting methods or members from the base type.
Derivation constraint indicates to the compiler that the generic type parameters derives from a base type such an interface or a particular base class. 
You can provide constraints for every generic type parameter that your class declares. You can have a base class constraint, meaning, stipulating that the generic type parameter derives from a particular base class:
However, you can only use one base class at most in a constraint because neither C#, Visual Basic or managed C++ support multiple inheritance of implementation. Obviously, the base class you constrain to cannot be a sealed class, and the compiler enforces that. In addition, you cannot constrain System.Delegate or System.Array as a base class.
You can constrain both a base class and one or more interfaces, but the base class must appear first in the derivation constraint list.You can combine the default constructor constraint with derivation constraints, provided the default constructor constraint appears last in the constraint list.

Auto-Generate Wrapper Classes for Stored Procedures Using the AutoSproc Tool

Auto-Generate Wrapper Classes for Stored Procedures Using the AutoSproc Tool


The essence of the idea behind AutoSproc is for the developer to define methods on an interface that correspond to the stored procedures that exist in a database. These interface methods are abstract at the time of program compilation, but receive an implementation at runtime from a code generation assembly the client program references, named AutoSproc.dll. At the heart of this assembly there is a publicly callable static (shared) method called SprocFactory.CreateInstance(). A key parameter that must be passed when making a call to this method is type information for an interface. The primary function of this method is to dynamically fabricate a class that implements the designated interface and to return an instance of that class to the caller. As an example, consider the following stored procedure definition:



CREATE PROCEDURE upAddTwoNumbers
@a int,
@b int,
@result int output
AS
select @result = @a+@b

Given this definition, the interface would be defined in Visual Basic .NET as follows:
Public Interface IMath
    Inherits ISprocBase
    Function upAddTwoNumbers(ByVal a As Integer, _
      ByVal b As Integer, _
      ByRef result As Integer) As Integer
End Interface

ISprocBase adds three properties to your deriving interface:
Public Interface ISprocBase
   Property Connection() as IDbConnection
   Property AutoClose () as Boolean
   Property Transaction () as IDbTransaction
End Interface
The Connection property is the means by which one passes the database connection to the code generated class at runtime.
ISprocBase.AutoClose Property
The AutoClose property on the interface can be used to toggle this feature on and off dynamically at runtime during the lifetime of the application.

ISprocBase.Transaction Property

It is often the case that a local transaction is used to protect multiple operations carried out against a database. To facilitate this, a transaction property is defined on the base interface. Its usage is fairly straightforward: Use the database connection to begin the transaction (IDbConnection.BeginTransaction()), feed the transaction to the transaction property on the code generated class, make one or more transacted stored procedure calls then either commit / abort or rollback the transaction (IDbTransaction.Commit()/ Abort() / Rollback()).
It is important to note that if AutoClose is set to true, then the transaction will exhibit potentially undesirable auto commit behavior because closing the database connection implicitly attempts to commit the transaction. It is recommended that if the Transaction property is being used then AutoClose is set to false.

SprocFactory.CreateInstance() Method Overloads

There are four overloaded SprocFactory.CreateInstance() methods offered, only one of which is strictly necessary (the second one). The other three are offered as a convenience to the developer for seeding Connection and AutoClose properties at creation time. It should be noted that overloads not providing an AutoClose parameter (the first and third) will configure it to true by default.

Public Shared Function CreateInstance (ByVal itf as Type, _
ByVal prov as DBProvider) _
as Object

2.
Public Shared Function CreateInstance (ByVal itf as Type, _
ByVal prov as DBProvider, _
                  autoClose as Boolean) as Object 
3
Public Shared Function CreateInstance (ByVal itf as Type, _
ByVal conn as IDbConnection) _
as Object
4.
Public Shared Function CreateInstance (ByVal itf as Type, _
ByVal conn as IDbConnection, _
                  ByVal autoClose as Boolean) _
                  as Object
The DBProvider enumeration is the means by which the user configures the code generation layer to emit an implementation. For this release, only SQL Server and OleDb managed providers are available. If the user elects to use the third or fourth CreateInstance() method then the database provider type is inferred by the code generation layer from the IDbConnection parameter, thus making a DBProvider enumeration parameter unnecessary.

Monday, March 10, 2014

Reflection in the .NET Framework



.Net Reflection Concepts In Depth

The classes in the System.Reflection namespace, together with System.Type, enable you to obtain information about loaded assemblies and the types defined within them, such as classes, interfaces, and value types. You can also use reflection to create type instances at run time, and to invoke and access them.

The common language runtime loader manages application domains, which constitute defined boundaries around objects that have the same application scope. This management includes loading each assembly into the appropriate application domain and controlling the memory layout of the type hierarchy within each assembly.
Assemblies contain modules, modules contain types, and types contain members. Reflection provides objects that encapsulate assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object. You can then invoke the type's methods or access its fields and properties. Typical uses of reflection include the following:
  • Use Assembly to define and load assemblies, load modules that are listed in the assembly manifest, and locate a type from this assembly and create an instance of it.
  • Use Module to discover information such as the assembly that contains the module and the classes in the module. You can also get all global methods or other specific, nonglobal methods defined on the module.
  • Use ConstructorInfo to discover information such as the name, parameters, access modifiers (such as public or private), and implementation details (such as abstract orvirtual) of a constructor. Use the GetConstructors or GetConstructor method of a Type to invoke a specific constructor.
  • Use MethodInfo to discover information such as the name, return type, parameters, access modifiers (such as public or private), and implementation details (such asabstract or virtual) of a method. Use the GetMethods or GetMethod method of a Type to invoke a specific method.
  • Use FieldInfo to discover information such as the name, access modifiers (such as public or private) and implementation details (such as static) of a field, and to get or set field values.
  • Use EventInfo to discover information such as the name, event-handler data type, custom attributes, declaring type, and reflected type of an event, and to add or remove event handlers.
  • Use PropertyInfo to discover information such as the name, data type, declaring type, reflected type, and read-only or writable status of a property, and to get or set property values.
  • Use ParameterInfo to discover information such as a parameter's name, data type, whether a parameter is an input or output parameter, and the position of the parameter in a method signature.
  • Use CustomAttributeData to discover information about custom attributes when you are working in the reflection-only context of an application domain.CustomAttributeData allows you to examine attributes without creating instances of them.
The classes of the System.Reflection.Emit namespace provide a specialized form of reflection that enables you to build types at run time.
Reflection can also be used to create applications called type browsers, which enable users to select types and then view the information about those types.
There are other uses for reflection. Compilers for languages such as JScript use reflection to construct symbol tables. The classes in the System.Runtime.Serialization namespace use reflection to access data and to determine which fields to persist. The classes in the System.Runtime.Remoting namespace use reflection indirectly through 

Runtime Types in Reflection

Reflection provides classes, such as Type and MethodInfo, to represent types, members, parameters, and other code entities. However, when you use reflection you don't work directly with these classes, most of which are abstract (MustInherit in Visual Basic). Instead, you work with types provided by the common language runtime (CLR).
For example, when you use the C# typeof operator (GetType in Visual Basic) to obtain a Type object, the object is really a RuntimeType. RuntimeType derives from Type, and provides implementations of all the abstract methods.
These runtime classes are internal (Friend in Visual Basic). They are not documented separately from their base classes, because their behavior is described by the base class documentation.