Category Archives: Technology

Design Patterns

There are different classifications/categoris of design pattern when we group together
Classifications:
.Creational
.Structural
.Behavioral
.Security
.Concurrency
.Sql
.User Interface
.Relational
.Social
.Distributed

The classification of design patterns keep growing, this is only exhaustive list.
Design Patterns:
Different types of design patterns:
Creational Patterns
1. Abstract factory: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
2. Builder: Separate the construction of a complex object from its representation allowing the same construction process to create various representations.
3. Factory method: Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
4. Lazy initialization: Tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed.
5. Multiton: Ensure a class has only named instances, and provide global point of access to them.
6. Object pool: Avoid expensive acquistion and release of resources by recycling objects that are no longer in use. Can be considered a generalisation of connection pool and thread pool patterns.
7. Prototype: Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
8. Resource acquisition is initialization: Ensure that resources are properly released by tying them to the lifespan of suitable objects.
9. Singleton: Ensure a class has only one instance, and provide a global point of access to it.

Structural Patterns:
1. Adapter or Wrapper or Translator: Convert the interface of a class into another interface clients expect. An adapter lets classes work together that could not otherwise because of incompatible interfaces. The enterprise integration pattern equivalent is the translator.
2. Bride: Decouple an abstraction from its implementation allowing the two to vary independently.
3. Composite: Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
4. Decorator: Attach additional responsibilities to an object dynamically keeping the same interface. Decorators provide a flexible alternative to subclassing for extending functionality.
5. Facade: Provide a unified interface to a set of interfaces in a subsystem. Facade defines a high-level interface that makes the subsystem easier to use.
6. Flyweight: Use sharing to support large numbers of similar objects efficiently.
7. Front Controller: The pattern relates to the design of Web applications. It provides a centralized entry point for handling requests.
8. Module: Group several related elements, such as classes, singletons, methods, globally used, into a single conceptual entity.
9. Proxy: Provide a surrogate or placeholder for another object to control access to it.

Behavioral Patterns:
1. Blackboard: Generalized observer, which allows multiple readers and writers. Communicates information system-wide.
2. Chain of responsibility: Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.
3. Command: Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log request, and support undoable operations.
4. Interpreter: Given a language, define a representation for its grammar alond with an interpreter that uses the representation to interpret sentences in the language.
5. Iterator: Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
6. Mediator: Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicityly, and it lets you vary their interaction independently.
7. Memento: Without violating encapsulation, capture and externalize an objects’s internal state allowing the object to be restored to this state later.
8. Null object: Avoid null references by providing a default object.
9. Observer or Publish/subscribe: Define a one-tomany dependency between objects where a state change in one object results in all its dependents being notified and updated automatically.
10.Servant: Define common functionality for a group of classes.
11.Specification: Recombinable business logic in a Boolean fashion.
12.State: Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
13.Strategy: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
14.Template method: Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
15.Visitor: Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.

Concurrency Patterns:
1. Active Object: Decouples method execution from method invocation that reside in their own thread of control. The goal is to introduce concurrency, by using asynchronous method invocation and a scheduler for handling requests.
2. Balking: Only execute an action on an object when the object is in a particular state.
3. Binding Properties: Combining multiple observers to force properties in different objects to be synchronized or coordinated in some way.
4. Double-checked locking: Reduce the overhead of acquiring a lock by first testing the locking criterion (the ‘lock hint’) in an unsafe manner; only if that succeeds does the actual lock proceed. Can be unsafe when implemented in some language/hardware combinations. It can therefore sometimes be considered an anti-pattern.
5. Event-based asynchronous: Addresses problems with the asynchronous pattern that occur in multithreaded programs.
6. Guarded Suspension: Manages operations that require both a lock to be acquired and a precondition to be satisfied before the operation can be executed.
7. Lock: One thread puts a “lock” on a resource, preventing other threads from accessing or modifying it.
8. Messaging design pattern (MDP): Allows the interchange of information (i.e. messages) between components and applications.
9. Monitor object: An object whose methods are subject to mutual exclusion, thus preventing multiple objects from erroneously trying to use it at the same time.
10.Reactor: A reactor object provides an asynchronous interface to resources that must be handled synchronously.
11.Read-write lock: Allows concurrent read access to an object, but requires exclusive access for write operations.
12.Scheduler: Explicitly control when threads may execute single-threaded code.
13.Thread pool: A number of threads are created to perform a number of tasks, which are usually organized in a queue. Typically, there are many more tasks than threads. Can be considered a special case of the object pool pattern.
14:Thread-specific storage: Static or global memory local to a thread.

Creational Patterns
->Abstract Factory
-> Builder
-> Factory Method
-> Prototyp
-> Singleton
-> Lazy instatiation
-> Utility Pattern
Creational pattern talks about how we instatiate an object. Different patterns for different ways of instantiation.

Lets check some of the commonly used patterns:
Adapter Pattern
Bridge Pattern
Builder Pattern
Chain of Responsibility
Command Pattern
Composite Pattern
Decorator Design Pattern
Event Aggregator
Facade Pattern
Factory Pattern
Flyweight
Interpreter
Iterator Pattern
Lazy Load Pattern
Mediator Pattern
Memento
Model View Presenter (MVP) Pattern
Model View ViewModel (MVVM) Pattern
Null Object Pattern
Observer Pattern
The Prototype Pattern
Proxy Pattern
Repository Pattern
Singleton
Service Locator Pattern
State Pattern
Strategy Pattern
Template Method
Unit of Work
Visitor Pattern

Lets get the brief introduction of the above mentioned patterns
Adapter Pattern: Adapters are commonly known as wrappers. It’s basically like to when you want to use some methods in a library but the objects or parameters are not the same as in your application then you’ll create a wrapper/adapter which takes the parent/host library methods and convert them to the way that your application can utilize it. It’s called adapter pattern.
Like AC – to – DC adapter we use in our day to day life or voltage adapter when we travel to different countries for your electronic appliances.

Bridge Pattern: “Decouple an abstraction from its implementation so the two can vary independently” as per Gangs of Four. In simple terms, when you are using an object in combination with some other objects rather than providing all the possible combinations you can create an abstraction for each object and then let the user decide on the combination so that at any point of time in the future if you want to add any new items to any of the objects it should not affect the combination. Since the combination is still possible. (Ex: different Burgers and fries & drink or different Burgers and Vegetables & milk.. if you create an abstraction for burgers and fries & drink or vegetables & milk then you can create any number of combinations even if you add another kind of burger or another combination of drink like vegetables & drink).

Builder Pattern: “Separates the construction of a complex object from its representation so that the same construction process can create different representations.” as per Gangs of Four. In simple software terms, separate the data from logic and reuse that logic. Instead of giving the entire steps of a process which is to be repeated, create a logic for that and reuse it. (Ex: going to subway and giving the same instruction again and again whenever you go there create a pattern and just mentioning the pattern that you like to have each time you go there.) simplify the process.

Chain of Responsibility: “Ordered list of message handlers which knows how to do things”. The process goes in this way: Sender gets a message which need to be deciphered and send the response, sender is aware of receiver 1 in the chain as there are multiple receivers in the chain and Sender sends the message to receiver 1 to decipher, as Receiver 1 is not able to decipher that it will send to the next level of receiver Receiver 2 and receiver 2 is capable of deciphering it and sends the response to the sender. Sender is not aware about the receiver 2 and the higher levels of receiver 2 are not aware of the message. It’s like every level has its responsibility and if it’s not capable of resolving the problem it will send to the next higher level and next higher level. Whichever level is able to resolve the problem, will send the response directly to the initial layer raising the problem. Best like Linked list.

The Command Pattern: Also known as Action/Transaction Pattern. Represent an action/logic/operation as an object. Decouple clients that execute the command from the details and dependencies of the command logic. It enables delayed execution.

Factory Patterns: Consider factories when we are unsure of the implementation of an interface I want to return for a given class or creation should be separated from representation of an object or lots of if/else statements when deciding which concrete class to create or switch statements when deciding which concrete class to create:
3 different types of factories available
1. Simple Factory Pattern: Encapsulate object creation. Allows for late-bound decisions regarding instationation (configuration based, other persistent storage, input or other dynamic data). Caller class knows what concrete factory it needs.

Selector Index supported in different levels of CSS

Selector Index supported in different levels of css as per w3

PatternMeaningDescribed in sectionCSS1CSS2CSS3
*any elementUniversal selectorNoYesYes
Ean element of type EType
selector
YesYesYes
E[foo]an E element with a "foo" attributeAttribute selectorsNoYesYes
E[foo="bar"]an E element whose "foo" attribute value is exactly equal to "bar"Attribute
selectors
NoYesYes
E[foo~="bar"]an E element whose "foo" attribute value is a list of
whitespace-separated values, one of which is exactly equal to "bar"
Attribute
selectors
NoYesYes
E[foo^="bar"]an E element whose "foo" attribute value begins exactly with the
string "bar"
Attribute
selectors
NoNoYes
E[foo$="bar"]an E element whose "foo" attribute value ends exactly with the
string "bar"
Attribute
selectors
NoNoYes
E[foo*="bar"]an E element whose "foo" attribute value contains the substring
"bar"
Attribute
selectors
NoNoYes
E[foo|="en"]an E element whose "foo" attribute has a hyphen-separated list of
values beginning (from the left) with "en"
Attribute
selectors
NoYesYes
E:rootan E element, root of the documentStructural
pseudo-classes
NoNoYes
E:nth-child(n)an E element, the n-th child of its parentStructural
pseudo-classes
NoNoYes
E:nth-last-child(n)an E element, the n-th child of its parent, counting from the last
one
Structural
pseudo-classes
NoNoYes
E:nth-of-type(n)an E element, the n-th sibling of its typeStructural
pseudo-classes
NoNoYes
E:nth-last-of-type(n)an E element, the n-th sibling of its type, counting from the last
one
Structural
pseudo-classes
NoNoYes
E:first-childan E element, first child of its parentStructural
pseudo-classes
NoYesYes
E:last-childan E element, last child of its parentStructural
pseudo-classes
NoNoYes
E:first-of-typean E element, first sibling of its typeStructural
pseudo-classes
NoNoYes
E:last-of-typean E element, last sibling of its typeStructural
pseudo-classes
NoNoYes
E:only-childan E element, only child of its parentStructural
pseudo-classes
NoNoYes
E:only-of-type
an E element, only sibling of its typeStructural
pseudo-classes
NoNoYes
E:emptyan E element that has no children (including text nodes)Structural
pseudo-classes
NoNoYes
E:link

E:visited
an E element being the source anchor of a hyperlink of which the
target is not yet visited (:link) or already visited (:visited)
The link
pseudo-classes
YesYesYes
E:activean E element during certain user actionsThe user
action pseudo-classes
YesYesYes
E:hover

E:focus
an E element during certain user actionsThe user
action pseudo-classes
NoYesYes
E:targetan E element being the target of the referring URIThe
target pseudo-class
NoNoYes
E:lang(fr)an element of type E in language "fr" (the document language
specifies how language is determined)
The
:lang() pseudo-class
NoYesYes
E:enabled

E:disabled
a user interface element E which is enabled or disabledThe UI
element states pseudo-classes
NoNoYes
E:checkeda user interface element E which is checked
(for instance a radio-button or checkbox)
The UI
element states pseudo-classes
NoNoYes
E::first-linethe first formatted line of an E elementThe
::first-line pseudo-element
YesYesYes
E::first-letterthe first formatted letter of an E elementThe
::first-letter pseudo-element
YesYesYes
E::beforegenerated content before an E elementThe
::before pseudo-element
NoYesYes
E::aftergenerated content after an E elementThe
::after pseudo-element
NoYesYes
E.warningan E element whose class is "warning" (the document language
specifies how class is determined).
Class
selectors
YesYesYes
E#myidan E element with ID equal to "myid".ID
selectors
YesYesYes
E:not(s)an E element that does not match simple selector sNegation
pseudo-class
NoNoYes
E Fan F element descendant of an E elementDescendant
combinator
YesYesYes
E > Fan F element child of an E elementChild
combinator
NoYesYes
E + Fan F element immediately preceded by an E elementAdjacent sibling combinatorNoYesYes
E ~ Fan F element preceded by an E elementGeneral
sibling combinator
NoNoYes

Reference from W3.org

.Net common questions

Here are some common questions on .Net which can be asked in interviews:

Describe the difference between a Thread and a Process?
An application consists of one or more processes. A process, in the simplest terms, is an executing program. One or more
threads run in the context of the process. A thread is the basic unit to which the operating system allocates processor
time. A thread can execute any part of the process code, incluging parts currently being executed by another thread.

What is a Windows Service and how does its lifecycle differ from a “standard” EXE?
Windows service allows you to create long-running executable applications that run in their own windows sessions. These
services can be managed to start at the boot time or can be controlled manually. The windows service do not have any UI to show
to the user.
Windows service lifetime:
For the service to run, it need to be installed. With the installation, it will load the service into the Service control manager
. Once the service is installed, one can start from the Service Control Manager or from code “start”. The service will run until someone
stops it or the system is shutdown. The service can in any one of these status running, paused or stopped. One can write code to
handle in these statuses.

Standard ‘Exe’ need to be started manually everytime you log in. Standard ‘Exe’ can have UI for the user.

What is the difference between an EXE and a DLL?
EXE is an extension used for executable files while DLL is the extension for a dynamic link library.
An EXE file can be run independently while a DLL is used by other applications
An EXE file defines an entry point while a DLL does not
A DLL file can be reused by other applications while an exe cannot.
A dll would share the same process and memory space of the calling application while an exe creates its separate process and memory space.

What is strong-typing versus weak-typing?
Strong typing means that once assigned a value of a particular kind, objects objey strict rules about how they can interact with other objects of vaious types.
Weak typing means that such rules are more relaxed.
Python is considered strongly typed while PHP is considered weak-typing.
c# is strong types and javascript is weak typed.

still to come…

Reactive Extensions

While testing little bit with the reactive extensions, I felt the same thing which we used to do with many lines of code can be done using the reactive extensions so easily just by subscribing. The basic principle used is “Observer Pattern”: some objects observe a certain event or we can say as some subscribed objects get notified when a certain event or action occurs. With the linq in built this was fascinating to work with.

As enumerator uses pull the observer uses push.

The entire library revolves around two interfaces IObserve and IObservable. It’s like any object that observes should implement IObserve interface and the objects that are going to emit should implement IObservable interface. Earlier IObserve and IObservable were implemented in different assembly, now they are in System.Core, so it’s global and very useful.

The general syntax will be like

var query = from n in Enumerable.Range(1, 5) select n;
foreach(var n in query)
     Console.WriteLine(n);

//call the method which writes "I'm Done" to the console

The same can be written in Rx

var query = from n in Enumerable.Range(1, 5) select n;
var observableQuery = query.ToObservable();
observableQuery.Subscribe(Console.WriteLine, () => {Console.WriteLine("I'm Done");});

If we look at the code here, we are converting an Range [1, 2, 3, 4, 5] into Observable. When the system access each item , that item is passed to the Console.WriteLine which is observer her and the next parameter is a callback.

There is lot more than this..
We can make the operation to be performed on one thread and dispatch using the other.. For time consuming operations this will be good

If we have a WPF application and in that we have a button “Send” and textbox results

	private string stringWait(string str)
		{
			Thread.Sleep(250);
			return str;
		}
		protected void btnSend_Click(Object sender, EventArgs e)
		{
			var query = (from n in Enumerable.Range(1, 25) select stringWait(n.ToString())).ToObservable(Scheduler.ThreadPool);
			query.ObserveOnDispatcher().Subscribe(
				(string x) => {	Results.AppendText(String.Format("{0}\n", x));}
			);
			
		}

In the above code the query is observed by the dispatcher whereas the the operation is performed in the thread pool. If we use the same thread to dispatch that will raise and clr exception. To resolve this concurrency issue we can use ObserveOnDispatcher method, which will write the data.

There are many methods in the Observable which are useful

var source = Observable.Generate(0, i=>i<5, i=>i+1, i=>i*2, i=>TimeSpan.FromSeconds(i));

The above code will generate the sequence with the timespan difference.

			IDisposable subscription = source.Subscribe(
				(int x) => {Console.WriteLine("Received {0} from source and the thread {1}", x, Thread.CurrentThread.ManagedThreadId);Thread.Sleep(1000);},
			                                            (Exception ex)=> {Console.WriteLine("Received error: {0}", ex.Message);},
			                                            () => {Console.WriteLine("End of subscription");});

The subscribe method creates a subscription which implements IDisposable, which will be disposed when the subscription is completed.

the “Subscribe” method will emit data for 3 occurences “onNext”, “onError”, “onCompleted”.
Subscribe(onNext, onError, onCompleted)

Any object can be subscribed to any particular event too.. just like an event handler to notify the objects of the event. The same thing can be handled with the Rx, rx won’t replace the existing event handler system but we can use it in multiple scenarios

With the current version you can subscibe to an event like the following

var lbl = new Label{Text="Hello There", AutoSize=true};
			var txt = new TextBox {Width=200};
			txt.TextChanged += (sender, e) => {lbl.Text = "text changed" + txt.Text;};
			var frm = new Form{
				Controls = {
					lbl,
					txt
				}
					};
			var events = Observable.FromEventPattern<MouseEventHandler, MouseEventArgs>(h => h.Invoke, eh => frm.MouseMove += eh, eh => frm.MouseMove -= eh);
			using(events.Subscribe( evt => {
			                 	lbl.Text += Environment.NewLine + evt.EventArgs.Location.ToString();
			                 	Console.WriteLine("Current Location: {0} at {1}", evt.EventArgs.Location.ToString(), DateTime.Now.ToShortTimeString());
			                        }))
				
			{
			
			Application.Run(frm);
			}

Could not set focus on the invisible object – AjaxControlToolkit

Recently when we updated our AjaxControlToolkit library, strangely it was giving an “Could not set focus on the invisible Object” error on some machines. When I debugged it, the error raised with the tab panel. The same code is working fine with the older AjaxControlToolkit library version. But we modified our pages to suit the latest version so we had to tweek the current version js function. The developers of AjaxControlToolkit have added a method to set focus on the tab panels. The following code resolved the issue..


        //To resolve an error(set focus) with the current AjaxControlToolkit version (4.1.51116.0)
        if (Sys.Extended.UI.TabPanel != 'undefined' && Sys.Extended.UI.TabPanel) {
            Sys.Extended.UI.TabPanel.prototype._setFocus = function (a) {
                var x = $get("__tab_" + a.get_element().id);
                if (x.hidden == false && x.style.visibility != 'hidden' && x.style.display != 'none')
                    x.focus();
            }
        }
   

Powershell – Basics 4

lets talk about the variables

# All variables start with a $. Show a simple assignment
$hi = "Hello World"

#Print the Value
$hi

Write-Host $hi

# Show the type
$hi.GetType()

#Types oare mutaple
Clear-Host
$hi = 5
$hi.GetType()

Clear-Host
[System.Int32]$myint = 42 # Can make strongly typed variables
$myint
$myint.GetType()

$myint = "This won't work will raise an exception"

# There are shortcuts for most .net types
clear-host
[int] $myotherint = 42
$myotherint.GetType()

[string] $mystring = "hansy"
$mystring.GetType()

# Others include short, float, decimal, single, bool, byte, etc

(42).GetType() # Not just varibles are types
"Hansy is cool".GetType()

# Accessing methods on objects
"Hansy is Cool".ToUpper()
"Hansy is cool".Contains("is")

# comparisons
$var = 42
$var -gt 40
$var -lt 40
$var -eq 42

# List is
# -eq Equals
# -ne not equal to
# -lt less than
# -gt Greater than
# -le Less than or equal to
# -ge Greater than or equal to

# -Like        Like wildcard pattern matchin
# -NotLike     Not like
# -Match       Matches based on regular expressions
# -NotMatch    Non-matches based on regular expressions

# Calculations are like any other language
$var = 3*11 # Also uses +, -, and /
$var

$var++ # supports unary operators ++ and --
$var

#implicit Type conversions
"43" -eq 42
42 -eq "42"

# Whatever is on the right is converted to the data type on the left
# can lead to some odd conversions
42 -eq "042" # True because the string is converted to int
"042" -eq 42 # False because the int is converted to string


#--------------------------------------------
# Using the *-Variable cndlets
#--------------------------------------------

Clear-Host

#normal variable usage
$normal = 33
$normal

$text = "in the morning"
$text

# Long version of $var = 123
New-variable -Name var -Value 123
$var

#Displays the variable and it's values
Get-Variable var -valueonly

Get-Variable var

Get-Variable # Without Patams it shows all variables

# Assign a new vale to an existing variable
# $var = 789
Set-Variable -Name var -value 789
$var

#clear the contents of a variable
# same as $var = null
Clear-variable -Name var
# After a clear you can still access $var, but it has no value
$var

#Wipe out a varilable
Remove-variable -Name var
# Now var is gone if you try to remove or clear again an error occurs
# (note if you try to access it by just doing a $var the var is recreated)

Get-Variable var # now produces an error

$var # recreates the object


#------------------------------------------
# String Handling
#------------------------------------------

# String Quoting
Clear-Host

"This is a string"
'This is a string too!'

# Mixed Quoted
'I just wanted to say "Hello World", OK?'
"I can't believe how cool powershell is!"

# You can also double quote to get quot3s in strings
"I just wanted to say ""Hello World"", OK?"
'I can''t believe how cool powershell is!'

#Escape sequences - use the backtick `
Clear-host
# backspace `b (have to show in rea window)
"hans`braj"

# newline `n
"Hans`nraj"

# carriage return `r (doesn't really show anything)
"Hans`sraj"

# crlf `r`n
"hans`r`nraj"

# tabs
"hans`traj"


# Here strings for large blocks of text----------------
clear-host
$hertext=@"
Some text here
more here and little
    bit more here

and a blank line above
"@

$hertext

# the @ and quote must be last on starting line then first on ending line
# also works with single quotes

$morehertext =@'
Some more text here
to test with single
   quote
   
 using a blank line too!.
'@
 
 # note how the nexted ' is handled ok, no double quoting needed

 $morehertext
# String interpolation
clear-host
$items = (Get-ChildItem).Count
$loc = Get-Location
"There are $items items are in the folder $loc" 

# To actually display the variable, excape it with a backtick
"There are `$items items are in the folder `$loc."

# String interpolation only works with double quotes
'There are $items items are in the folder $loc '

# It does work with here strings
$hereinterpolation = @"
Items`tFolder
-----`t------------
$items`t$loc

"@

$hereinterpolation

# Can use expressions in strings, need to be wrapped in $()
clear-host
"There are $((Get-ChildItem).COunt) items are in the folder $(Get-Location)."

"The 15% tip of a 33.33 dollar bill is $(33.33 * 0.15) dollars."

#String Formatting -C# like syntax is supported
# In C you'd use:

[string]::Format("There are {0} items.", $items)

#Powershell shortuct
"There are {0} items." -f $items

"There are {0} items in the location {1}." -f $items, $loc

"The 12% tip of a 33.33 dollar bill is {0} dollars" -f (33.33 * 0.12)

"The 12% tip of a 33.33 dollar bill is {0:0.00} dollars" -f (33.33 * 0.12)

#Wildcards
clear-host
"Hansraj" -like "hans*"
"Hansraj" -like "some*"
"Hansraj" -like "?ansraj" # question marks work for single characters
"Hansraj" -like "hans*[a-j]"   # ends in a char berween a and j
"Hansraj" -like "hans*"   # ends in a char between c and s

# Regular expressions
clear-host
"231-334-1254" -match "[0-9]{3}-[0-9]{3}-[0-9]{4}"  #validdate phone number
"abc-334-1254" -match "[0-9]{3}-[0-9]{3}-[0-9]{4}" #validation fails
"231.334.1254" -match "[0-9]{3}-[0-9]{3}-[0-9]{4}" #validation fails


#---------------------------------------
# Arrays
#-----------------------------------------

# Simiple array
clear-host
$array = "some", "code"
$array[0]
$array[1]
$array

$array.GetType()

#Updating arrays
$array = "robert", "Rama"
$array

$array[0] = "roope"
$array[1] = "ssope"

$array

#Formal array creating syntax
$array = @("some", "code")
$array

$array = @() # only way to create an empty array
$array.Count

$array = 1..5 # Can load arrays using numeric range notation
$array

# Check to see if an item exists
clear-host
$numbers = 1, 42, 234
$numbers -contains 42

$numbers -notcontains 99

$numbers -notcontains 234

##

#----------------------------------------
# Hash Tables
#-----------------------------------------

$hash = @{"Key" = "Value";
           "Some" = "Code";
           "mcsft" = "Microsoft"}
$hash           #Displays all values
$hash["mcsft"]  # Get a single value for the key

$hash."mcsft" # Get a single value using object suntax

# You can use variables a keys
$mykey = "Some"
$hash.$mykey      #using variable as a property
$hash.$($mykey)   #Evaluating as an expression
$hash.$("So" + "me")

#Adding and removing values
$hash               #Here's what's there to start
$hash["Top Gear"] = "topgear.com"   # Add value using new key
$hash               #Show the additional row

$hash.Remove("Some")  # Remove by passing the key
$hash

# See if key exists
$hash.Contains("Top Gear")
$hash.Contains("Some")

$hash.ContainsValue("Code")
$hash.ContainsValue("Microsoft")

$hash.Keys
$hash.Values

$hash.Keys -Contains "mcsft"


##########--
### Built in variables
#########----

clear-host
set-location c:\New_folder
#Automatic variables

#False and true
$false
$true
#nUll
$null

# Current directory
$pwd

#Users HOme Direcotory
$home
#Info about a users machine
$host

# Process ID
$PID

#Info about the current version of powershell
$PSVersionTable

$_  # CurrentObject
Get-ChildItem | Where-Object {$_.Name -like "*.ps1"}

Powershell – Basics 3

If we look more into powershell programming

#---------------------------------------------------
# Functions
#---------------------------------------------------

# Functions are basically script blocks with names.
function write-fullname($firstName, $lastName)
{
    Write-host ($lastName + " , " + $firstName)
}

write-fullname "Kishore" "Patil"  //output: Patil, Kishore

# unlike other languages, you don't use () or ,
# Rather than using set-variable with its -scope, you can pass by ref
# Note however it turns it into an object, thus requiring the .Value syntax
function Set-fvar([ref] $myparam)
{
$myparam.Value = 33
}

clear-host
$fvar = 42
"fvar before: $fvar"
Set-fvar ([ref] $fvar) # Must add ref to call
"fvar after: $fvar"

# Read from pipeline
function Get-CoolFiles()
{
    begin {$retval = "Here are some cool files: `r`n"}
    process {
                if ($_.Name -like "*.ps1")
                    {$retval = $retval + "`t"+ $_.Name + "`r`n"}
                }
    end {return $retval}
}


clear-host
Get-ChildItem | Get-CoolFiles

# Above works but ties it to PS1


# Filters can be built to remove unwanted files
filter Show-PS1Files
{
    $filename = $_.Name
    if ($filename -like "*.ps1")
        { 
            return $_
         }
}

clear-host
Get-ChildItem | Show-PS1Files

# This Version doesn't check for ps1, it just lists what's passed in
function List-FileNames()
{
  begin {$retval = "Here are some cool files: `r`n"}
    process {
               $retval = $retval + "`t"+ $_.Name + "`r`n"
                }
    end {return $retval}
    
}

clear-host
Get-ChildItem | List-FileNames

#Now combine the two for real flexibility
Get-ChildItem | Show-PS1Files | List-FileNames

# Now to do other files, just create another filter
filter Show-textfiles
{
    $filename = $_.Name
    if ($filename -like "*.txt")
        { 
            return $_
         }
}


Get-ChildItem | Show-textFiles | List-FileNames

# Now you have two ways to use your functions
clear-host
Get-ChildItem | Show-PS1Files | List-FileNames
Get-ChildItem | Show-textFiles | List-FileNames

# Having your function output to the pipeline
clear-host
Get-ChildItem | Select-Object "Name"

function Get-ChildName()
{
    Write-output (Get-ChildItem | Select-Object "Name")
}

Get-ChildName | Where-Object {$_.Name -like "*.ps1"}

# Supporting -verbose and -debug options
# To support, first need to change the values of the special variables:
# $DebugPreference        Default is SilentlyContinue, change to Continue
# $VerbosePreference      Default is SilentlyContinue, change to Continue

function Get-ChildName()
{
    param([switch]$verbose, [switch]$debug)
    
    if ($verbose.IsPresent)
    { $VerbosePreference = "Continue"} 
    else
    {$VerbosePreference = "SilentlyContinue"}   
    if ($debug.IsPresent)
    {
        $DebugPreference = "Continue"
    }
    else
    {
        $DebugPreference = "SilentlyContinue"
    }
    
    
    write-verbose "Current working location is $(Get-Location)"
    write-output (Get-ChildItem | Select-Object "Name")
    write-debug "OK I've selected some."
}

clear-host
Get-ChildName
Get-childname -verbose
Get-childName -debug
Get-ChildName -verbose -debug


#-------------------------------------------------------
# Adding help to your functions
#-------------------------------------------------------

clear-host
get-help get-childname

#Custom tags within a comment block that Get-Help will recognize
# Note that not all of them are required
# .SYNOPSIS        - A brief description of the command
# .DESCRIPTION     - Detailed command description
# .PARAMETER name  - Include one description for each parameter
# .EXAMPLE         - Detailed examples on how to use the command
# .INPUTS          - What pipeline inputs are supported
# .OUTPUTS         - What this function outputs
# .NOTES           - Any misc notes you haven't put anywhere else
# .LINK            - A link to the URL for more help. Use one .Link tag per URL
# Use "Get-Help about_comment_based_help" for full list and details

function Get-ChildName()
{
<#
    .SYNOPSIS
    Returns a list of only the names for the child items in the current location.
    
    .DESCRIPTION
    This function is similar to Get-ChildItem, except that it returns only the name property.
    
    .INPUTS
    None.
    
    .OUTPUTS
    System.String. sends a collection of strings out of the piepeline.
        
#>

    Write-output (Get-ChildItem | Select-Object "Name")
}


clear-host
get-help get-childname


clear-host
get-help get-childname -full

#---------------------------------------------------------------
# Error handling
#---------------------------------------------------------------

function divier($enum, $denom)
{
    Write-Host "Divier begin"
    $result = $enum / $denom
    Write-host "Result: $result"
    Write-Host "Divier done."
}

clear-host
divier 33 11

divier 33 0

function divier($enum, $denom)
{
    Write-Host "Divier begin"
    $result = $enum / $denom
    Write-host "Result: $result"
    Write-Host "Divier done."
    trap
    {
        write-host "oh no! An error has occured !!"
        write-host $_.ErrorId
        write-host $_.Exception.Message
        continue # Continue will continue with the next line of code after the error
    }
}

clear-host
divier 33 0

function divier($enum, $denom)
{
    Write-Host "Divier begin"
    $result = $enum / $denom
    Write-host "Result: $result"
    Write-Host "Divier done."
    trap
    {
        write-host "oh no! An error has occured !!"
        write-host $_.ErrorId
        write-host $_.Exception.Message
        break # With break, or omitting it, error bubbles up to parent
    }
}

clear-host
divier 33 0

function divier($enum, $denom)
{
    trap [System.DivideByZeroException]
    {
        write-host "Hey, chowderhead, you can't divide by zero!"
        continue
    }
     trap
    {
        write-host "oh no! An error has occured !!"
        write-host $_.ErrorId
        write-host $_.Exception.Message
        break # With break, or omitting it, error bubbles up to parent
    }
    Write-Host "Divier begin"
    $result = $enum / $denom
    Write-host "Result: $result"
    Write-Host "Divier done."
   
}

clear-host
divier 33 0

# Two main ways to handle errors
# Option 1 - Handle error internally - see above function

# option 2 - Add trap logic in parent

# Change continue to break
function divier($enum, $denom)
{
    trap [System.DivideByZeroException]
    {
        write-host "Hey, chowderhead, you can't divide by zero!"
        break
    }
     trap
    {
        write-host "oh no! An error has occured !!"
        write-host $_.ErrorId
        write-host $_.Exception.Message
        break # With break, or omitting it, error bubbles up to parent
    }
    Write-Host "Divier begin"
    $result = $enum / $denom
    Write-host "Result: $result"
    Write-Host "Divier done."
   
}

# Now call routine in a script block or other function
& {
clear-host
divier 33 0

# Assume child has handled error, keep goin silently
trap
{ continue }

}

#-----------------------------------------------------------#
# Working with files
#-----------------------------------------------------------#
clear-host
Get-ChildItem "?.txt"

Get-Content "a.txt"
$a = Get-Content "a.txt"

clear-host
$a

# Looks are decptive, this actually an array
$a[0]
$a[1]

$a.GetType()

clear-host
for($i =0;$i -le $a.Count;$i++)
{$a[$i]}

# To combine, we can use join, passing in the seperator and the variable
$seperator = [System.Environment]::NewLine # could have done `r`n
$all = [string]::Join($seperator, $a)

$all

$all.GetType()  # string

# Supports wildcards
$courses = Get-content "?.txt"
$courses

$allcourses =[string]::Join($seperator, $courses)
$allcourses

# To write things to disk, use set-content

# Just to prove it's not there
Get-ChildItem "All Courses.txt"

set-content -value $allcourses -path "All Courses.txt"

Get-Content "All Courses.txt"

# Set-Content is destructive!!! If the file exists it's overwritten
Set-Content -Value "Powershell" -Path "All Courses.txt"
Get-Content "All Courses.txt"

# To append, use add-content
set-content -value $allcourses -path "All Courses.txt" # Recreate file
Get-Content "All Courses.txt"


Add-Content -Value "Powershell" -Path "All Courses.txt"
Get-Content "All Courses.txt" # Show it again with new course

# clean up afterward
Remove-item "All courses.txt"

# csv files
# use it to save objects

Get-process | Export-CSV "Processes.csv"

# And then read them
$header = "_NounName", "Name", "Handles", "VM", "WS", "PM", "NPM", "Path", "Company", "CPU", "FileVersion", "ProductVersion", "Product"
$processes = Import-CSV "Processes.csv" -Header $header
$processes

# XML Files
# Create an XML Template
$courseTemplate = @"
<courses version="1.0">
    <course>
        <name></name>
        <level></level>
    </course>
</courses>
"@

$courseTemplate | Out-File "C:\Users\Kpatil\documents\Powershell_Tut\somecourses.xml"

# Create a new xml variable and load it from the file
$courseXml = New-Object xml
$courseXml.Load("C:\Users\kpatil\documents\Powershell_Tut\SomeCourses.xml")

# Grab the template
$newCourse = (@($courseXml.courses.course)[0]).Clone()

#Loop over the collection from CSV and add them to the xml
$header = "Course", "Level"
$coursecsv = Import-Csv "All Courses.csv" -Header $header

for($i=0;$i -lt $coursecsv.Count;$i++)
{
    $newCourse = $newCourse.Clone() # copy the previous object, or for the first time copy the template
    $newCourse.Name = $coursecsv[$i].Course
    $newCourse.Level = $coursecsv[$i].Level
    $courseXml.Courses.AppendChild($newCourse) > $null # If you don't redirect to Null it echos each appen
}

#Remove the template since we now have data
$courseXml.Courses.Course |
    Where-Object {$_.Name -eq ""} |
    ForEach-Object {[void]$courseXml.Courses.RemoveChild($_)}

# Save to Xml file
$courseXml.Save("C:\Users\kpatil\documents\Powershell_Tut\SomeCourses.xml")

# Open it up and show as a plain text file
$textxml = Get-content "C:\Users\kpatil\documents\Powershell_Tut\SomeCourses.xml"
$textxml

# Open it up and work with it as an xml file
$mycoursesxml = get-content "C:\Users\kpatil\documents\Powershell_Tut\SomeCourses.xml"
foreach($course in $mycoursesXml.courses.course)
{
    Write-host "The course" $course.Name "is a Level" $course.Level "course."
}

Powershell – Basics 2

If we look more into powershell, like conditional statements and looping like (if..else, switch, while) just like in .Net basically syntax looks similar to c#

#----------------------------
# Conditional statements
#---------------------------

Clear-Host
#Condition - if/else
$var = 2
if ($var -eq 1)
{
Clear-Host
"If loop"
}
else
{
clear-host
"else loop"
}

# if elseif
if($var -eq 1)
{
 clear-host
 "If -eq 1 loop"
}
else
{
    if ($var -eq 2)
    {
    clear-host
    "If -eq 2 loop"
    }
    else
    {
    clear-host
    "else else loop"
    }
}

#Switch statement for multiple conditions
clear-host
$var = 43 #Also test with 43 and 49

switch ($var)
{
    41 {"Forty one"}
    43 {"Forty three"}
    49 {"Forty nie"}
    default {"Fifty"}
}


#Will match all lines that match
clear-host
$var = 42
switch($var)
{
    42 {"Forty two"}
    "42" {"Forty Two string"}
    default {"default"}
}

#To Stop processing once a block is found use break
clear-host
$var = 42
switch($var)
{
    42 {"Forty two";break}
    "42" {"Forty Two string";break} 
    default {"default"}
}

#Swtich works with collections, looping and execyting for each match
clear-host
switch (3,1,2,42)
{ 
1 {"One"}
2 {"Two"}
3 {"Three"}
default {"The default answer"}
}

# String compares are case insensitive by default
clear-host
switch ("Some")
{
    "some" {"lowercase"}
    "SOME" {"UpperCase"}
    "Some" {"Mixedcase"}
}

# Use the -casesensitive switch to make it sensitive
clear-host
switch -casesensitive ("Some")
{
  "some" {"lowercase"}
    "SOME" {"UpperCase"}
    "Some" {"Mixedcase"}
}

# Supports wildcards
clear-host
switch -Wildcard ("Some")
{
  "so*" {"*"}
    "?ome" {"?"}
    "So??" {"???"}
}

# Note it will also support regex matches

##

#-----------------------------------------------------------
# Looping
#-----------------------------------------------------------

#while
clear-host
$i = 1
while ($i -le 5)
{
    "`$i = $i"
    $i = $i +1
}

# won't execute if condition is already true
clear-host
$i = 6
while ($i -le 5)
{
    "`$i = $i"
    $i = $i +1
}


#Do
clear-host
$i = 1
do
{
    "`$i = $i"
    $i++
}while ($i -le 5)

# Do will always execute at least once
clear-host
$i = 6
do
{
    "`$i = $i"
    $i++
}while ($i -le 5)

# Use until to make the check more positive
clear-host
$i = 1
do
{
    "`$i = $i"
    $i++
}until ($i -gt 5)

# For loop iterate a number of times
clear-host
for ($f =0;$f -le 5;$f++)
{
    "`$f = $f"
}

#Note the initializer can be set seperately
clear-host
$f=1
for (;$f -le 5;$f++)
{
    "`$f = $f"
}

# Iterating over a collection 1 by 1
clear-host
$array = 11,12,13,14,15  # Simple array
for ($f =0;$f -lt $array.Length ;$f++)
{
    "`$array[$f] =" +$array[$f]
}

# foreach works on a collection
clear-host
$array = 11,12,13,14,15  # Simple array
foreach ($item in $array)
{
    "`$item = $item"
}

# foreach works with an array of objects
clear-host
$array = 11,12,13,14,15  # Simple array
foreach ($item in Get-ChildItem)
{
  $item.Name
}

# Combine with if to give a better focus
clear-host
set-location "C:\Users\kpatil\Documents\Powershell_Tut"
$array = 11,12,13,14,15  # Simple array
foreach ($item in Get-ChildItem)
{
    if($item.Name -like "*.ps1")
    {
        $item.Name
     }
}

# Use break to get out of the loop
clear-host
set-location "C:\Users\newuser\Documents\Powershell_basics"
$array = 11,12,13,14,15  # Simple array
foreach ($item in Get-ChildItem)
{
    if($item.Name -like "*.ps1")
    {
        $item.Name
        break # Exits the loop on first hit
     }
}

# Use continue to skip the rest of a loop but got onto the next iteration
clear-host
set-location "C:\Users\newuser\Documents\Powershell_Tut"
foreach ($item in Get-ChildItem)
{
    if($item.Name -like "*.ps1")
    {
        $item.Name
        continue # 3xits the loop on first hit
     }
     "This isn't a powershell command: $item"
}

# When used in a nested loop, break exits to the outer loop
clear-host
foreach ($outside in 1..5)
{
"`$outside = $outside"
    foreach($inside in 6..9)
    {
        "   `$inside = $inside"
        break
    }
}

# Use loop labels to break to a certain loop
clear-host
:outsideloop foreach ($outside in 1..5)
{
"`$outside = $outside"
    foreach($inside in 6..9)
    {
        "   `$inside = $inside"
        break outsideloop
    }
}

# Using continuew inside an inner loop
clear-host
foreach ($outside in 1..5)
{
"`$outside = $outside"
    foreach($inside in 6..9)
    {
        "   `$inside = $inside"
        continue
        "this will never execute as continue goes back to start of inner for loop"
        #note, because we continue to the inside loop, the above line
        # will never run but it will go through all itereations of the inner loop
    }
}

clear-host
:outsideloop foreach ($outside in 1..5)
{
"`$outside = $outside"
    foreach($inside in 6..9)
    {
        "   `$inside = $inside"
        continue outsideloop
        "this will never execute as continue goes back to start of inner for loop"
        #here, because we break all the way to the outer loop the last two
        # iterations (8 and 9) never run
    }
    "this will never run too"
}

##

Powershell – Basics

It’s very interesting to learn and work with powershell. It’s very powerful and uses most of the Microsoft .Net Class Library. If we look at the basics

#Get-Command - Retrieves a list of all powershell commands
Get-Command

# Can expand by searching for just a verb or noun
Get-Command -verb "get"
Get-Command -noun "service"

# Get-Help can be used to explain a command
Get-Help Get-Command
Get-Help Get-Command -examples
Get-Help Get-Command -detailed
Get-Help Get-Command -full

#Most Command can also be passed a -? parameter to get help
Get-Command -?

#Moving around the file tree
#Get-ChildItem list all items in current path
Get-ChildItem

# set-Location will change the current path
Set-Location c:\app
Set-Location "C:\New_folder\"

# Pipelining -combine CmdLets for Power
Get-ChildItem | Where-Object {$_.Length -gt 1kb }

Get-ChildItem | Where-Object {$_.Length -gt 1kb } | Sort-Object Length

#Can break commands up among several lines
# (note pipe must be last char on line)
Get-ChildItem |
    Where-Object {$_.Length -gt 1kb } |
    Sort-Object Length
    
#To Specify columns in the output and get nice formatting, use Format-Table
Get-ChildItem |
    Where-Object {$_.Length -gt 1kb } |
    Sort-Object Length |
    Format-Table -Property Name, Length -AutoSize

#You can also use the Select-Object to retrieve certain properties from an object
Get-ChildItem |
    Select-Object Name, Length | Where-Object {$_.Length -gt 1kb }|
    Sort-Object Length
    
# .Net Everywhere
$str = "I am now a powershell novice"
$str            //Gets the string
$str.Length     //Gets the length of the string
$str.GetType()  //String

Dynamic in VB.Net and Creating a wrapper

I was trying some new things and its not that difficult to implement Dynamic Object in VB.Net either. I tried by creating a dynamic class which can take any number of fields by using a dictionary object

Initially i created SomeDictionary Class

Public Class SomeDictionary
Private ReadOnly _values As Dictionary(Of String, Object)
Private ReadOnly _oldValues As Dictionary(Of String, Object) = New Dictionary(Of String, Object)()

Public Sub New()
_values = New Dictionary(Of String, Object)
End Sub

Public Sub New(values As IDictionary(Of String, Object))
_values = values
End Sub

Default Public Property SomeDictionary(key As String) As Object
Get
Dim result As Object = Nothing
_values.TryGetValue(key, result)
Return result
End Get
Set(value As Object)
If Not _oldValues.ContainsKey(key) Then
Dim oldValue As Object = Nothing
_values.TryGetValue(key, oldValue)
_oldValues(key) = oldValue
End If
_values(key) = value
End Set
End Property

Public Function GetChanges() As IDictionary(Of String, Object)
Dim result = (From key In _oldValues.Keys
Let oldValue = _oldValues(key)
Let newValue = _values(key)
Where Not Object.Equals(oldValue, newValue)
Select New With {.Key = key, .Value = newValue}).ToDictionary(Function(p) p.Key, Function(p) p.Value)
Return result
End Function

End Class

Once this is done, I created a sample Dynamic class

Public Class SomeCommonClass
Inherits Dynamic.DynamicObject
Dim _tracking As SomeDictionary
Public Sub New()
_tracking = New SomeDictionary()
End Sub
Public Overrides Function TrySetMember(binder As Dynamic.SetMemberBinder, value As Object) As Boolean
Try
If _tracking Is Nothing Then
Return False
End If
_tracking(binder.Name) = value
Catch ex As Exception

End Try
Return True
End Function

Public Overrides Function TryGetMember(binder As Dynamic.GetMemberBinder, ByRef result As Object) As Boolean
Try
If _tracking Is Nothing Then
Return False
End If
If _tracking(binder.Name) Is Nothing Then
result = Nothing
Return False
End If
result = _tracking(binder.Name)
Catch ex As Exception

End Try
Return True
End Function

Public Overrides Function TryInvokeMember(binder As Dynamic.InvokeMemberBinder, args() As Object, ByRef result As Object) As Boolean
Try

Dim mInfo = GetType(SomeDictionary).GetMethod(binder.Name)
If mInfo Is Nothing Then
result = Nothing
Return False
Else
result = mInfo.Invoke(_tracking, args)
End If
Return True
Catch ex As Exception
result = Nothing
Return False
End Try
End Function
End Class

We can override the setmember and getmember methods of DynamicObject class and use it the way we like it.
We can also override the InvokeMember method also so that we can implement the kind of response we want when the user calls a method. Here just for example I used the same Dictionary class to implement this method we can use any other method also in case if you are creating a dyanamic class as a wrapper:
Calling the Dynamic class is also very simple

Dim some As Object = New SomeCommonClass
some.Name = "Kishore Patil"
some.Phone = "12124455"
some.Address_City = "Cincinnati"
some.Address_Street = "8000 Some Dr"
some.Address_State = "Ohio"

We can use this particular class to have any kind of field stored and retrived using the Dictionary.
The following is the example converted to VB.Net originally published here for C#

Public Class DynamicXmlNode
    Inherits Dynamic.DynamicObject
    Dim node As XElement

    Public Sub New(node As XElement)
        Me.node = node
    End Sub

    Public Sub New()

    End Sub

    Public Sub New(name As String)
        node = New XElement(name)
    End Sub
    Public Overrides Function TryConvert(binder As Dynamic.ConvertBinder, ByRef result As Object) As Boolean

        If binder.Type = GetType(String) AndAlso binder.ReturnType = GetType(String) Then
            result = node.Value
            Return True
        ElseIf binder.Type = GetType(Integer) AndAlso binder.ReturnType = GetType(Integer) Then
            result = node.Value
            Return True
        End If
        Return True
    End Function

    Public Overrides Function TrySetMember(binder As Dynamic.SetMemberBinder, value As Object) As Boolean
        Dim setNode As XElement = node.Element(binder.Name)
        If Not setNode Is Nothing Then
            setNode.SetValue(value)
        Else
            If value.GetType = GetType(DynamicXmlNode) Then
                node.Add(New XElement(binder.Name))
            Else
                node.Add(New XElement(binder.Name, value))
            End If

        End If
            Return True
    End Function

    Public Overrides Function TryGetMember(binder As Dynamic.GetMemberBinder, ByRef result As Object) As Boolean
        Dim getNode As XElement = node.Element(binder.Name)
        If Not getNode Is Nothing Then
            If getNode.HasElements Or String.IsNullOrEmpty(getNode.Value) Then
                result = New DynamicXmlNode(getNode)
            Else
                result = getNode.Value
            End If

            Return True
        Else
            result = Nothing
            Return False
        End If
    End Function

    Public Overrides Function TryInvokeMember(binder As Dynamic.InvokeMemberBinder, args() As Object, ByRef result As Object) As Boolean
        Try
            Dim xmlType As Type = GetType(XElement)
            result = xmlType.InvokeMember(binder.Name, Reflection.BindingFlags.InvokeMethod Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.Instance, Nothing, result, args)
            Return True
        Catch ex As Exception
            result = Nothing
            Return False
        End Try

    End Function
End Class

To use Convert in VB we need to something like this CTypeDynamic(node.Address.City, GetType(String)). It’s very helpful in writing wrappers only drawback being its slow and no intellisense will be available.