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

Monday, May 18, 2009

ListBox Deselect Tip

In ListBox, I've found that we can not deselect a entry once we selected any one of the entry in the list, even selecting no entry area. But I've found one of the solution to fix this issue as :
Let lstBox be the listbox in a form then,

Private Sub lstBox_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lstBox.MouseDown
Try
If Not lstBox.SelectionMode = SelectionMode.None Then
lstBox.SelectedIndex = lstBox.IndexFromPoint(e.X, e.Y)
End If
If (Windows.Forms.Control.ModifierKeys And Keys.Control) <> 0 Then
If lstBox.SelectedIndex = lstBox.IndexFromPoint(e.X, e.Y) Then
LstbIMBoxList.SelectedIndex = -1
End If
End If

Catch ex As Exception
'
End Try
End Sub

This may fix the issue in many situations depending on the requirements.

Tuesday, May 5, 2009

Singleton class

 Public Class MySingletonCls

Private Shared objSingle As MySingletonCls
Private Shared bIsCreated As Boolean

Private Sub New()
'Override the default constructor
End Sub

Public Shared Function CreateInstance() As
MySingletonCls
If bIsCreated = False Then
objSingle = New
MySingletonCls()
bIsCreated = True
Return objSingle
Else
Return objSingle
End If
End Function
End Class

Friday, May 1, 2009

Tip to fetch XML using LINQ

Function FetchXML(ByVal url As Uri) As XElement

Dim x = WebRequest.Create(url)

Using r = x.GetResponse, rs As New StreamReader(r.GetResponseStream)

Return XElement.Parse(rs.ReadToEnd)

End Using

End Function

Call the function with the location of the xml file to get the corresponding XML element, that can be used for needed purpose.

Tip to handle XML based info project

Many times we need to manage the projects that just process specific information. Like if we consider a project that handles information about student(name,rno,course,class). So each student will have this information. To very easy way, if we create an XML file with one of the student. Creating a xml with this info is not very tough job.
Upto this point, half is done. Now we just need to get a class which can carry this information for various purposes and which can be written directly to xml file and also can read data from xml file( easiest way is serialize/deserialize mechanism can be very useful)

Now to get exact class that can be serialized directly to xml can be easily obtained from xsd utility of Visual Studio. just open the Visual Studio Command Prompt, and get the xsd file for your xml file and then convert this file directly to required class file. So the steps that can be needed to get the class are as below:

1. Create xml file say 'MyXml.xml'
2. run xsd MyXml.xml, will result MyXml.xsd
3. run xsd MyXml.xsd /c /l:vb, will result MyXml.vb

[the class can be constructed in various ways by using xsd, for details refer xsd documentation.]

note, in step 2 and 3, if current directory for running the command is same that is containing the MyXml.xml file then use command as such, else specify the full path of the file(s). Also target for the resulting file also can be specified(refer xsd documentation).

now we are with a class for which an object can be easily serialized/deserialized. So create collection of objects to carry all the records, applly any type of manipulations and serialize with XMLSerializer to write it to xml directly without worring about most of the validations as most are handled by serializers.

Thursday, April 30, 2009

Protecting Assembly/DLL from illegal access tips

Sometimes we want to protect the access to the various functions of our assembly, I have identified that if the functions of the assembly made as friend and assembly is also made friend assembly, then the results will be as desired. As

A friend assembly is an assembly that is permitted to access another assembly's Friend types and members.

So Its possible to protect illegal access to our secure functionality.

This is one of the solution that can be helpful in some situation.

The info of Friend Assemblies can found at the link http://msdn.microsoft.com/en-us/library/bb384772.aspx

Wednesday, April 29, 2009

Some Simple LINQ Examples for existing examples

Here are some simple examples to understand better to LINQ

creating an iterator that will give you the letters "a" to "z" as you enumerate it:
Dim letters(0 To 25) As Char
For i As Int32 = 0 To 25
letters(i) = ChrW(&H61 + i)
Next

By Using LINQ
Dim letters = From i In Enumerable.Range(0, 26) _
Select ChrW(&H61 + i)

To read from a stream line-by-line,
search for a substring, and return the first couple of matches.

strLine = myStreamReader.ReadLine
Do While strLine IsNot Nothing
If strLine.Contains(value) Then
count += 1
resultList.Add(strLine)
If count >= 3 Then Exit Do
End If
strLine = myStreamReader.ReadLine
Loop

Unfortunately, StreamReader doesn't have an
iterator that returns each line. Without something that is enumerable,
you can't form the basis of a LINQ query, so you're forced to write
your query imperatively. That's not as bad as it might first sound;

Building the query into the imperative procedural block does work,
although it's kind of on the ugly side.

If you have an extension method named Lines that
returns an IEnumerable with each item a line, then you can create a
query like this:

Dim result = From line In myStreamReader.Lines _
Where line.Contains(value) _
Take 3




Tuesday, April 28, 2009

Tip for Alphablended area of image in list view

In List View, while displaying the images for the various files/folders, sometimes we face the problem that the alpha blended area of the image is not displayed properly with the default configuration of the list view. So to show the image with the correct display, I've found that if we set the ColorDepth of the image list (to be used to store the images to be shown in list view) to appropriate values, it provides the results as desired. So if smallImgLst and largeImgLst are the two image lists used for list view then if we need two views of the list i.e. Small images(16x16) and Large imges(32x32) then we can set the values as below:

smallImgLst.ColorDepth=ColorDepth.Depth32Bit
largeImgLst.ColorDepth=ColorDepth.Depth32Bit

smallImgLst.ImageSize=New System.Drawing.Size(16,16)
largeImgLst.ImageSize=New System.Drawing.Size(32,32)

If there are some other tips to resolve such kind of issue then comments are invited for discussion.

Friday, April 24, 2009

Display Image in ComboBox

In case we need to display a list of images in ComboBox we can do it by caring just few things about combobox. Firtsly set the 'DrawMode' of the ComboBox to 'OwnerDrawFixed' if all the images are of same size or set 'OwnerDrawVariable' if images are of variable size. and also for the variable sized images set the width and height during the 'MeasureItem' event of the combobox. If imgList1 contains all the needed images of variable and let number of items in the combobox is equal to number of images in the imagelist and each index of image specifies the corresponding item in combo box, Then I guess the following will be fine to get the list of images in the combobox.

1. Set the property 'DrawMode' to OwnerDrawVariable
2. In the method that implement event 'DrawItem' of the combo box, for the case if index of current item is non empty then then draw the image. i.e.

If e.Index<>-1 Then
e.Graphics.DrawImage(imgList1.images(e.Index),e.Bounds.Left,e.Bounds.Top)
End If

3. In the method that implements the 'MeasureItem' event of the combo box the following can be used
e.ItemHeight =imgList1.ImgaeSize.Height
e.ItemWidth = imgList1.ImageSize.Width


These are the basic settings that are needed to display images in combo box, rest are depends on the requirements.

Drop the lines if you think that can be help better for similar kind of requirements.

Count Character Occurances In a String

In a string occurance of particular character can be found easily by using the function 'InStr()' which returns the location of the character in the string. But if we want to count the number of occurances of particular character in the string then I've found the following three ways to get the

Private Function countOccurance1(ByVal hayStack As String,ByVal needle As Char) As Integer
If String.IsNullOrEmpty(hayStack) Then Return 0
Dim chars() As Char = hayStack.ToCharArray
Dim count As Integer = 0
For Each ch As Char In chars
If ch = needle Then count += 1
Next
Return count

End Function

Private Function countOccurance2(ByVal hayStack As String, ByVal needle As String) As Integer
Return (Len(hayStack) - Len(Replace(hayStack, needle, ""))) / Len(needle)
End Function

Private Function countOccurance3(ByVal hayStack As String, ByVal needle As String) As Integer
Dim i As Long, sHayStack As String : sHayStack = hayStack
Do Until InStr(sHayStack, needle) = 0
sHayStack = Replace(sHayStack, needle, "", 1, 1) : i += 1
Loop
Return i

End Function

I've not tested which is more effiecient, but all provides the similar results for many number tests.