Concept: Extensions

Permalink 06/16/10 09:56, by admin, Categories: Projects, Visual Basic, .Net , Tags: .net, extensions, syntax



While translating a C# library, i ran into a segment of code that i didnt recognize. After doing some research found out that the same design can be implemented in VB.Net (VB 2k8). One catch to the whole implementation is that the Extension development is only possible in a module. As well, there are some limitations to the design of the extension.

C# style


Scope ReturnType MethodName('this' ParentType parameter, ParamType para1, ...)

When designing this in C# the structure is:
- Scope : Public, Shared, Private, Friend, etc
- ReturnType : Object or Type
- MethodName : any name that is consistent with the naming convention of the compiler,
- 'this' : the internal pointer to the object that will have the extension,
- ParentType : the object/type that will be utilizing this extension,
- parameter : the internal reference to the 'this' object for operation within the extension method.
- ParamType : the object/type that will actually be passed to the method
- para1 : the parameter variable name to be used within the method

All that being said, here is a live example from a Silverlight Library that i have been de-engineering for educational purposes only (Silverlight Menu).


public static Point TransformFromRootVisual(this UIElement element)
MatrixTransform globalTransform = (MatrixTransform)element.TransformToVisual(null);
return globalTransform.Matrix.Transform(_zero);
catch { }
return _zero;


Point p = this.TransformFromRootVisual();

VB 2k8 style

VB 2k8 has a similar declaration statement, but varies in how each part is incorporated. I will keep the same declaration format names for consistency and comparison.


<Extension()> _
Scope Method MethodName(parameter As ParentType, para1 As ParamType, ...) As ReturnType

End Method

- <Extension()> : Attribute to precede the Method declaration, much like all other Attributes, except this Attribute is Method (Sub/Function) specific and is not available for use with any other declaration type.
- Scope : Private, Public, Friend, etc.
- Method : Sub or Function
- MethodName : Any method name that is consistent with the nameing convention of the compiler
- parameter : any parameter name that is consistent with the naming convention of the compiler.
- ParentType : The object/type that this Extension method will be attached to.
- param1 : Any parameter name that is consistent with the naming convention of the compiler, this parameter will actually be a passed value. This is an optional part of the Extension declaration.
- ParamType : The object/type that the parameter will be defined.
- ReturnType : the object/type that will be returned once all operations are completed inside the method.

As you can see there isn't a whole lot of difference between the C# and VB 2k8 format. yes there are some structural and design implementation difference but in either case they result in the same outcome.

Here is an example of the VB 2k8 equivalent of the C# example:
Extension Declaration:

<extension ()> _
Public Function TransformFromRootVisual(ByVal element As UIElement) As Point
Dim p As New Point

Dim globalTransform As MatrixTransform
globalTransform = CType(element.TransformToVisual(Nothing), MatrixTransform)

p = globalTransform.Matrix.Transform(_zero)
Catch ex As Exception
p = _zero
End Try

Return p
End Function


Dim p As Point = Me.TransformFromRootVisual()


Although in C# you dont have the availability of putting certain code in a module to make it "globally" available, to the whole namespace in which it is declared, you need to place it in a class that is static and not instantiatable.

On the flip side, in VB 2k8 you need to explicitely define a module within the namespace in which you want it used. The caveat is that Extension(s) for VB 2k8 are restricted to only Module level methods and not Class level. Which for some mind-sets restricts the ability to co-locate in consolidated locations.

The key notes:
1) Include System.Runtime.ComilerServices
2) make sure the first parameter is the Object/Type you want the method to be associated with. If you want it to operate on Object types, then make the first parameter of type Object, but be aware that if you do so, the Extension method will be extended out to all objects that inherit type Object within the namespace.

Dynamically Loading Controls

Permalink 03/19/10 11:44, by admin, Categories: News, Visual Basic, .Net , Tags: dynamic loading controls, dynamic loading usercontrols, loadcontrol

Recently, i ran into a situation where i needed to daisy-chain several usercontrols together. The basic thought was similar to most sites "New User Data Entry" forms. You fill one out, and then you goto the next one to fill more incriminating information and then the last form you fill out, you basically sign your life away and your first born.

Problem i ran into was the fact that i could not achieve this effect without a severe overload of page resources (i.e. Multi-View/View relationship) and even then it was sadly sketchy and buggy.

After doing some research and some serious code management (thats what i call it :> ) I managed to achieve a relatively small method, through VB but should be easily translatable since it is small, to get the effect i needed.

Friend Shared Sub NextForm(ByRef par As Control, ByRef curr As Control, ByVal [new] As String)
'remove current control (curr) from parent (par)
'load control into cntrl object
Dim cntrl As Control = par.Page.LoadControl([new])
'add control to the parent
End Sub

Minus the comments and method declaration, this is a 3-liner. For my instance i put it in the residing page and as i performed my logic inside the usercontrols i simply called the page class and then the method.

Below is an example of how i used it in the code.

Data.NextForm(Me.Parent, Me, "content/" & ProdType.Material.ToString & ".ascx")

- Data is the ASPX page
- Me.Parent is the usercontrols containing control (for my instance, it was a placeholder)
- Me is the usercontrol
- "content/" & ProdType.Material.ToString & ".ascx" is the string representation of the location of the usercontrol.

If i remember right LoadControl can any of the different url representations. I use a referential level, for portability if i am lucky and it needs to be implemented elsewhere.

Custom Paging with DataTable

Permalink 03/11/10 12:31, by admin, Categories: News, Projects, .Net, ASP , Tags:, custom paging, gridview

Recently, i found the need to do some custom paging. With this i found several resources that used either a DataSource or a DataView. My specific problem was related to the fact that i was in need of a known column definition but a slightly custom pager row.

So i started out developing the PagerRow as needed, and found that it was cool that you could simply attach 'CommandName="Page"' and 'CommandArgument="First"' to operate the function of moving back to the first page (go here on MSDN to get the full description).

Once i got this far, i then start playing with the Paging Events. First i created click events for each of the buttons to try to manually change the pages, that didnt work (wasted 1hr 30m), then i tried operating it through the PageIndexChanged event, that didnt work (wasted 1hr), lastly, by piecing all of the Custom Paging instructions from all of the high-level coding sites, i surmised a working page function for my need (investment 2hrs - PRICELESS :yes: ).

Considering the amount of time i spent on this and some self discovery, i felt like this would be something others might use. As well, it might fit into the GridView model you are looking for.

Notes To Use:
- I have removed the code that is company specific but put comments at the locations where they should be edited.

If you have any questions, please dont hesitate to comment for explanation or send me an email.

Custom Paging GridView - VB Source
Custom Paging GridView - Designer
Custom Paging GridView - HTML

Runtime Method/Class Call

Permalink 03/10/10 12:04, by admin, Categories: News, Visual Basic, .Net , Tags: assembly.getassembly, constructorinfo.invoke, reflection, runtime class instantiation, runtime method calls, type.invokemember,


Recently, i found myself wanting to dynamically (runtime) construct a method from a class and then call that method without developing a nasty logic structure.

In essence, i wanted to perform this logic, based on known method/class naming:

Dim tmpMethod As String = "Get"
Dim tmpParameters() As Object
tmpMethod &= core.Type.ToString
If Not (core.Shift = Nothing) Then
tmpMethod &= "ByShift"
tmpParameters = New Object() {CType(core.Line, Byte), CType(core.Shift, Byte)}
tmpParameters = New Object() {CType(core.Line, Byte)}
End If

without all the overhead of performing nested If..Then statements, or worse a structure Select...Case logic.

What i came up with is the use of a very high-level programming reflection. With the help of everyone at the MSDN Forums, they were able to push and help me to get this developed.

Below is what ultimately was developed. Although the InvokeMethod method is pretty much nailed down to a Component type (DataAdapter, TableAdapter, etc), it can be massaged for any type and made into a Generic to fit more uses. Although the InvokeMember method can not operate on Generic Methods themselves, you should be able to wrap it with your own generics to conform to your structure

Copied the code below from another site, go here

Public Shared Function CreateInstance(ByVal [type] As Type, ByVal [class] As String, ByVal args() As Object) As Object
Dim ass As Reflection.Assembly = Reflection.Assembly.GetAssembly([type])
For Each t As Type In ass.GetTypes
If t.IsClass = True Then
If t.FullName.EndsWith("." + [class]) Then
Dim con() As Reflection.ConstructorInfo = t.GetConstructors
For Each constr As Reflection.ConstructorInfo In con
If constr.GetParameters.Length = args.Length Then
Return constr.Invoke(args)
End If
End If
End If
Return Nothing
Catch ex As Exception
Throw New System.Exception("could not create instance ---->" + [class])
Return Nothing
End Try
End Function

Copied most of this logic from the MSDN site and pieced together from the MSDN Support inquiry that i submitted.

Public Shared Function InvokeMethod(Of T)(ByVal typeName As ComponentModel.Component, ByVal methodName As String, ByVal param() As Object) As T
Dim [class] As String = typeName.ToString.Substring(typeName.ToString.LastIndexOf(".") + 1)
'create an instance of the object of typeName by its class alone
Dim instance As Object = CreateInstance(typeName.GetType, [class], New Object() {})
'get the type of the object
Dim invoker As Type = instance.GetType

Dim result As Object
result = invoker.InvokeMember(methodName, Reflection.BindingFlags.Public Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.InvokeMethod, Nothing, instance, param)

Return CType(result, T)
End Function

Silverlight 3 Tutorial on Moveable background/terrain

Permalink 09/23/09 15:17, by admin, Categories: News , Tags: 2d moveable background, silverlight, silverlight 3, sl3d


I have developed a transition tutorial with some minor modifications for instantiation.

SL3 Tut

Original posting by Mike Snow

:: Next >>


Programming Blog about the different projects we are working on.


April 2014
Sun Mon Tue Wed Thu Fri Sat
 << <   > >>
    1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30      

XML Feeds

powered by b2evolution