Coding For a Living


A place to share and comment about coding for a living.

Opening the black box with Microsoft® Roslyn Mike McIntyre


Until now the VB and C# compilers have been black boxes, un accessible to Microsoft.Net developers.

Enter Microsoft Roslyn, “a set of APIs for exposing the Microsoft C# and Visual Basic .NET compilers as services available at runtime.”

This software is currently available as a community technology preview (CTP).

Roslyn can be imagined as a “compiler as a Windows service” which VB and C# developers can access through the new Roslyn APIs.

It allows the entire compile-execute process to be invoked from within .Net applications to, for example, give VB and C# a dynamic languages ability to generate and invoke code at runtime.

Or, how about incorporating Roslyn into a .NET application that accepts user input then uses Roslyn APIs to process the input (remember how good old class VB could evaluate a string?)

Roslyn is powerful but you won’t know how powerful it is until you try it out yourself.

Download it today!

Visual Basic WPF Using the Microsoft.Ink Library Mike McIntyre

Incorporating digital ink into Visual Basic WPF applications is done with the Microsoft.Ink DLL. Ink has evolved COM and Windows Forms to full integration into the WPF. You do not need to install separate SDKs or runtime libraries.

Below is an example of using procedural code with Ink. Ink can also be used with XAML.

Imports Microsoft.Ink Public Class Form1 Dim WithEvents myInkOverlay As InkOverlay Dim selectedMode As InkOverlayEditingMode Sub New() ' This call is required by the Windows Form Designer. InitializeComponent() myInkOverlay = New InkOverlay(Panel1) myInkOverlay.Enabled = True End Sub 'Back of pen erase Sub CursorInRangeEventHandler(ByVal sender As Object, ByVal e As InkCollectorCursorInRangeEventArgs) Handles myInkOverlay.CursorInRange 'If the pen is inverted, set mode to "delete" If (e.Cursor.Inverted) Then myInkOverlay.EditingMode = InkOverlayEditingMode.Delete Else 'Pen is not inverted, so select whatever mode the user requested myInkOverlay.EditingMode = selectedMode End If End Sub 'Ink mode radio button Sub InkRadioClickedHandler(ByVal sender As Object, ByVal e As EventArgs) Handles RadioButton1.CheckedChanged If (RadioButton1.Checked) Then selectedMode = InkOverlayEditingMode.Ink DoModeChange(InkOverlayEditingMode.Ink) End If End Sub 'Select mode radio button Sub SelectRadioClickedHandler(ByVal sender As Object, ByVal e As EventArgs) Handles RadioButton2.CheckedChanged If (RadioButton2.Checked) Then selectedMode = InkOverlayEditingMode.Select DoModeChange(InkOverlayEditingMode.Select) End If End Sub 'Delete mode radio button Sub DeleteRadioClickedHandler(ByVal sender As Object, ByVal e As EventArgs) Handles RadioButton3.CheckedChanged If (RadioButton3.Checked) Then selectedMode = InkOverlayEditingMode.Delete DoModeChange(InkOverlayEditingMode.Delete) End If End Sub 'Wire up delete mode buttons 'Delete entire stroke Sub StrokeRadioClickedHandler(ByVal sender As Object, ByVal e As EventArgs) Handles RadioButton4.CheckedChanged 'Can be called during Form construction, prior to myInkOverlay instantiation If (myInkOverlay Is Nothing) Then Return End If If (RadioButton4.Checked) Then myInkOverlay.EraserMode = InkOverlayEraserMode.StrokeErase End If End Sub 'Delete point(s) at pen tip only Sub PointRadioClickedHandler(ByVal sender As Object, ByVal e As EventArgs) Handles RadioButton5.CheckedChanged If (RadioButton5.Checked) Then myInkOverlay.EraserMode = InkOverlayEraserMode.PointErase End If End Sub Sub DoModeChange(ByVal NewMode As InkOverlayEditingMode) 'Can be called during Form construction, prior to myInkOverlay instantiation If (myInkOverlay Is Nothing) Then Return End If 'Switch the collection mode myInkOverlay.EditingMode = NewMode 'Switch the radio buttons to reflect new mode Select Case NewMode Case InkOverlayEditingMode.Ink RadioButton1.Checked = True RadioButton2.Checked = False RadioButton3.Checked = False Case InkOverlayEditingMode.Select RadioButton1.Checked = False RadioButton2.Checked = True RadioButton3.Checked = False Case InkOverlayEditingMode.Delete RadioButton1.Checked = False RadioButton2.Checked = False RadioButton3.Checked = True Case Else Throw New ArgumentOutOfRangeException() End Select End Sub End Class

Visual Basic ServiceContractAttribute Class Mike McIntyre

The recommended way to create a Windows Communication Foundation (WCF) contract is with an interface. Acontract specifies the collection and structure of messages required to access the operations the service offers.

The ServiceContractAttribute class is used to indicate that an interface or a class defines a service contract in a Windows Communication Foundation (WCF) application.

A class can support multiple contracts by deriving and implementing multiple interfaces decorated with the ServiceContract attribute.

<ServiceContract> _ Interface IMyContract <OperationContract> _ Function MyMethod() As String End Interface <ServiceContract> _ Interface IMyOtherContract <OperationContract> _ Sub MyOtherMethod() End Interface Class MyService Implements IMyContract Implements IMyOtherContract Public Function MyMethod() As String Implements IMyContract.MyMethod End Function Public Sub MyOtherMethod() Implements IMyOtherContract.MyOtherMethod End Sub End Class

Visual Basic 2012– Caller Information Mike McIntyre

New in Visual Basic 2012 is the caller information feature. This feature enables you to obtain information about the caller of a method.

By using Caller Info attributes, you can obtain information about the caller to a method. You can obtain file path of the source code, the line number in the source code, and the member name of the caller. This information is helpful for tracing, debugging, and creating diagnostic tools.

To obtain this information, you use attributes that are applied to optional parameters, each of which has a default value. 

For more information about using the Caller Information feature click:

       Caller Information (C# and Visual Basic)

Sample Use

' Imports System.Runtime.CompilerServices ' Imports System.Diagnostics Private Sub DoProcessing() TraceMessage("Something happened.") End Sub Public Sub TraceMessage(message As String, <CallerMemberName> Optional memberName As String = Nothing, <CallerFilePath> Optional sourcefilePath As String = Nothing, <CallerLineNumber()> Optional sourceLineNumber As Integer = 0) Trace.WriteLine("message: " & message) Trace.WriteLine("member name: " & memberName) Trace.WriteLine("source file path: " & sourcefilePath) Trace.WriteLine("source line number: " & sourceLineNumber) End Sub ' Sample output: ' message: Something happened. ' member name: DoProcessing ' source file path: C:\Users\username\Documents\Visual Studio 2012\Projects\CallerInfoVB\CallerInfoVB\Form1.vb ' source line number: 15

Visual Basic 2012–Iterators Mike McIntyre

Iterators are used to perform custom iteration over collections such as lists or arrays.

Iterators make it possible to use the iterator programming pattern. Wikipedia states: “In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements. The iterator pattern decouples algorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled.”

Iterators can be used to create a custom iteration over array or collection class.

Iterators can increase performance because they allow you to asynchronously consume the elements of a large collection.

Iterators can decrease memory use too.

Learn more by clicking: What's New for Visual Basic in Visual Studio 2012


Visual Basic 2012– Async Feature Mike McIntyre

The VisualBasic 2012 Async feature makes it simpler to make code asynchronous.

With it you can call into asynchronous methods WITHOUT callbacks and WITHOUT splitting your code into different methods.

The following example shows a Visual Basic async method.

' Add an Imports statement and a reference for System.Net.Http

Imports System.Net.Http
Class MainWindow
    ' Mark the event handler with async so you can use Await in it. 
    Private Async Sub StartButton_Click(sender As Object, e As RoutedEventArgs)
        ' Call and await separately. 
        'Task<int> getLengthTask = AccessTheWebAsync(); 
        '' You can do independent work here. 
        'int contentLength = await getLengthTask; 
        Dim contentLength As Integer = Await AccessTheWebAsync()
        ResultsTextBox.Text &=
            String.Format(vbCrLf & "Length of the downloaded string: {0}." & vbCrLf, contentLength)
    End Sub 
    ' Three things to note in the signature: 
    '  - The method has an Async modifier.  
    '  - The return type is Task or Task(Of T). (See "Return Types" section.) 
    '    Here, it is Task(Of Integer) because the return statement returns an integer. 
    '  - The method name ends in "Async."
    Async Function AccessTheWebAsync() As Task(Of Integer)
        ' You need to add a reference to System.Net.Http to declare client. 
        Dim client As HttpClient = New HttpClient()
        ' GetStringAsync returns a Task(Of String). That means that when you await the 
        ' task you'll get a string (urlContents). 
        Dim getStringTask As Task(Of String) = client.GetStringAsync("")
        ' You can do work here that doesn't rely on the string from GetStringAsync.
        ' The Await operator suspends AccessTheWebAsync. 
        '  - AccessTheWebAsync can't continue until getStringTask is complete. 
        '  - Meanwhile, control returns to the caller of AccessTheWebAsync. 
        '  - Control resumes here when getStringTask is complete.  
        '  - The Await operator then retrieves the string result from getStringTask. 
        Dim urlContents As String = Await getStringTask
        ' The return statement specifies an integer result. 
        ' Any methods that are awaiting AccessTheWebAsync retrieve the length value. 
        Return urlContents.Length
    End Function 
    Sub DoIndependentWork()
        ResultsTextBox.Text &= "Working . . . . . . ." & vbCrLf
    End Sub 
End Class 
' Sample Output: 
' Working . . . . . . . 
' Length of the downloaded string: 41763.

To learn more click: Asynchronous Programming with Async and Await