Coding For a Living

rss

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


Possible Features of C#.6 and VB.12 Mike McIntyre

Below are some features that may be a part of C#.6 and VB.12.  For current information visit Language feature implementation status for Dev14

Feature status as of 10/3/2014:

Feature

Example

C#

VB

Primary constructors

class Point(int x, int y) { … }

No

No

Auto-property initializers

public int X { get; set; } = x;

Done

Exists

Getter-only auto-properties

public int Y { get; } = y;

Done

Done

Ctor assignment to getter-only autoprops

Y = 15

Done

Done

Parameterless struct ctors

Structure S : Sub New() : End Sub : End Structure

Done

Done

Using static members

using System.Console; … Write(4);

Done

Exists

Dictionary initializer

new JObject { ["x"] = 3, ["y"] = 7 }

Done

No

Indexed member initializer

new JObject { $x = 3, $y = 7 }

No

No

Indexed member access

c.$name = c.$first + " " + c.$last;

No

Exists

Declaration expressions

int.TryParse(s, out var x);

No

No

Await in catch/finally

try … catch { await … } finally { await … }

Done

Maybe

Exception filters

catch(E e) if (e.Count > 5) { … }

Done

Exists

Typecase

Select Case o : Case s As String : …

No

Maybe

Guarded cases

Select Case i : Case Is > 0 When i Mod 2 = 0

No

No

Partial modules

Partial Module M1

N/A

Done

Partial interfaces

Partial Interface I1

Exists

Done

Multiline string literals

"HelloWorld"

Exists

Done

Year-first date literals

Dim d = #2014-04-03#

N/A

Done

Binary literals

0b00000100

No

No

Digit separators

0xEF_FF_00_A0

No

No

Line continuation comments

Dim addrs = From c in Customers ' comment

N/A

Done

TypeOf IsNot

If TypeOf x IsNot Customer Then …

N/A

Done

Expression-bodied members

public double Dist => Sqrt(X * X + Y * Y);

Done

No

Event initializers

new Customer { Notify += MyHandler };

No

No

Null propagation

customer?.Orders?[5]?.$price

Done

Planned

Semicolon operator

(var x = Foo(); Write(x); x * x)

No

No

Private protected

private protected string GetId() { … }

No

No

Params IEnumerable

int Avg(params IEnumerable numbers) { … }

Maybe

Maybe

Constructor Inference

new Tuple(3, "three", true);

No

No

String interpolation

"\{p.First} \{p.Last} is \{p.Age} years old."

Planned

Planned

TryCast for nullable

Dim x = TryCast(u, Integer?)

Exists

No

Delegate combination with +

d1 += d2

Exists

No

Implicit implementation

Class C : Implicitly Implements I

Exists

No

nameof operator

string s = nameof(Console.Write);

Done

Planned

Strict modules

Strict Module M

Exists

No

Faster CInt

Dim x = CInt(Math.Truncate(d)) |

Exists

No

#pragma

#Disable Warning BC40008

Done

Done

Checked and Unchecked blocks

Checked : x += 1 : End Checked

Exists

No

Field targets on autoprops

Serializable> Property p As Integer

Maybe

Maybe

If(b,e1,e2) uses type context

Dim x As Integer? = If(b,1,Nothing)

N/A

No


What is the Microsoft .NET Compiler Platform? Mike McIntyre

The Microsoft .NET Compiler Platform, better known as Roslyn, consists of two compilers (one for C# and one for Visual Basic) with rich code analysis APIs.

Roslyn provides compilers as services which can be used to create code focused tools and applications. This creates opportunities for innovation in areas such as meta-programming, code generation and transformation, scripting, interactive use of the C# and VB languages, and embedding of C# and VB in domain specific languages.

Roslyn exposes the C# and Visual Basic compiler’s code analysis to you as a consumer by providing an API layer that mirrors a traditional compiler pipeline.

image

Each phase of this pipeline is now a separate component. First the parse phase, where source is tokenized and parsed into syntax that follows the language grammar. Second the declaration phase, where declarations from source and imported metadata are analyzed to form named symbols. Next the bind phase, where identifiers in the code are matched to symbols. Finally, the emit phase, where all the information built up by the compiler is emitted as an assembly.

In April 2014 Roslyn went open source.

Get started with Roslyn


VB RSS Feed Aggregator Mike McIntyre

A RSS feed aggregator aggregates syndicated web content such as online newspapers, blogs, podcasts, and video blogs (vlogs) for various purposes e.g. to provide one location for easy viewing.

The VB module provides a code sample for one way you can create a RSS feed aggregator with VisualBasic.

Module Module1
    Const feedUrl As String = "http://+:8086/VBfeeds/"


    Sub Main()
        Dim listener As New HttpListener

        listener.Prefixes.Add(feedUrl)
        listener.Start()

        'Open a browser pointing at the feeds being served.
        System.Diagnostics.Process.Start("iexplore.exe", "http://localhost:8086/VBfeeds/")

        'Serve requests.
        While True
            Dim context As HttpListenerContext = listener.GetContext()
            Dim body As XElement = GetReplyBody()
            context.Response.ContentType = "text/xml"

            Using writer As XmlWriter = New XmlTextWriter(context.Response.OutputStream, System.Text.Encoding.UTF8)
                body.WriteTo(writer)
            End Using
        End While

    End Sub

    Function GetReplyBody() As XElement
        Dim feeds() As String = {"http://blogs.msdn.com/vbteam/rss.aspx?Tags=VB6_5F00_Migration_2F00_
                                 "http://blogs.msdn.com/vsdata/rss.xml", _
                                 "http://blogs.msdn.com/vbteam/rss.aspx?Tags=IDE&AndTags=1"}

        Return 
                   
                       VB Genius
                       http://+:8086/VBfeeds/
                       VB Team Members
                       XLinq-based RSS aggregator using VB Only Super Cool XML Literals Feature
                       
                   
               
    End Function
End Module

Use Linq with Reflection in Visual Basic Mike McIntyre

The Reflector class below generates an HTML document outlining the public API for a given assembly.

First, an XML document is emitted in memory (see Emit*()).

The document captures the relevant aspects of the assembly's metadata.

Next, an HTML document is extracted from the XML document (see Extract*()).

I love Linq.

Public Class Reflector
    Public document As XDocument

    Public Sub Reflect(ByVal assemblyFile As String)
        Dim Assembly As Assembly = Assembly.LoadFrom(assemblyFile)
        document = New XDocument(EmitAssembly(Assembly))
    End Sub

    Public Sub Transform(ByVal writer As XmlWriter)
        If document Is Nothing Then Return
        Dim assembly As XElement = document.Element("assembly")
        Dim transform As New XDocument(ExtractAssembly(assembly))
        transform.Save(writer)
    End Sub

    Public Function EmitAssembly(ByVal assembly As Assembly) As XElement
        Return 
                   
               
    End Function

    Public Function EmitNamespace(ByVal ns As String, ByVal types As IEnumerable(Of Type)) As XElement
        Return 
                   
               
    End Function

    Public Function EmitType(ByVal type As Type) As XElement
        Return < name=>
                   
                   
                   
                   
                   
                   
                   
                   
                   
               
    End Function

    Public Function EmitGenericArguments(ByVal args As IEnumerable(Of Type)) As IEnumerable(Of XElement)
        Return From arg In args _
                Select 
                           
                       
    End Function

    Public Function EmitModifiers(ByVal type As Type) As XElement
        Dim builder As StringBuilder = New StringBuilder()
        If type.IsPublic Then
            builder.Append("public")
        ElseIf type.IsNestedPublic Then
            builder.Append("public")
        ElseIf type.IsNestedFamily Then
            builder.Append("protected")
        ElseIf type.IsNestedFamANDAssem Then
            builder.Append("protected internal")
        End If
        If type.IsSealed Then builder.Append(" sealed")
        If type.IsAbstract Then builder.Append(" abstract")

        Return 
                   
               
    End Function

    Public Function EmitExtends(ByVal baseType As Type) As XElement
        If baseType Is Nothing Or baseType Is GetType(Object) Or baseType Is GetType(ValueType) Or baseType Is GetType(System.Enum) Then Return Nothing
        Return 
                   
               
    End Function

    Public Function EmitImplements(ByVal ifaces As IEnumerable(Of Type)) As IEnumerable(Of XElement)
        Return From iface In ifaces _
               Select 
                          
                      
    End Function

    Public Function EmitDeclaringType(ByVal declaringType As Type) As XElement
        If declaringType Is Nothing Then Return Nothing
        Return 
                   
               
    End Function

    Public Function EmitNestedTypes(ByVal ntypes As IEnumerable(Of Type)) As IEnumerable(Of XElement)
        Return From ntype In ntypes _
                Where GetVisible(ntype) _
                Select EmitType(ntype)
    End Function

    Public Function EmitMethods(ByVal metds As IEnumerable(Of MethodBase)) As IEnumerable(Of XElement)
        Return From metd In metds _
        Where GetVisible(metd) _
        Select 
                   
                   
                   
                   
                   
               
    End Function

    Public Function EmitProperties(ByVal props As IEnumerable(Of PropertyInfo)) As IEnumerable(Of XElement)

        Return From prop In props _
                    Where GetVisible(prop.GetGetMethod()) Or _
                    GetVisible(prop.GetSetMethod()) _
                    Select 
                               
                               
                           


    End Function

    Public Function EmitReference(ByVal type As Type) As IEnumerable(Of Object)

        If (Not type.IsGenericType) Then
            Return New Object() {New XAttribute("name", type.Name), _
                                 New XAttribute("namespace", GetNamespace(type))}
        Else
            Return New Object() {New XAttribute("name", type.Name), _
                                 New XAttribute("namespace", GetNamespace(type)), _
                                 EmitGenericArguments(type.GetGenericArguments())}
        End If
    End Function

    Public Function EmitModifiers(ByVal metd As MethodBase) As XElement
        Dim builder As StringBuilder = New StringBuilder()
        If metd.IsPublic Then
            builder.Append("public")
        ElseIf metd.IsFamily Then
            builder.Append("protected")
        ElseIf metd.IsFamilyAndAssembly Then
            builder.Append("protected internal")
        End If

        If metd.IsAbstract Then builder.Append(" abstract")
        If metd.IsStatic Then builder.Append(" static")
        If metd.IsVirtual Then builder.Append(" virtual")

        Return New XElement("modifiers", builder.ToString())
    End Function

    Public Function EmitReturnType(ByVal metd As MethodBase) As XElement
        Dim metdInfo As MethodInfo = TryCast(metd, MethodInfo)
        If metdInfo Is Nothing Then Return Nothing
        Return 
                   
               
    End Function

    Public Function EmitExtension(ByVal metd As MethodBase) As XElement
        Return 
               
    End Function

    Public Function EmitParameters(ByVal parms As IEnumerable(Of ParameterInfo)) As IEnumerable(Of XElement)
        Return From parm In parms _
               Select 
                          
                              
                          
                      
    End Function

    Public Shared Function GetNamespace(ByVal type As Type) As String
        Dim ns As String = type.Namespace
        Return If(ns IsNot Nothing, ns, String.Empty)
    End Function

    Public Shared Function GetVisible(ByVal type As Type) As Boolean
        Return type.IsPublic Or type.IsNestedPublic Or type.IsNestedFamily Or type.IsNestedFamANDAssem
    End Function

    Public Shared Function GetVisible(ByVal metd As MethodBase) As Boolean
        Return metd IsNot Nothing AndAlso (metd.IsPublic Or metd.IsFamily Or metd.IsFamilyAndAssembly)
    End Function

    Public Function ExtractAssembly(ByVal assembly As XElement) As XElement
        Return 
                   
                       
                           
                       
                   
                   
                       

Assembly:

End Function Public Function ExtractNamespace(ByVal ns As XElement) As XElement Return

Namespace:

End Function Public Function ExtractType(ByVal type As XElement) As XElement Return

End Function Public Function ExtractModifiers(ByVal element As XElement) As String Return element.Element("modifiers").Value End Function Public Function ExtractName(ByVal element As XElement) As String Dim name As String = element.Attribute("name").Value Dim i As Integer = name.LastIndexOf("`") If i > 0 Then name = name.Substring(0, i) ' fix generic name Return name End Function Public Function ExtractGenericArguments(ByVal element As XElement) As String If Not element.Elements("genericArgument").Any() Then Return String.Empty Dim builder As StringBuilder = New StringBuilder("<") For Each genericArgument As XElement In element.Elements("genericArgument") If builder.Length <> 1 Then builder.Append(", ") builder.Append(ExtractReference(genericArgument)) Next builder.Append(">") Return builder.ToString() End Function Public Function ExtractReference(ByVal element As XElement) As String Return ExtractName(element) + ExtractGenericArguments(element) End Function Public Function ExtractInherits(ByVal type As XElement) As String If Not type.Elements("extends").Concat(type.Elements("implements")).Any() Then Return String.Empty Dim builder As New StringBuilder() For Each [inherits] As XElement In type.Elements("extends").Concat(type.Elements("implements")) If builder.Length = 0 Then builder.Append(" : ") Else builder.Append(", ") End If builder.Append(ExtractReference([inherits])) Next Return builder.ToString() End Function Public Function ExtractConstructors(ByVal type As XElement) As XElement Dim ctors = From ctor In type.Elements("method") _ Where ExtractName(ctor) = ".ctor" _ Select
  • If Not ctors.Any() Then Return Nothing Return

    Constructors:

      End Function Public Function ExtractProperties(ByVal type As XElement) As XElement Dim props = From prop In type.Elements("property") _ Let propName = ExtractName(prop) _ Let getter = "get_" + propName _ Let setter = "set_" + propName _ Select
      If Not props.Any() Then Return Nothing Return

      Properties:

      End Function Public Function ExtractOperators(ByVal type As XElement) As XElement Dim ops = From op In type.Elements("method") _ Let name = ExtractName(op) _ Where name.StartsWith("op_") _ Select
      If Not ops.Any() Then Return Nothing Return

      Operators:

      End Function Public Function ExtractMethods(ByVal type As XElement) As XElement Dim metds = From metd In type.Elements("method") _ Let name = ExtractName(metd) _ Where name <> ".ctor" And _ Not type.Elements("property").Where(Function(prop) name = "get_" & ExtractName(prop) Or _ name = "set_" + ExtractName(prop)).Any() And Not name.StartsWith("op_") _ Select ExtractMethod(metd) If Not metds.Any() Then Return Nothing Return New XElement("div", New XElement("h4", "Methods: "), New XElement("ul", metds)) End Function Public Function ExtractMethod(ByVal metd As XElement) As XElement Return
    • End Function Public Function ExtractParameters(ByVal metd As XElement) As String Dim builder As StringBuilder = New StringBuilder("(") For Each parm As XElement In metd.Elements("parameter") If builder.Length = 1 Then If metd.Element("extension") IsNot Nothing Then builder.Append("this ") Else builder.Append(", ") End If builder.Append(ExtractReference(parm.Element("parameterType"))) builder.Append(" ") builder.Append(ExtractName(parm)) Next builder.Append(")") Return builder.ToString() End Function End Class


      Windows Store apps Dev Center 2013 Mike McIntyre

      Have you checked out the Windows Store apps Dev Center lately?

      It’s been filled with excellent resources for learning about and developing Windows Store apps. From code, to design guidelines, it’s chuck full of what you need to develop Windows Store Apps.

      Windows 8.1

      Windows 8.1

      Feature guide

      Product guide

      Getting started

      Support forums

      Design

      Design

      Design downloads

      Our design principles

      Index UX guidelines

      iPad to Windows Store app

      Migrate

      Migrate

      iOS

      Android

      Windows 8

      WPF/Silverlight

      Develop

      Develop

      Samples

      API reference

      Downloads

      Certification requirements


      Visual Basic If Operator Mike McIntyre

      It looks like a function but it is an operator.  The Visual Basic If operator provides the functionality of the IIF function and more - including short-circuiting. It can be use as a ternary operator which mimics the functionality of the IIF function while adding some more to it, and as a binary operator which provides a comparison/assignment feature. image

      The operator uses short-circuit evaluation to conditionally return one of two values. The If operator can be called with three arguments or with two arguments.

      When If is called by using three arguments, the first argument must evaluate to a value that can be cast as a Boolean. That Boolean value will determine which of the other two arguments is evaluated and returned.

      ' This statement prints TruePart, because the first argument is true. Console.WriteLine(If(True, "TruePart", "FalsePart")) ' This statement prints FalsePart, because the first argument is false. Console.WriteLine(If(False, "TruePart", "FalsePart")) Dim number = 3 ' With number set to 3, this statement prints Positive. Console.WriteLine(If(number >= 0, "Positive", "Negative")) number = -1 ' With number set to -1, this statement prints Negative. Console.WriteLine(If(number >= 0, "Positive", "Negative"))

      Gadgeteer Book–Learn to Program With VB & .Net Mike McIntyre

      This book is a free resource from Microsoft Press which helps students learn to program with the .Net Gadgeteer, a device originated at the Microsoft Research in Cambridge, U.K.. image

      The Gadgeteer book explains how to program with VB and .Net using the FEZ Cerberus Tinker Kit modules such as the mainboard, USPClientSP power module, the Joystick, the LED strip, and the Display N18 module.

      Students plug together modules then use Visual Studio 2012 or Visual Studio 2010 to build a .Net Gadgeteer project.

      The Visual Studio project includes lots of visual tools for connecting and configuring modules.

      image 

      I love this book and the FEZ Tinker Kit. 

      Back in the day I remember buying electronic parts, wiring up boards and hooking up devices based on computer magazine articles.

      This kit gives a similar ‘hands on experience’ with the power of VB and .NET added in. 

      This book and the FEZ Cerberus Tinker Kit are highly recommended for the young nerds in your life.  The book is free and the kit costs around $100 U.S.


      What can you do with Roslyn? Scripting Mike McIntyre

      With Microsoft Roslyn you can write applications that evaluate code at runtime.

      While it’s been possible to implement scripting since the release of .Net it’s not been easy. Check out Brian Rasmussen’s blog on scripting:

           Learn about the Roslyn scripting API


      DB Schema Design–Rethinking ‘Type’ Tables Pt 1 Mike McIntyre

      If you are a typical business application developer you probably work with a database which is cluttered with ‘type’ tables e.g. InvoiceType, CustomerType, PaymentType, CreditCartType, OrderType, ItemType, ProductType – which all have a schemas similar to these:

           image

      There are the same number of columns in each type table above. 

      The data type of the columns are the same in all the tables. 

      Some column names are the same in all the tables. 

      Columns names that are not the same in all tables do follow the same naming rule in each table e.g. ItemTypeId, OrderTypeId, ListTypeId which all end with ‘Id’.

      Given how similar these tables are, why not use 2-3 tables for all standard ‘type’ data, maybe something like this?

       

           image

      More to follow in part 2 of ‘DB Schema Design–Rethinking ‘Type’ Tables’


      Return a string, and just a string, from HTTP Post Mike McIntyre

      You want to return a string, just a string, from an HTTP POST call.

      You code it like this:

      Response.Write("Hello World")

      The HTTP POST returns:

      All you wanted was “Hello World”.

      You should have coded it like this:

      Response.Write("Hello World") ' The Response.End method causes the Web server to stop processing the script and return the current result. The remaining contents of the file are not processed. Response.End()