Best vb.net questions in April 2011

Is .( ever legal in C# or VB.Net?

17 votes

Can the sequence .( ever appear in C# or VB.Net code?
(Not in a string, comment, or XML literal, EDIT: or preprocessor directive)

I'm reasonably certain that the answer is no, but I'd like to make sure.

The only places that . appears in the grammar are:

real-literal:
    decimal-digits   .   decimal-digits ...
    .   decimal-digits ...

namespace-or-type-name:
    namespace-or-type-name   .   identifier ...


member-access:
    primary-expression   .   identifier ...
    predefined-type   .   identifier ...

qualified-alias-member   .   identifier ...

base-access:
    base   .   identifier

unbound-type-name:
    unbound-type-name   .   identifier

qualified-identifier: 
    qualified-identifier   .   identifier

member-name:
    interface-type   .   identifier

indexer-declarator:
    type   interface-type   .   this   

(The ... means I have elided the remainder of the production rule.) In none of these cases is a .( valid as . is either followed by digits, a valid identifier, or the keyword this.

Is this an error in the VB.Net compiler or by design?

16 votes

I've found a difference in overload resolution between the C# and the VB-compiler. I'm not sure if it's an error or by design:

Public Class Class1
    Public Sub ThisBreaks()
        ' these works '
        Foo(Of String)(Function() String.Empty) 'expression overload '
        Foo(String.Empty) 'T overload '

        ' this breaks '
        Foo(Function() String.Empty)
    End Sub

    Public Sub Foo(Of T)(ByVal value As T)

    End Sub

    Public Sub Foo(Of T)(ByVal expression As Expression(Of Func(Of T)))

    End Sub
End Class

Note that it doesn't matter if the overloaded Foo-methods are defined in VB or not, the only thing that matters is that the call site is in VB.

The VB-compiler will report an error:

Overload resolution failed because no accessible 'Foo' is most specific for these arguments:

'Public Sub Foo(Of String)(expression As System.Linq.Expressions.Expression(Of System.Func(Of String)))': Not most specific.

'Public Sub Foo(Of )(value As )': Not most specific.


Adding the C# code which works for comparison:

class Class1
{
    public void ThisDoesntBreakInCSharp()
    {
        Foo<string>(() => string.Empty);
        Foo(string.Empty);
        Foo(() => string.Empty);
    }

    public void Foo<T>(T value)
    {

    }

    public void Foo<T>(Expression<Func<T>> expression)
    {

    }
}

I'm pretty sure I've found the reason for this and it is not a short coming of the VB-compiler but it is a short coming of the C# compiler.

Consider the following which is legal in VB:

Dim foo = Function() String.Empty

The equivalent would not be legal in c#:

var foo = () => string.Empty;

So, type inference is a bit stronger in VB, because of this the argument in the example Function() String.Empty can be inferred to Function(Of String) which would be applicable to the Foo(Of T)(ByVal value As T) overload.

In C# this can not happen since the () => string.Empty can never be inferred without context, it can be inferred in the expression overload but not in the T-overload.

Is there a way to serialize multiple XElements onto the same line?

12 votes

I'm dealing with the dreaded <Run/> in Silverlight 3 and having to programmatically create a <TextBlock> and its inlines:

Why dreaded? Because it doesn't work, I guess, the way you'd expect. Exhibit A, below, should produce

BARN
(with fancy colors for each character), but instead it produces:
B A R N

EXHIBIT A

<TextBlock FontFamily="Comic Sans MS" FontSize="88">
    <Run Foreground="#A200FF">B</Run>
    <Run Foreground="#FF0000">A</Run>
    <Run Foreground="#FFC000">R</Run>
    <Run Foreground="#FFFF00">N</Run>
</TextBlock>

What does produce the desired result, however, is:

EXHIBIT B

<TextBlock FontFamily="Comic Sans MS" FontSize="88">
    <Run Foreground="#A200FF">B</Run><Run Foreground="#FF0000">A</Run><Run Foreground="#FFC000">R</Run><Run Foreground="#FFFF00">N</Run>
</TextBlock>

Stupid, eh? Anyway, this is documented @ XAML Processing Differences Between Silverlight 3 and Silverlight 4 under Whitespace Handling where it says:

Silverlight 3 treats whitespace more literally in a wider range, including some cases where CLRF is considered significant. This sometimes led to file-format XAML with omitted CRLF in order to avoid unwanted whitespace in the presentation, but which was not human-readable in editing environments. Silverlight 4 uses a more intuitive significant-whitespace model that is similar to WPF. This model collapses file-formatting whitespace in most cases, with exception of certain CLR-attributed containers that treat all whitespace as significant. This whitespace model gives editing environments greater freedom to introduce whitespace that can improve XAML code formatting. Also, Silverlight 4 has text elements that permit even greater control over whitespace presentation issues.

Great, but I'm not using SL4 because I'm creating a WP7 app programmatically. Yeah, my XAML is generated. Using XML Literals. Then sent to a string. Like this:

Dim r1 As XElement = <Run Foreground="#A200FF">B</Run>
Dim r2 As XElement = <Run Foreground="#FF0000">A</Run>
Dim r3 As XElement = <Run Foreground="#FFC000">R</Run>
Dim r4 As XElement = <Run Foreground="#FFFF00">N</Run>
Dim tb = <TextBlock FontFamily="Comic Sans MS" FontSize="88">
             <%= r1 %><%= r2 %><%= r3 %><%= r4 %>
         </TextBlock>
Dim result = tb.ToString

After all this, here's my question: How can I produce Exhibit B instead of Exhibit A. That textblock will become part of a greater number of elements in a XAML page, so the .ToString part isn't exactly accurate in this location - that happens when all of the XAML for the user control page is kicked out to file.


EDIT (6 May 2011): A little progress and a bounty


I've made a bit of progress as below, but I'm running up against a mental block here on how to accomplish an unusual split and processing of XML to output a string. Take this new example:

<Canvas>
  <Grid>
    <TextBlock>
      <Run Text="r"/>
      <Run Text="u"/>
      <Run Text="n"/>
    </TextBlock>
    <TextBlock>
      <Run Text="far a"/>
      <Run Text="way"/>
      <Run Text=" from me"/>
    </TextBlock>
  </Grid>
  <Grid>
    <TextBlock>
      <Run Text="I"/>
      <Run Text=" "/>
      <Run Text="want"/>
      <LineBreak/>
    </TextBlock>
    <TextBlock>
      <LineBreak/>
      <Run Text="...thi"/>
      <Run Text="s to"/>
      <LineBreak/>
      <Run Text=" work"/>
    </TextBlock>
  </Grid>
</Canvas>

I want the output string to be:

<Canvas>
  <Grid>
    <TextBlock>
      <Run Text="r"/><Run Text="u"/><Run Text="n"/>
    </TextBlock>
    <TextBlock>
      <Run Text="far a"/><Run Text="way"/><Run Text=" from me"/>
    </TextBlock>
  </Grid>
  <Grid>
    <TextBlock>
      <Run Text="I"/><Run Text=" "/><Run Text="want"/>
      <LineBreak/>
    </TextBlock>
    <TextBlock>
      <LineBreak/>
      <Run Text="...thi"/><Run Text="s to"/>
      <LineBreak/>
      <Run Text=" work"/>
    </TextBlock>
  </Grid>
</Canvas>

I've been looking at the XMLWriter and XMLWriterSettings, based on Eric White's post, which seems to be a good start for the runs (not including the potential <LineBreak/>s yet, which also stumps me). Like this:

Sub Main()
    Dim myXML As XElement = <Canvas>
                                <Grid>
                                    <TextBlock>
                                        <Run Text="r"/>
                                        <Run Text="u"/>
                                        <Run Text="n"/>
                                    </TextBlock>
                                    <TextBlock>
                                        <Run Text="far a"/>
                                        <Run Text="way"/>
                                        <Run Text=" from me"/>
                                    </TextBlock>
                                </Grid>
                            </Canvas>
    Console.Write(ToXMLString(myXML))
    Console.ReadLine()
End Sub
Public Function ToXMLString(xml As XElement) As String
    Dim tb As XElement = xml.Elements.<TextBlock>.FirstOrDefault
    Dim xmlWriterSettings As New XmlWriterSettings
    XmlWriterSettings.NewLineHandling = NewLineHandling.None
    XmlWriterSettings.OmitXmlDeclaration = True
    Dim sb As New StringBuilder
    Using xmlwriter As XmlWriter = xmlwriter.Create(sb, XmlWriterSettings)
        tb.WriteTo(xmlwriter)
    End Using
    Return sb.ToString
End Function

But I'm having a huge problem going much further with figuring out how to parse this to produce the desired output above.

The key to solving this problem is to write a recursive function that iterates through the XML tree, writing the various elements and attributes to specially created XmlWriter objects. There is an 'outer' XmlWriter object that writes indented XML, and an 'inner' XmlWriter object that writes non-indented XML.

The recursive function initially uses the 'outer' XmlWriter, writing indented XML, until it sees the TextBlock element. When it encounters the TextBlock element, it creates the 'inner' XmlWriter object, writing the child elements of the TextBlock element to it. It also writes white space to the 'inner' XmlWriter.

When the 'inner' XmlWriter object is finished with writing the TextBlock element, the text that the writer wrote is written to the 'outer' XmlWriter using the WriteRaw method.

The advantages of this approach is that there is no post-processing of the XML. It is extremely difficult to post-process XML and be certain that you have properly handled all cases, including arbitrary text in CData nodes, etc. All of the XML is written using only the XmlWriter class, thereby ensuring that this will always write valid XML. The only exception to this is the specially crafted white-space that is written using the WriteRaw method, which achieves the desired indenting behavior.

One key point is that the 'inner' XmlWriter object's conformance level is set to ConformanceLevel.Fragment, because the 'inner' XmlWriter needs to write XML that does not have a root element.

To achieve the desired formatting of Run elements (i.e. Run elements that are adjacent have no insignificant white space between them), the code uses the GroupAdjacent extension method. Some time ago, I write a blog post on the GroupAdjacent extension method for VB.

When you run the code using the specified sample XML, it outputs:

<Canvas>
  <Grid>
    <TextBlock>
      <Run Text="r" /><Run Text="u" /><Run Text="n" />
    </TextBlock>
    <TextBlock>
      <Run Text="far a" /><Run Text="way" /><Run Text=" from me" />
    </TextBlock>
  </Grid>
  <Grid>
    <TextBlock>
      <Run Text="I" /><Run Text=" " /><Run Text="want" />
      <LineBreak />
    </TextBlock>
    <TextBlock>
      <LineBreak />
      <Run Text="...thi" /><Run Text="s to" />
      <LineBreak />
      <Run Text=" work" />
    </TextBlock>
  </Grid>
</Canvas>

Following is the complete listing of the VB.NET example program. In addition, I've written a blog post, Custom Formatting of XML using LINQ to XML, which presents the equivalent C# code.

`

Imports System.Text
Imports System.Xml

Public Class GroupOfAdjacent(Of TElement, TKey)
    Implements IEnumerable(Of TElement)

    Private _key As TKey
    Private _groupList As List(Of TElement)

    Public Property GroupList() As List(Of TElement)
        Get
            Return _groupList
        End Get
        Set(ByVal value As List(Of TElement))
            _groupList = value
        End Set
    End Property

    Public ReadOnly Property Key() As TKey
        Get
            Return _key
        End Get
    End Property

    Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of TElement) _
            Implements System.Collections.Generic.IEnumerable(Of TElement).GetEnumerator
        Return _groupList.GetEnumerator
    End Function

    Public Function GetEnumerator1() As System.Collections.IEnumerator _
            Implements System.Collections.IEnumerable.GetEnumerator
        Return _groupList.GetEnumerator
    End Function

    Public Sub New(ByVal key As TKey)
        _key = key
        _groupList = New List(Of TElement)
    End Sub
End Class

Module Module1
    <System.Runtime.CompilerServices.Extension()> _
    Public Function GroupAdjacent(Of TElement, TKey)(ByVal source As IEnumerable(Of TElement), _
                ByVal keySelector As Func(Of TElement, TKey)) As List(Of GroupOfAdjacent(Of TElement, TKey))
        Dim lastKey As TKey = Nothing
        Dim currentGroup As GroupOfAdjacent(Of TElement, TKey) = Nothing
        Dim allGroups As List(Of GroupOfAdjacent(Of TElement, TKey)) = New List(Of GroupOfAdjacent(Of TElement, TKey))()
        For Each item In source
            Dim thisKey As TKey = keySelector(item)
            If lastKey IsNot Nothing And Not thisKey.Equals(lastKey) Then
                allGroups.Add(currentGroup)
            End If
            If Not thisKey.Equals(lastKey) Then
                currentGroup = New GroupOfAdjacent(Of TElement, TKey)(keySelector(item))
            End If
            currentGroup.GroupList.Add(item)
            lastKey = thisKey
        Next
        If lastKey IsNot Nothing Then
            allGroups.Add(currentGroup)
        End If
        Return allGroups
    End Function

    Public Sub WriteStartElement(ByVal writer As XmlWriter, ByVal e As XElement)
        Dim ns As XNamespace = e.Name.Namespace
        writer.WriteStartElement(e.GetPrefixOfNamespace(ns), _
            e.Name.LocalName, ns.NamespaceName)
        For Each a In e.Attributes
            ns = a.Name.Namespace
            Dim localName As String = a.Name.LocalName
            Dim namespaceName As String = ns.NamespaceName
            writer.WriteAttributeString( _
                e.GetPrefixOfNamespace(ns), _
                localName, _
                IIf(namespaceName.Length = 0 And localName = "xmlns", _
                    XNamespace.Xmlns.NamespaceName, namespaceName),
                a.Value)
        Next
    End Sub

    Public Sub WriteElement(ByVal writer As XmlWriter, ByVal e As XElement)
        If (e.Name = "TextBlock") Then
            WriteStartElement(writer, e)
            writer.WriteRaw(Environment.NewLine)

            ' Create an XML writer that outputs no insignificant white space so that we can
            ' write to it and explicitly control white space.
            Dim settings As XmlWriterSettings = New XmlWriterSettings()
            settings.Indent = False
            settings.OmitXmlDeclaration = True
            settings.ConformanceLevel = ConformanceLevel.Fragment
            Dim sb As StringBuilder = New StringBuilder()
            Using newXmlWriter As XmlWriter = XmlWriter.Create(sb, settings)
                ' Group adjacent runs so that they can be output with no whitespace between them
                Dim groupedRuns = e.Nodes().GroupAdjacent( _
                    Function(n) As Boolean?
                        If TypeOf n Is XElement Then
                            Dim element As XElement = n
                            If element.Name = "Run" Then
                                Return True
                            End If
                            Return False
                        End If
                        Return False
                    End Function)
                For Each g In groupedRuns
                    If g.Key = True Then
                        ' Write white space so that the line of Run elements is properly indented.
                        newXmlWriter.WriteRaw("".PadRight((e.Ancestors().Count() + 1) * 2))
                        For Each run In g
                            run.WriteTo(newXmlWriter)
                        Next
                        newXmlWriter.WriteRaw(Environment.NewLine)
                    Else
                        For Each g2 In g
                            ' Write some white space so that each child element is properly indented.
                            newXmlWriter.WriteRaw("".PadRight((e.Ancestors().Count() + 1) * 2))
                            g2.WriteTo(newXmlWriter)
                            newXmlWriter.WriteRaw(Environment.NewLine)
                        Next
                    End If
                Next
            End Using
            writer.WriteRaw(sb.ToString())
            writer.WriteRaw("".PadRight(e.Ancestors().Count() * 2))
            writer.WriteEndElement()
        Else
            WriteStartElement(writer, e)
            For Each n In e.Nodes
                If TypeOf n Is XElement Then
                    Dim element = n
                    WriteElement(writer, element)
                    Continue For
                End If
                n.WriteTo(writer)
            Next
            writer.WriteEndElement()
        End If
    End Sub

    Function ToStringWithCustomWhiteSpace(ByVal element As XElement) As String
        ' Create XmlWriter that indents.
        Dim settings As XmlWriterSettings = New XmlWriterSettings()
        settings.Indent = True
        settings.OmitXmlDeclaration = True
        Dim sb As StringBuilder = New StringBuilder()
        Using xmlWriter As XmlWriter = xmlWriter.Create(sb, settings)
            WriteElement(xmlWriter, element)
        End Using
        Return sb.ToString()
    End Function

    Sub Main()
        Dim myXML As XElement = _
            <Canvas>
                <Grid>
                    <TextBlock>
                        <Run Text='r'/>
                        <Run Text='u'/>
                        <Run Text='n'/>
                    </TextBlock>
                    <TextBlock>
                        <Run Text='far a'/>
                        <Run Text='way'/>
                        <Run Text=' from me'/>
                    </TextBlock>
                </Grid>
                <Grid>
                    <TextBlock>
                        <Run Text='I'/>
                        <Run Text=' '/>
                        <Run Text='want'/>
                        <LineBreak/>
                    </TextBlock>
                    <TextBlock>
                        <LineBreak/>
                        <Run Text='...thi'/>
                        <Run Text='s to'/>
                        <LineBreak/>
                        <Run Text=' work'/>
                    </TextBlock>
                </Grid>
            </Canvas>
        Console.Write(ToStringWithCustomWhiteSpace(myXML))
        Console.ReadLine()
    End Sub

End Module

`

Conversion of Date into hour/minute/second incredibly slow

8 votes

I need a date cyclically convert into its components (hour, minute, second). The following code does this quite well.

Dim time_hour As Integer
Dim time_minute As Integer
Dim time_second As Integer
Dim time_ms As Integer
Dim storedNow As Date

storedNow = Now
time_hour = storedNow.Hour
time_minute = storedNow.Minute
time_second = storedNow.Second
time_ms = storedNow.Millisecond

However, I have found this a performance problem. I have examined the source code with a profiler, and the conversion of Now into its components seems to be incredibly slow. Is there a quick way to the current time to disassemble into its component parts?

Take a look at Extremoptimization.com. There are a few interesting mathematic thoughts about this. Here's a possible sketch of a solution:

Dim ticks As Long
Dim time_hour As Integer
Dim time_minute As Integer
Dim time_second As Integer
Dim time_ms As Integer
Dim storedNow As Date

storedNow = Now
ticks = storedNow.Ticks
time_ms = CInt((ticks \ 10000) Mod 86400000)
time_hour = CInt(Math.BigMul(time_ms >> 7, 9773437) >> 38)
time_ms -= 3600000 * time_hour
time_minute = CInt(((Math.BigMul(time_ms >> 5, 2290650)) >> 32))
time_ms -= 60000 * time_minute
time_second = ((time_ms >> 3) * 67109) >> 23
time_ms -= 1000 * time_second

But be careful. Your source code will not be maintainable. This does your conversion very reliable, but I'm not sure if anyone else would understand what you are doing on the first view. The reward is a conversion, that is about 25 times faster than the classic approach. However, you still should think about your approach and if it is not possible to avoid this.

Hello SO,

I am somewhat confused about presence of two seemingly identical VB.NET functions: CType(args) and Convert.ToType(args). I'm fairly new to .NET and VB in general, so I'm not quite sure whether one of them is a VB6 legacy or they actually have different purposes / uses / limitations. Is one of the them newer / safer? Are there reasons to use one but not the other?

Cheers! = )

CType is from VB6 times and is not the best when it comes to efficiency. You should be able to use Convert.ToXxxx() methods for convertion and TryCast() and DirectCast() for casting instead of CType().

What is the meaning of ! in the code ?

7 votes

I'm a newbie in programming and visual basic 2008 language.

I'm learning to use sqlite database in visual basic 2008, and I got the following tutorial code. The code is working correctly and my question is: what is the meaning of that ! mark in the code. Please point to me where to get more information as I wish to learn more about that. I have Windows Sdk v6.1 installed.

Private Sub Button8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button8.Click
    Dim DatabaseFilepath As String = "e:\sqlite.db3"

    Dim SQLconnect As New System.Data.SQLite.SQLiteConnection()
    Dim SQLcommand As System.Data.SQLite.SQLiteCommand

    SQLconnect.ConnectionString = "Data Source=" & DatabaseFilepath & ";"
    SQLconnect.Open()

    SQLcommand = SQLconnect.CreateCommand

    Dim SchemaTable = SQLconnect.GetSchema(System.Data.SQLite.SQLiteMetaDataCollectionNames.Tables)

    For int As Integer = 0 To SchemaTable.Rows.Count - 1
        If SchemaTable.Rows(int)!TABLE_TYPE.ToString = "table" Then
            MessageBox.Show(SchemaTable.Rows(int)!TABLE_NAME.ToString())
        End If
    Next

    SQLcommand.Dispose()
    SQLconnect.Close()
End Sub

UPDATE:

Can anyone tell me what is the alternative for that bang operator in the code ? That bang operator looks unusual.

Its called the Bang Operator.

It means, use the default property of this type.

VB.NET: Doesn't anyone use the dictionary member access expression? (a.k.a. the bang operator)

In C#, is it possible to implement an interface member using a member with a different name, like you can do in VB.NET?

6 votes

Ok, this is a question I'm asking, not as in demonstrating good coding practices (this actually could be considered a bad practice) but rather in regards to 'can' it be done at all.

That said, in VB.NET you implement an interface like this...

Sub SomeInterfaceMember()
    Implements ISomeInterface.SomeInterfaceMember
End Sub

while in C# you do it explicitly like this (which can only be called via the interface)...

void ISomeInterface.SomeInterfaceMember(){}

or more simply, implicitly like this...

void SomeInterfaceMember(){} // Note the name matches the interface member

However, regarding VB, I can also do this...

Sub SomeRandomMemberName()
    Implements ISomeInterface.SomeInterfaceMember
End Sub

In other words, the method that handles the implementation can have a completely different name than the interface's member name.

I'm just wondering if there's something similar to this in C#. (Yes, I know I can simply do an explicit interface, then access it via another 'wrapper' member with a different name that simply delegates to it, but in VB.NET, you do both with a single method.)

So can that be done?

Mark

No, this isn't possible in C#. (You can't "explicitly implement an interface" in VB.NET either.)

Binding converted Enum to a ComboBox

6 votes

I tried to bind the following Enum to a ComboBox

Public Enum PossibleActions
  ActionRead
  ActionWrite
  ActionVerify
End Enum

I can't change the Enum itself, but I do not want to display these strings. My intention is just to cut the prefix 'Action' and display 'Read', 'Write' and 'Verify' in the ComboBox. Therefore I wrote a ValueConverter

Public Class PossibleActionsConverter
  Implements IValueConverter

      Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        Dim actions() As PossibleActions
        Dim strings() As String

        actions = CType(value, PossibleActions())
        ReDim strings(actions.GetUpperBound(0))
        For i = 0 To actions.GetUpperBound(0)
          strings(i) = actions(i).ToString.Substring(6)
        Next
        Return strings
      End Function

      Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Dim s As String

        s = CStr(value)

        Return [Enum].Parse(GetType(PossibleActions), "Action" & s)
      End Function
    End Class

My XAML looks like

xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:StepEditor"

[...]

<Window.Resources>
    <ObjectDataProvider x:Key="possibleActionsEnum" MethodName="GetValues"
                        ObjectType="{x:Type sys:Enum}">
        <ObjectDataProvider.MethodParameters>
            <x:TypeExtension Type="local:PossibleActions"></x:TypeExtension>
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
    <local:PossibleActionsConverter x:Key="possibleActionsConverter"></local:PossibleActionsConverter>
</Window.Resources>

[...]
Either:

<ComboBox ItemsSource="{Binding Source={StaticResource possibleActionsEnum}, Converter={StaticResource possibleActionsConverter}}"
          SelectedItem="{Binding SelectedAction}"></ComboBox>

Or:

<ComboBox ItemsSource="{Binding Source={StaticResource possibleActionsEnum}, Converter={StaticResource possibleActionsConverter}}"
          SelectedItem="{Binding SelectedAction, Converter={StaticResource possibleActionsConverter}}"></ComboBox>

My problem is the binding of the selected item. It fails, but I can't figure out why.

The binding of SelectedItem is wrong, because you convert your Enum into Strings, but SelectedItems is a single string. If you want to stick on this architecture, write a converter that converts a single string back to your enum. The Convert and ConvertBack-methods of your existing converter are close to the solution. They can look like:

  Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
    Dim action As PossibleActions

    action = CType(value, PossibleActions)
    Return action.ToString.Substring(6)
  End Function

  Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
    Dim s As String

    s = CStr(value)
    Return [Enum].Parse(GetType(PossibleActions), "Action" & s)
  End Function

C# and VB in C#

5 votes

I have a c# and vb .net solution. I need to use the c# form inside vb form as a tab. How can I do this?

I did it by adding the .exe file of VB project as a reference in the C# project and called the Form.Show() of the VB project.

Listbox with 1000+ items freezing Visual Studio

5 votes

Hi,

I have a listbox with 1091 items in it, which I am adding during design time. Every time Visual Studio tries to save after I manually populate the listbox it will hang indefinitely. Is there any way around this, am I trying to add too many items to a listbox?

Thanks

Instead of doing it manually city-by-city at design time, I would simply loop through a text filee (or excel file or database) at runtime and add all of the cities to a list, which then is used to populate the listbox.

Of course, this isn't the answer to your current question, but this may be a solution to your current problem.

Update: Resource Files might be a happy medium. You can still keep your city names in some sort of a text file. Then, you add that text file to a resource file. The resource file is then integrated with your program so you don't have to deal with a user ever knowing that the file exists.

I tried it out in C# (my preferred language) and it was more simple than I expected. After adding the resource file Resource1, I added my textfile cityListTextFile.txt to Resource1. From then, I could access it like this:

string cityList = Resource1._cityListTextFile;

After that line of code, I had all of the contents of cityListTextFile.

Take a look at this tutorial on using resource files in VB.NET and a C# one for fun.

Is VB.NET weakly typed compared to C#

5 votes

Yesterday I was at an interview where my interviewer (who admittedly didn't claim to be an expert on the subject) stated that "VB.NET is more weakly typed then C#" - (At the same time he couldn't recall an example).

This statement seemed incorrect to me (particularly given that both languages use the same framework libraries for their types) and I advised as such and that perhaps he was confused with the option to turn Option Strict or Option Infer on/off.

At the same time I know that VB.NET has situations where it will do type coercion - leading to occasionally unexpected results (although I also cant recall under what conditions) - (Actually I think I just remembered that it was mainly when performing arithmetic operations with different types - whereas other languages will force you to be explicit (?) ).

So could someone please clarify is VB.NET somehow more weakly typed then C# and if so could you provide examples?

"Weakly typed" and "strongly typed" are effectively meaningless without clarification. The way they are used they usually mean "the type system has features I do not like" or "the type system has features I do like". It sounds like your interviewer does not have a clear idea of what those terms mean, and therefore probably shouldn't be asking questions about them in interviews.

There are a lot of features of type systems that different people say are "strongly typed" vs "weakly typed". For example, some people say that "strongly typed" means "every object knows its own type at runtime". Some people say that "strongly typed" means that the compiler knows the exact type of every variable and expression. Some people say that it means that the compiler has inexact type bounds on every variable and expression. And so on. Every feature of type systems can count as points towards 'strong'.

I say abandon the whole ill-founded notion of "strong" and "weak" typing and talk about what you actually mean.

The differences between the C# and VB type systems are few, particularly since the addition of 'dynamic' to C# 4.0. Both C# and VB use the CLR type system, in which every object knows its own type, and in which illegal type conversions are detected by the runtime (either when the code runs or when it is passed through the verifier) and turned into exceptions. Both have single inheritance for classes and multiple inheritance for interfaces. Both make a distinction between value types and reference types. And so on.

The principle difference between C# and VB type systems is that VB supports optionally dialing down the compile time static type checking, and deferring type checking to runtime, more like a dynamically typed language. This is very handy when interoperating with object models that were designed for dynamic type systems. We added a similar feature to C# 4.0, but in keeping with C# 4.0's historical support of static typing, the feature is based on statically typing certain expressions as "dynamic", which are then resolved by starting up the type analyzer again at runtime and doing the type analysis against the live objects.

What happened to Intellisense for enum types in Visual Studio 2010 using VB.NET?

5 votes

I am using Visual Studio 2010 Prof.

In C# I can create my own Enumerator and use it like this:

MyEnum value = 

Now, Intellisense will suggest a value of MyEnum.

In VB, when I write:

Dim value As MyEnum = 

I get a huge list of every types. When starting to write my enumerator value (could be a word like "sunny") it filters out some types but I would like to have it like in C#. Anyway I will use the MyEnum type and no "String nor Objecte nor IntPtr...".

Any idea?

Screenshot

Also I made a short video: Video with sample (new)

Regards

This is a documented issue in VS 2010, pre-SP1. See: https://connect.microsoft.com/VisualStudio/feedback/details/551699/intellisense-enum-values. It has been fixed in SP1. If you can't install SP1, the only workaround is to use the mouse or Alt + , to switch from the "All" to the "Common" tab.

Fibonacci Sequence in VB.net using loop

4 votes

Hi there

Please could you help me with displaying the first 10 Fibonacci numbers. My code displays the following result: 1, 2, 3, 5, 8, 13, 21, 34, 55 and I need it to also display the first two Febonacci numbers (0 and 1). How would I do that?

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim a As Integer = 0
        Dim b As Integer = 1
        Dim fib As Integer = 0

        Do
            fib = a + b
            a = b
            b = fib
            Label1.Text = Label1.Text + fib.ToString & ControlChars.NewLine
        Loop While fib < 55
    End Sub
End Class

Where in professional programming would you need to use Febonacci sequences?

Thanks!

Just add

Label1.Text = Label1.Text + a.ToString & ControlChars.NewLine
Label1.Text = Label1.Text + b.ToString & ControlChars.NewLine

before the Do ... while.

For applications linked to Fibonacci numbers see : Fibonacci: Applications

Double insert in MS Access?

4 votes

I'm somehow getting a double insert; every time I submit the form, it sends two records to the database. I can't figure out what's going on. This is a general idea of what my code looks like:

Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click

'Data collection'

'Define Connection'
    Dim myConn As New OleDbConnection
    myConn.ConnectionString = adsGrandmaster.ConnectionString
    myConn.Open()

'Insert command'
    Dim myIns1 As New OleDbCommand("INSERT INTO tableGrandmaster (date_received, prefix, course_number, title, new, changed, inactivate, end_date, credits, description, hours_lecture, hours_lec_lab, hours_lab, hours_total, related_instruction, repeat, challengeable, in_catalog, in_printed_schedule, core_course, core_name, program_elective, program_name, prereqs, coreqs, recommended, green_course, code, dept_code, division_code, changing_depts, acti_code, grading, general_ed, writing, social_science, math, information_literacy, arts_letters, science_computer, speech_comm, cultural_literacy, date_curriculum_approval, date_state_sent, date_state_approval, date_created) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", myConn)

'Insert parameters'

'Execute command'
    myIns1.ExecuteNonQuery()

'Close connection'
    myConn.Close()

Update:

The last little piece of my .aspx.vb file:

'Execute command'
    myIns1.ExecuteNonQuery()

    Label1.Text = "Grandmaster submitted."

    'Close connection'
    myConn.Close()

End Sub

Protected Sub btnBack_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnBack.Click
    Response.Redirect("./index.htm")
End Sub
End Class

If I place my breakpoint at or before myIns1.ExecuteNonQuery(), nothing inserts. If I place it after myIns1.ExecuteNonQuery(), it inserts once. If I place it after "End Sub" (under myConn.Close()), it inserts twice.

Make sure that the aspx:button declaration is not wired up to the onclick event on the code-in-front page as well as the code behind page.