Thursday, November 18, 2010

Partial Class & Partial Method

It is possible to split the definition of a class or a struct, an interface or a method over two or more source files. Each source file contains a section of the type or method definition, and all parts are combined when the application is compiled.

e.g.
File:f1.vb
Public Interface I1
    Sub setMsg()
    Function getMsg() As String
End Interface

File:f2.vb
Partial Public Class C1
Implements I1

End Class

File:f3.vb
Partial Class C1

Partial Private Sub myTestFunc()
End Sub

End Class

File:f4.vb
Partial Public Class C1
Public Sub setMsg() Implements I1.setMsg
------------
-------------
End Sub
End Class

File:f5.vb
Partial Public Class C1

Public Function getMsg() As String Implements I1.getMsg
------------
-------------
End Function
End Class


File:f6.vb
Public Class C1
Private Sub myTestFunc()
------------
-------------
End Sub

End Class

reference:
http://www.4guysfromrolla.com/articles/071509-1.aspx

Tuesday, October 26, 2010

Compress/Decompress byte streams

Imports System.IO
Imports System.IO.Compression

Public NotInheritable Class Compressor
    Private Sub New()
    End Sub

    Public Shared Function Compress(data As Byte()) As Byte()
        Dim output As New MemoryStream()
        Dim gzip As New GZipStream(output, CompressionMode.Compress, True)
        gzip.Write(data, 0, data.Length)
        gzip.Close()
        Return output.ToArray()
    End Function

    Public Shared Function Decompress(data As Byte()) As Byte()
        Dim input As New MemoryStream()
        input.Write(data, 0, data.Length)
        input.Position = 0
        Dim gzip As New GZipStream(input, CompressionMode.Decompress, True)
        Dim output As New MemoryStream()
        Dim buff As Byte() = New Byte(63) {}
        Dim read As Integer = -1
        read = gzip.Read(buff, 0, buff.Length)
        While read > 0
            output.Write(buff, 0, read)
            read = gzip.Read(buff, 0, buff.Length)
        End While
        gzip.Close()
        Return output.ToArray()
    End Function
End Class
 

Thursday, September 16, 2010

Anonymous Types

Anonymous types:  As the name itself clears, creates an object without declaring its data type/class. Since name of the data type/class is not specified --that the type is referred to as an anonymous type.

VB.Net
Person = New With {
    .FirstName = "Ram",
    .MiddleName = "Gopal",
    .LastName = "Verma" }
C#
 var Person = New With {
    FirstName = "Ram",
    MiddleName = "Gopal",
    LastName = "Verma" };
Above example is one of  declaration of anonymous typed object where once a person object is created then this object is used as if object of some of real physical class.

During compilation while the control reached at above code then the following are the steps that are performed internally.
  1. Compiler automatically generates anonymous class.
  2. It anonymously instantiate an object that contains the properties in anonymous type
  3. The instantiated object is assigned to the anonymous type variable "Person" 
 The anonymous type inherits from Object, it holds the properties specified in declaring the object.

So object of anonymous  type are used as of a normal class.

Marker Interface

An interface that consists of no method....... or an interface having nothing in the body is called marker interface. These interfaces can be useful in the scenarios while we need to mark some kind of implementations of derived class objects for different kinds of behavior.

e.g Let C be a class

C1 and C2 inherits C and also C2 implements Imarker interface. 
now suppose the object to be realistic in real world and the objects of class that implements Imarker interface are always intelligent entities.

now let 5 objects of C1 and 3 objects of C2 go for competition and clearly objects of C2 are winner. Then to check which object is winner which is not, instead of checking property of individual we just will check which is object is assignable to reference of Imarker interface. which removes lot of checks in case of complex scenarios.

Comparing instance is type of a class

There are various kinds of ways to check whether a object is instance of given class or not. The following are some of the ways that has been identified to be find this condition

Public Interface MyMarkerInterface
 
End Interface
 
Public Class myTestCls
    Implements MyMarkerInterface
         Private _m As Integer
    Public ReadOnly Property Age() As Integer
        Get
            Return _m
        End Get
    End Property
 
End Class

The above is the class that implements some interface........ So in some case I want to check whether the instance of above class is instance of Interface.


    Private Function isMarkerkedObj1(ByVal o1 As myTestClsAs Boolean
        If TypeOf o1 Is MyMarkerInterface Then
            Return True
        Else
            Return False
        End If
    End Function
 
    Private Function isMarkerkedObj2(ByVal o1 As myTestClsAs Boolean
        If o1.GetType.IsSubclassOf(GetType(MyMarkerInterface)) Then
            Return True
        Else
            Return False
        End If
    End Function
 
    Private Function isMarkerkedObj3(ByVal o1 As myTestClsAs Boolean
        If GetType(MyMarkerInterface).IsAssignableFrom(o1.GetType) Then
            Return True
        Else
            Return False
        End If
    End Function
Now all the above methods are using different methods to compare the type of object to check is this type of particular kind .

e.g. Dim obj1 as new myTestCls
-------------
------------- 
-------------
isMarkerkedObj1(obj1)
isMarkerkedObj2(obj1)
isMarkerkedObj3(obj1)

all the above calls will return true.

Note: The requirement discussed might be confusing but is very useful in many scenarios a the interface used is a marker interface which consists of nothing in the body. So in certain cases we may require to mark some objects for certain behavior then we use this interface.

Wednesday, September 1, 2010

What is a Manifest?

All the metadata needed to specify the assembly's version requirements and security identity. Metadata is needed to define the scope of the assembly and resolve references to resources and classes.

It can be stored in either a PE (Portable Executable) file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a standalone PE (Portable Executable) file that contains only assembly manifest information.

The information contained in the assembly manifest
I. Assembly's identity: The first four items — 1. the assembly name 2. version number 3. culture 4. and strong name information.

1. Assembly name: A text string specifying the assembly's name.
2. Version number: A major and minor version number, and a revision and build number. The common language runtime uses these numbers to enforce version policy.
3. Culture: Information on the culture or language the assembly supports. This information should be used only to designate an assembly as a satellite assembly containing culture- or language-specific information. (An assembly with culture information is automatically assumed to be a satellite assembly.)
4. Strong name information: The public key from the publisher if the assembly has been given a strong name.

II. List of all files in the assembly: A hash of each file contained in the assembly and a file name. Note that all files that make up the assembly must be in the same directory as the file containing the assembly manifest.

III. Type reference information: Information used by the runtime to map a type reference to the file that contains its declaration and implementation. This is used for types that are exported from the assembly.

IV. Information on referenced assemblies: A list of other assemblies that are statically referenced by the assembly. Each reference includes the dependent assembly's name, assembly metadata (version, culture, operating system, and so on), and public key, if the assembly is strong named.

Thursday, May 27, 2010

Private Assemblies

A private assembly is an assembly that is deployed with an application and is available for the exclusive use of that application. That is, other applications do not share the private assembly. Private assemblies are one of the methods that can be used to create isolated applications. For more information, see About Isolated Applications and Side-by-Side Assemblies.

Private assemblies must be designed to work side-by-side with other versions of the assembly on the system. For more information, see Guidelines for Creating Side-by-side Assemblies.

Private assemblies must be accompanied by an assembly manifest. Note that name restrictions apply when packaging a DLL as a private assembly to accommodate the way in which Windows searches for private assemblies. When searching for private assemblies, the recommended method is to include the assembly manifest in the DLL as a resource. In this case, the resource ID must equal 1 and the name of the private assembly may be the same as the name of the DLL. For example, if the name of the DLL is MICROSOFT.WINDOWS.MYSAMPLE.DLL, the value of the name attribute used in the assemblyIdentity element of the manifest may also be Microsoft.Windows.mysample. An alternate method of searching for private assemblies is to provide the assembly manifest in a separate file. In this case, the name of the assembly and its manifest must be different than the name of the DLL. For example, Microsoft.Windows.mysampleAsm, Microsoft.Windows.mysampleAsm.manifest, and Microsoft.Windows.mysample.dll. For more information about how side-by-side searches for private assemblies see Assembly Searching Sequence.

Static Assemblies v/s Dynamic Assemlies Tips

Static Assembly
- Stored on disc in PE files
- contains .NET Framework types (interfaces and classes) as
well as resources for the assembly (bitmaps, JPEG files,
resource files, and so on)

Dynamic Assembly
- Not saved on disc before execution and run directly from memory but can be saved on disc after execution


What else please make comments

Assembly Manifest Definition Tips

-A Data Structure responsible to store inforamtion about assembly i.e. metadata.
-metadata contain various information like: assembly's version, security identity and other metadata needed to define the scope of assembly and resolve references to resources and classes.
- can be stored in a PE file (DLL/EXE) with Microsoft Intermediate Language (MSIL) or in standalone PE file that contains only assembly manifest information.
-contains a collection of data that describes how the elements in the assembly relate to each other

Wednesday, March 24, 2010

Managed Modules- Windows Portable Executable (PE)

The above diagram shows the resulting a managed module. A managed module is a standard Windows portable executable (PE) file that requires the CLR to execute. In the future, other operating systems may use the PE file format as well.

A Managed Module is composed of the following parts:





















Part

Description
PE header This is the standard Windows PE file header, which is similar to the Common Object File Format (COFF) header. The PE header indicates the type of file--GUI, CUI, or DLL—and also has a timestamp indicating when the file was built. For modules that contain only IL code (see below, Intermediate Language Code), the bulk of the information in the PE header is ignored. For modules that contain native CPU code, this header contains
information about the native CPU code.
CLR header This header contains the information (interpreted by the CLR and utilities) that makes this a managed module. It includes the version of the CLR required, some flags, the MethodDef metadata token of the managed module’s entry point method (Main method), and the location/size of the module’s metadata, resources, strong name, some flags, and other less interesting stuff.
Metadata Every managed module contains metadata tables, of which there are 2 main types: those that describe the types and members defined in your source code, and those that describe the types and members referenced by your source code.
Intermediate Language (IL) Code This is the code that was produced by the compiler as it compiled the source
code. IL is later compiled by the CLR into native CPU instructions.

Most compilers of the past produced code targeted to a specific CPU architecture, such as x86, IA64, Alpha, or PowerPC. All CLR-compliant compilers produce intermediate language (IL) code instead. IL code is sometimes referred to as managed code, because its lifetime and execution are managed by the CLR.

Metadata is simply a set of data tables that describe what is defined in the module, such as types and their members. Also it has tables indicating what the managed module references, such as imported types and their members. Metadata is a superset of older technologies such as type libraries and IDL files.

The important thing to note is that CLR metadata is far more complete than its predecessors. And, unlike type libraries and IDL, metadata is always associated with the file that contains the IL code. In fact, the metadata is always embedded in the same EXE/DLL as the code, making it impossible to separate the two. Since the metadata and code are produced by the compiler at the same time and are bound into the resulting managed module, the metadata and the IL code it describes are never out of sync with one another.

Metadata has many uses. Here are some of them:
· Metadata removes the need for header and library files when compiling, because all the information about the referenced types/members is contained in one file along with the IL that implements those type/members. Compilers can read metadata directly from managed modules.

· Visual Studio uses metadata to help you write code. Its IntelliSense feature parses metadata to tell you what methods a type offers and what parameters that method expects.

· The CLR code verification process uses metadata to ensure that your code performs only “safe” operations. Verification is discussed shortly.

· Metadata allows an object’s fields to be serialized into a memory block, remoted to another machine, and then deserialized, recreating the object and its state on the remote machine.

· Metadata allows the garbage collector to track the lifetime of objects. For any object, the garbage collector can determine the type of the object, and from the metadata it knows which fields within that object refer to other objects.


Four of the compilers that Microsoft offers--C#, Visual Basic, JScript, and the IL Assembler--always produce managed modules, which require the CLR to execute. That is, end users must have the CLR installed on their machines in order to execute any managed modules. This situation is similar to the one that end users face with MFC or VB 6 applications:
they must have the MFC or VB DLLs installed in order to run them.


But as CLR works with assemblies[ a logical grouping of one or more managed modules or resource files] not with Modules. An assembly is the smallest unit of reuse, security, and versioning, produced as single file assembly or multi-file assembly depending on compilers/tools choice.

The figure below should help explain what assemblies are about:


A single file [managed modules and resource (or data) files] is passed to tools, producing a single PE file that represents the logical grouping of files. This PE file contains a block of data called the manifest, which is simply another set of metadata tables. These tables describe the assembly: the files that make it up, the publicly exported types implemented by the files in the assembly, and the resource or data files that are associated with it.


Tuesday, March 23, 2010

Date Variable

Many times it require to check whether the date in the particular variable is assigned which can be checked by using

If IsDate(variable of type date) Then .......

Also, in case to verify that valid value is stored in the database while retrieving, to avoid null exception, it can be checked by using datareader as

If dr.isdbnull(column index) Then...
Or
If dr(mydate column Name/Index) Is DBNull.Value Then

Usefull tips:
in VB.net empty date is 1/1/1900
to verify correct date, ensure mydate.year > 1900