Jan 04

This one I found today, it was published on 18th of Dec by Tony Davis on http://www.simple-talk.com. Its quite interesting post I loved reading it.
Here is a short brief:
Visual Basic v9 appeared on November 19. In the past, the new release of Microsoft’s longest-running language might have caused a stir, but it was part of Microsoft .NET Framework 3.5 and there were plenty of other distractions. The changes to VB itself were pretty minor: The ‘Inline IF’ was finally retired in favour of a true ternary IF. We got support for LINQ, Lambda expressions like those of Python, support for XML Literals, and Type Inference. Hopefully, the real changes to the language will come with Visual Basic v10, which will use the Dynamic Language Runtime, and benefit from experience gained in the development of IronPython. It is set to be released with Silverlight 2 as ‘Dynamic Visual Basic’. In the meantime C# continues to increase its dominance in the .NET world. Poor JScript.NET seems to be in terminal decline despite its high quality, though it is, like VB, promised a DLR makeover for SilverLight, and is likely to be renamed ‘Managed JScript’.

For .NET scripting, things already look a lot livelier, thanks in part to the Dynamic Language Runtime (DLR). IronPython and PowerShell have, in the past year, found good solid niches, thanks to their effortless access to the CLR and, in the case of IronPython, excellent tutorials and good compatibility with existing Python code. We all hoped for more with IronRuby, which now seems to be stuck in a pre-alpha limbo due more to legal than technical problems. This is disappointing for those of us who liked some of the ideas in Ruby on Rails. While we wait for Ruby, there is Boo and Nemerle to play with.
read the whole

Dec 13

Part 4 from Bill Horst’s series, now its functions turn.

Functions

SQL SELECT clauses often involve functions, which can be scalar or aggregate. An aggregate function is applied to a field over all the selected records, while a scalar function is called with individual values, one record at a time. It is possible to re-create both kinds of functions with VB LINQ expressions, but in very different ways.

Scalar Functions

Scalar functions are called on each record with whatever parameters are specified. They can appear various places in a SQL query, such as in the SELECT clause. The Scalar Functions available differ from system to system, but usually, there will be an analogous VB method that can be used. If using a Scalar Function in a LINQ Select clause, you will probably need to specify an alias as well (FirstThreeLetters, CurrentTime).

SQL

SELECT LEFT(ItemName, 3) FirstThreeLetters, NOW() CurrentTime
FROM OrderTable

VB

From Shipment In OrderTable _
Select FirstThreeLetters = Left(Shipment.ItemName, 3), CurrentTime = Now

In the above case, Left and Now are methods already built into VB, defined in Microsoft.VisualBasic.dll. This will likely be the case for most common scalar functions you will find in SQL statements. Even if the function you wish to call does not exist in VB already, you can define your own methods, too. However, user-defined methods cannot be used in a Database query, as they will throw an exception at runtime. In the below example, MyFunction is a user-defined function called from the Select clause.

VB

From Shipment In OrderTable _
Select MyFunction(Shipment.Cost, Shipment.ShippingZip)

Aggregate Functions

Aggregate functions are called on certain fields over an entire set of records, and return one value. In a SQL statement, they can appear in the SELECT clause. With VB LINQ, this concept appears a bit differently.

A VB LINQ expression usually begins with a From clause. However, they can also begin with an Aggregate clause. The Aggregate clause has the same syntax as a From clause, except that it starts with a different keyword. If a query starts with an Aggregate clause, it must end with an Into clause. An Into clause is a comma-delimited list of Aggregate function calls, with aliases that can accompany them. The below example shows a SQL SELECT statement that uses Aggregate functions, and an equivalent VB LINQ expression.

SQL

SELECT SUM(Cost) TotalCost, COUNT(*)
FROM OrderTable
WHERE OrderDate > “Sept-29-2007

VB

Aggregate Shipment In OrderTable _
Where Shipment.OrderDate > #9/29/2007# _
Into TotalCost = Sum(Shipment.Cost), Count()

read source

Dec 10

This article comes from Scott Mitchell at 4guysfromrolla.com. Its good post which I liked and wanna share with you:

Extension methods allow a developer to tack on her own methods to an existing class in the .NET Framework. For example, imagine that our developer created a method named StripHtml, that strips HTML elements from a string using a regular expression. By associating this method with the System.String class, it could be called as if it was one of the System.String class’s built-in methods:

Dim str As String = "<b>Hello, world!</b>"
Dim strippedString = str.StripHtml()

Creating the Extension Methods with Visual Basic
In order to create the extension methods in Visual Basic we need to first create a Module. For each extension method you want to create, add a method whose first input parameter is of the type that you want to add the extension method to. Moreover, prefix the method with the Extension() attribute.

The following Module named DateTimeHelpers contains two methods: ToRelativeToCurrentTimeString(DateTime) and ToRelativeToCurrentUtcTimeString(DateTime), both of which accept a DateTime instance as their first input parameter. The methods are also marked with the Extension() attribute (which is found in the System.Runtime.CompilerServices namespace). The two methods call the private ToRelativeString method, which returns the appropriate string message based on the difference in time between the two passed-in DateTime values.

Imports System.Runtime.CompilerServices
Imports Microsoft.VisualBasic
 
Namespace Helpers
    Public Module DateTimeHelpers
       <Extension()> _
       Public Function ToRelativeToCurrentTimeString(ByVal dt As DateTime) As String
            Return ToRelativeString(dt, DateTime.Now)
       End Function
 
       <Extension()> _
       Public Function ToRelativeToCurrentUtcTimeString(ByVal dt As DateTime) As String
            Return ToRelativeString(dt, DateTime.UtcNow)
       End Function
 
       Private Function ToRelativeString(ByVal timeInPast As DateTime, ByVal currentTime As DateTime) As String
            If timeInPast.Date <> currentTime.Date Then
                ' timeInPast happend more than a day ago... show the date & time
                Return timeInPast.ToString()
            Else
                ' timeInPast and currentTime happened on the same day...
                Dim secondsApart As Integer = Convert.ToInt32(currentTime.Subtract(timeInPast).TotalSeconds)
 
                ' See if the date dt is within the last hour...
                If secondsApart < 10 Then
                   Return "Seconds ago..."
                ElseIf secondsApart < 60 Then
                   Return "Less than a minute ago..."
                ElseIf secondsApart < 3600 Then
                   Return String.Format("{0:N0} minutes ago...", secondsApart / 60 + 1)
                End If
 
                ' Ok, the date is more than an hour old... show the time
                Return timeInPast.ToShortTimeString()
            End If
       End Function
    End Module
End Namespace

We can now call these extension methods from a DateTime instance. In order to use an extension method, we first need to add an Imports directive to the code file, importing the namespace where the extension methods reside (Helpers). Upon doing that, the extension method is visible in the IntelliSense drop-down list, as the following screen shot illustrates.

read source

Oct 24

Thats something really good! Now in the new Visual Studio 2008 you don’t have to use underscore when writing text on multiple lines. Here is an example how we used to write it:

Dim oldWay = "this is a string" & vbCrLf & _
               "with formatting" & vbCrLf & _
               "and stuff" & vbCrLf & _
               "look ma, underscores" & vbCrLf & _

Now we can do something like that:

Dim newWay = <string>
this is a string
with formatting
and stuff
look ma, no underscores!!!</string>

The text formatting is preserved as well. All you have to do is get the .Value of the XElement, which is the string literal. As you can see this is much cleaner than what we’re used to. And if you still like to see your string literals in the default reddish color, you can easily change the color settings for VB XML literals in Tools –> Options –> Environment –> Fonts and Colors, then select “VB XML Text” and set the custom color to RGB(163,21,21).

Even more, now we can embed expressions using the <%= syntax.

Dim simple = <string>
This is a simple text merge example:
Hello, <%= Environment.UserName %>
                     </string>

Here is Beth Massi’s post about these features! Thanks Beth!

Oct 19

This language specification corresponds to the version of Visual Basic that will ship in Visual Studio 2008. The spec covers the following major new features:

• Friend assemblies (InternalsVisibleTo)
• Relaxed delegates
• Local type inferencing
• Anonymous types
• Extension methods
• Nullable types
• Ternary operator
• Query expressions
• Object initializers
• Expression trees
• Lambda expressions
• Generic type inferencing
• Partial methods

The following features are not covered but should be shortly:

• XML Members
• XML Literals
• XML Namespaces

Although it will be updated again for the final release, the VB team wanted to get this out to the community now.
Here is the source
Here is the actual link for download

Jun 08

Today I came across that post at Visual Basic Team blog which is quite good. Enjoy it reading!
I recently received an email from a customer asking for clarification as to what the difference was between VB 9, VBx and Sliverlight. In particular, it seems as if we have been releasing so much information about cool new stuff that at least a few people have become confused, making them a bit nervous about the future of VB.

The customer had also expressed some concerns about upgrading from VS 2005 to Orcas (VS 2008), particularly because he was considering making an upgrade from VB 6 to VS 2005 and wanted to make sure he would be able to take advantage of Orcas when it was released.

I figured there may be other customers that have similar concerns, and so thought this would make a good blog post, particularly because it’s been a while since I’ve posted anything (J).

As a result I’ve included a few of the questions he asked (paraphrased) below, along with my answers.

I hope this helps.

What is the difference between VB 9 and VBx? Which one is the next version of Visual Studio?

Visual Basic 9 is the next version of Visual Basic. Visual Basic 10, or VBx as it’s sometimes called, is the version of Visual Basic that will follow VB 9. Currently VBx is in very early stages, and is a long way off from production. In fact, most of our development team is actively working on VB 9.

Why on earth would you start talking about VB 10 before you’ve even released VB 9? This is confusing.

The product cycle for VB 9 is starting to wind down. We recently released Beta 1 of Visual Studio Code Name “Orcas”, and are currently working on releasing Beta 2. As the product cycle starts to wind down, our language design team is starting to think about what the “next next” version of the product will look like. They do this mainly as a way to “keep the pipeline moving”. If they had to wait until VB 9 was 100% complete before they started thinking about VB 10, then there would end up being a significant delay from when we finished VB 9 until we could start working on VB 10. This is because designing a product, and coming up with a plan to develop it can be extremely time consuming. It requires us to come up with a design, create a schedule, make any necessary organizational changes, and ensure we have the right staffing levels, all before we start coding. By “overlapping” the early design work for VB 10 with the “end game” work for VB 9 we are able to better “bootstrap” the whole process, thus making the transition from one project to the next as smooth as possible.

As our design team comes up with designs they like to release information about them as early as possible. The earlier we can get information out to our customers, the earlier we can get feedback about the things we are doing. This helps us to build the products that actually meet our customers’ needs. One thing we’ve managed to learn over the years is that the best possible way we can learn what it is that our customers want is to engage with them early and often.

As a result, near the end of a product cycle we will release information about our plans for the version of the product to follow the one we are currently working on. This gives our customers the chance to comment on it and let us know what they think. We then take that feedback and use it to develop a more complete plan for what we want to do.

What is VB 10 going to be like? What is this Silverlight Thing I keep hearing about? Is Silverlight a replacement for Visual Studio?

Our plans for VBx and Silverlight are still very rough and are nowhere near complete. As our customers start to use VB 9 and provide us with feedback that data will drive exactly what we end up doing in VB 10. That being said, however, we do have some rough ideas of the things we would like to do.

Silverlight 1.1 is a new light weight version of the .NET Framework that will allow you to develop rich applications that run in a web browser using .NET languages. The basic idea is to allow you to replace client side java script with .NET enabled languages, allowing you to write both the client side and sever side portions of your web applications in the same language. It also allows you to use WPF (windows presentation foundation) and WCF (windows communication foundation) to create extremely rich and interactive web applications in a way that is much easier than what is possible using HTML, Ajax, Java Script, or Flash.

VB 10 is going to be the version of Visual Basic that will follow VB 9 (the “next next version”). It will include new features designed to make VB a really great language for developing SilverLight apps, as well as enhancements to many of the new feature we are delivering in VB 9, such as Linq. You should still be able to do all the things with VB 10 that you could do with both VB 9 and VB 8.

The migration from VB 6 to VS 2005 is non-trivial. If I upgrade to VS 2005 will I able to use VB 9 when it comes out, or will I have to scrap all my work? What about VB 10? Should I be worried about the future of VB?

The transition from VB 8.0 to VB 9.0 should be smooth and relatively painless. We have gone to great lengths to ensure this.

Our plan is to also make the migration from VB 9 to VB 10 equally painless.

Although the migration from VB 6 to VB.NET is a bit tough, we are actively working on making that easier as well. We have been releasing a “VB Interoperability Toolkit” that allows an application to be gradually migrated from VB 6 to VS 2005, rather than requiring the whole thing to be migrated at once.

You can get more information about it here:

http://msdn2.microsoft.com/en-us/vbasic/aa701257.aspx

As far as the future of VB, you should definitely not be worried.

Microsoft is committed to VB, and making it a great language for developing applications for our various platforms. The future of VB should be a bright one!
read original

May 28

Jared here again. For previous articles in this series please see

Thus far in the series we’ve only lifted variables that are declared in the same block/scope. What happens if we lift variables in different scope? The answer is that one closure class will be created for every unique scope where a lifted variable is declared and all of the variables in that scope that are lifted will be placed in that closure. Once again, examples speak best

    Sub Scope1()       Dim x = 5       Dim f1 = Function(ByVal z As Integer) x + z       Console.WriteLine(f1(5))       If x > 2 Then           Dim y = 6           Dim g = 7           Dim f2 = Function(ByVal z As Integer) z + y + g           Console.WriteLine(f2(4))       End If   End Sub

The code will end up looking like so …

    Class Closure1       Public x As Integer

       Function Lambda_f1(ByVal z As Integer)           Return x + z       End Function

   End Class

   Class Closure2       Public y As Integer       Public g As Integer

       Function Lambda_f2(ByVal z As Integer)           Return y + z + g       End Function   End Class

   Sub Scope1()       Dim c1 As New Closure1()       c1.x = 5       Console.WriteLine(c1.Lambda_f1(5))       If c1.x > 2 Then           Dim c2 As New Closure2()           c2.y = 6           c2.g = 7           Console.WriteLine(c2.Lambda_f2(4))       End If   End Sub

There are a couple of items to take away from this example.

  1. Only two closure classes were created even though three variables were lifted. The number of closures only depends on the number of scopes of all of the lifted declared variables.
  2. The closures are created at the begining of the scope they are associated and not at the begining of the method. This will be more important in the next part of the series.
  3. Each lambda instance is attached to the closure associated with the scope the lambda is declared in.

The next twist is what were to happen if the lambda “f2″ were to also use the variable “x”. As it’s currently written there is no association between Closure1 and Closure2 therefore there is no way for it to access the lifted variable. The answer is two fold. Firstly to reduce clutter I pasted the closure classes as if they were separate entries. In fact Closure2 would appear as a nested class of Closure1 in the real generated code.

Secondly if x were used inside of “f2″, the real use would be “c1.x”. That’s (almost) no different than “someOtherVar.x”. Therefore the instance of c1 will be lifted into Closure2.

Dim f2 = Function(ByVal z As Integer) z + y + g + x

Woud result in the following definition of Closure2 …

    Class Closure2       Public y As Integer       Public g As Integer       Public c1 As Closure1

       Function Lambda_f2(ByVal z As Integer)           Return y + z + g + c1.x       End Function   End Class

In deeply nested lambdas and scopes this type of lifting will continue recursively.

read original

May 04

Thats the second part of the closures set. Jaredpar goes even further and describes how method calls are handled in closures.
As stated in the previous article, the purpose of closures is to allow all operations inside a lambda or query expression that would normally be available inside the function or sub. To do this closures often need to capture (or lift) relevant variables from the function into the generated class.

There are 2 types of methods and method calls that closures have to handle.

1. Method calls to a shared method or methods on modules.
2. Method calls to instance members of a class“

Scenario #1

Below is an example of a method call inside a lambda expression for scenario #1.

Module M1

   Function MyValue() As Integer       Return 42   End Function

   Sub Example1()       Dim x = 5       Dim f = Function() x + MyValue()   End Sub

End Module

Here we are calling a module method inside a lambda. Module Methods or Shared methods can be called from anywhere because they require no specific variable for the call. This requires no special work from closures as the call can just be made naturally.

    Class Closure       Private x As Integer

       Function Lambda_f() As Integer           Return x + M1.MyValue       End Function   End Class 

Scenario #2

Calling an instance method is more difficult than a shared method because it requires the referenc “Me”. If you don’t type this specifically in code the VB Compiler will add it for you under the hood. To make this work the closures code will also “lift” the variable “Me” in the same way that it lifts normal variables in a function.

Calling a instance method inside a lambda expression is little difference than calling a member method on a variable used in a lambda. The only difference is the variable is “Me”. For example

Class C1   Private m_myValue As Integer

   Function MyValue() As Integer       Return m_myValue   End Function

   Sub Example2()       Dim x = 5       Dim f = Function() x + MyValue()   End SubEnd Class

In this case we need to access both “x” and “Me.MyValue()” from the closure. The generated code will create space for both of these variables and the transformed code in Example2 will store both of the values.

Class Closure   Private x As Integer   Private OriginalMe As C1

   Function Lambda_f()       Return x + OriginalMe.MyValue()   End FunctionEnd Class
    Sub Example2()       Dim c As New Closure       c.x = 5       c.OriginalMe = Me       Dim f = New Func(Of Integer)(AddressOf c.Lambda_f)   End Sub

As usual, the generated code is much uglier but this essentially what will be generated. That wraps it up for method calls. In the next part, I will discuss the variable liftetime and scoping issues that come into play with closures.

view original

May 03

Must read for everyone who is developing in VB! Jared Parsons tells us what he think closure is: “A closure is a feature which allows users to seemlessly access an environment (locals, parameters and methods) from more than one function.

and here are some samples:

Class C1  Sub Test()      Dim x = 5      Dim f = Function(ByVal y As Integer) x + y      Dim result = f(42)  End Sub

End Class

In this code we have a lambda expression which takes in a single parameter and adds it with a local variable. Lambda expressions are implemented as functions in VB (and C#). So now we have two functions, “Test” and “f”, which are accessing a single local variable. This is where closures come into play. Closures are responsible for making the single variable “x” available to both functions in a process that is referred to as “lifting the variable”.

To do this the compiler will take essentially 4 actions.

1. Create a class which will contain “x” in order to share it among both functions. Call it “Closure” for now
2. It will create a new function for the lambda expression in the class “Closure”. Call it “f” for now
3. Create a new instance of the class “Closure” inside the sub “Test”
4. Rewrite all access of “x” into the member “x” of “Closure”.
view original

May 01

Fast quote from The Visual Basic Team Blog! Their latest entry is about Visual Basic Language on Silverlight.

Supported…

  • Late Binding: One of the most definitive features of the VB language, I find late binding to be especially useful in writing Silverlight code-behind.
  • Conversions: Implicit and explicit conversion operators are available—Ctype, CStr, etc.
  • Linq: Currently, Linq over objects is supported
  • String utilities: Len(), InStr(), Mid(), UCase(), etc
  • VB Collection: Most folks either love it or hate it. A subset of generic collections is also supported. (Non-generic collections are considered obsolete for Silverlight.)
    • Dictionary(Of Key, Value)
    • List(Of T)
    • ArrayList (Obsolete)
    • BitArray (Obsolete)
    • Hashtable (Obsolete)
    • Queue (Obsolete)
    • SortedList (Obsolete)
    • Stack (Obsolete)
  • Math utilities: Rnd(), Random()
  • IIF()
  • Information utilities: Things like IsNumeric(), IsDate(), UBound(), LBound(), and so on
  • Date utilities: Now(), TimeOfDay(), Year(), etc
  • Constants: vbCrLf, vbTab, etc. Some of the more obscure constants have been removed, but the core set is included.
  • All core VB Language Constructs: Type Inference, anonymous delegates, Handles, etc

Not Currently Supported…

  • The My Namespace: We removed this for Alpha release because much of the existing My Namespace doesn’t make a ton of sense in Silverlight.
  • XML Literals: The compiler support for XML literals is present, but System.Xml.Linq (which the feature depends on) is not available in Silverlight 1.1.
  • COM Support: Silverlight plug-ins are not allowed to call COM components, so we removed the VB utilities related to COM (e.g., the COM Class attribute)
  • FileSystem Object (VB6 Compatibility): Direct access to the file system is not permitted, so these APIs were removed. Alternatively, you might check out System.IO.IsolatedStorage if you need to persist data locally

view original