Best vb.net questions in March 2011

Why does C# set private variables before the base constructor, while VB.NET does the opposite?

13 votes

There was a question comparing C# code and VB.NET and the results between the seemingly identical code were entirely different. (Why C# is always winning over VB.NET?)

The explanation given is that C# will initialize the class fields, then call the base constructor, but VB.NET does the exact opposite.

My question is - why?

Is there a technical reason for the languages to be different? At first glance, it seems that either approach is equally valid, but I can't fathom why they wouldn't have selected the SAME approach.

EDIT: As 'Jeffrey L Whitledge' has pointed out, VB6 did not have inheritance, so I don't think we can say 'to keep VB.NET and VB6 more closely related'.

It is possible for a base constructor to expose an object to the outside world before derived-class constructors have run. While one should often avoid doing this, there are times when it's necessary. For example, one might have two objects which hold references to each other, and each object might have as a class invariant that the reference to the other object must be valid. Creating such a pair of objects would require having one object's constructor pass the partially-constructed object to the other, or having an object's constructor return before its class invariants were satisfied.

If derived-class field initializers are not run until after the base class constructor has run, and if the base-class constructor exposes the object to the outside world, that would mean that the object would be exposed to the outside world before any derived-class initialization had taken place. The creators of C# didn't like that idea, so they made derived-class initializers run before the base class constructor.

On the other hand, running derived-class initializers before the base-class constructor has a disadvantage: those initializers can't make any reference to the object under construction. There's also no way for them to make use of any arguments that are passed to the constructor. Having an object be partially initialized before control is handed over to the base-class constructor may be nice, but there are some severe limits as to how it can be initialized; it may or may not be possible to have the object in a fully-useful state before the base constructor is run.

The creators of vb.net apparently thought that since running initializers before the base constructor doesn't eliminate the need to deal with partially-constructed objects being exposed to the outside world, and since it precludes the use of some useful techniques, it was better to have the initializers run after the base constructor. This makes it possible for a base-level constructor to expose one of its parameters as a field, and then have the derived-class use the value of that field in the derived-class field initializers.

Arguably, the C# approach allows one to do things the vb.net one does not, but the reverse isn't true (one could implement vb-style field initializers by simply writing to the fields at the start of the constructor). On the other hand, having the declaration and initialization of a field next to each other is cleaner than having declarations in one place and initializations someplace else. Too bad neither language allows one to specify that certain specific field declarations should follow the opposite paradigm from the norm.

Translation of C# ActionCommand:ICommand into VB.net

10 votes

I found a C# class ActionCommand, that implements ICommand and bases on delegates for Execute and CanExecute. Looks perfect for me so far.

  public class ActionCommand : ICommand
  {
    private readonly Action<object> _executeHandler;
    private readonly Func<object, bool> _canExecuteHandler;

    public ActionCommand(Action<object> execute, Func<object, bool> canExecute)
    {
      if (execute == null)
        throw new ArgumentNullException("Execute cannot be null");
      _executeHandler = execute;
      _canExecuteHandler = canExecute;
    }

    public event EventHandler CanExecuteChanged
    {
      add { CommandManager.RequerySuggested += value; }
      remove { CommandManager.RequerySuggested -= value; }
    }
    public void Execute(object parameter)
    {
      _executeHandler(parameter);
    }
    public bool CanExecute(object parameter)
    {
      if (_canExecuteHandler == null)
        return true;
      return _canExecuteHandler(parameter);
    }
  }

Now I translated it into my needed VB.net variant (using code translators and some hands on)

Public Class ActionCommand
  Implements ICommand

  Public Event CanExecuteChanged As EventHandler Implements ICommand.CanExecuteChanged

  Private ReadOnly _executeHandler As Action(Of Object)
  Private ReadOnly _canExecuteHandler As Func(Of Object, Boolean)

  Public Sub New(ByVal execute As Action(Of Object),
                 ByVal canExecute As Func(Of Object, Boolean))
    If execute Is Nothing Then
      Throw New ArgumentNullException("Execute cannot be null")
    End If
    _executeHandler = execute
    _canExecuteHandler = canExecute
  End Sub

  Public Sub Execute(ByVal parameter As Object) Implements ICommand.Execute
    _executeHandler(parameter)
  End Sub

  Public Function CanExecute(ByVal parameter As Object) As Boolean Implements ICommand.CanExecute
    If (_canExecuteHandler Is Nothing) Then
      Return True
    End If
    Return _canExecuteHandler(parameter)
  End Function
End Class

My problem is around CanExecuteChanged and registering/mapping the events from CommandManager.RequerySuggested to CanExecuteChanged. The online code translator suggest the following:

Public Custom Event CanExecuteChanged As EventHandler
    AddHandler(ByVal value As EventHandler)
        CommandManager.RequerySuggested += value
    End AddHandler
    RemoveHandler(ByVal value As EventHandler)
        CommandManager.RequerySuggested -= value
    End RemoveHandler
End Event

but this cannot satify ICommand.CanExecuteChanged Can someone please help how to translate or solve this?

This article from MALIGUI .NET BLOG might help:

Public Custom Event CanExecuteChanged As EventHandler _
    Implements ICommand.CanExecuteChanged
        AddHandler(ByVal value As EventHandler)
            Dim handler2 As EventHandler
            Dim canExecuteCommand = __CanExecuteCommand
            Do
                handler2 = canExecuteCommand
                Dim handler3 = DirectCast(System.Delegate.Combine(handler2, value), EventHandler)
                canExecuteCommand = Interlocked.CompareExchange((__CanExecuteCommand), handler3, handler2)
            Loop While (Not canExecuteCommand Is handler2)
            __CanExecuteCommand = canExecuteCommand
        End AddHandler
        RemoveHandler(ByVal value As EventHandler)
            Dim handler2 As EventHandler
            Dim canExecuteCommand = __CanExecuteCommand
            Do
                handler2 = canExecuteCommand
                Dim handler3 = DirectCast(System.Delegate.Remove(handler2, value), EventHandler)
                canExecuteCommand = Interlocked.CompareExchange((__CanExecuteCommand), handler3, handler2)
            Loop While (Not canExecuteCommand Is handler2)
            __CanExecuteCommand = canExecuteCommand
        End RemoveHandler
        RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
            If (__CanExecuteCommand IsNot Nothing) Then
                __CanExecuteCommand.Invoke(sender, e)
            End If
        End RaiseEvent
    End Event

Why Shouldn't You Access a Shared/static Member Through An Instance Variable?

7 votes

Here's an example of what I'm talking about...

Public Class Sample1

    Public Shared Function MyValue() As Integer
        Return 0
    End Function

    Public Sub Code()
        Dim ThisIsBad = Me.MyValue
        Dim ThisIsGood = Sample1.MyValue
    End Sub

End Class

Me.MyValue gives a warning in VB.NET and (the equivalent code gives) an error in C#. Is there a particular reason for this? I find it more intuitive/natural to access the shared function using 'Me.MyValue' - but I avoid it to keep my warnings at 0.

Did someone else just decide 'Nah, it makes more sense to do it the other way' or is there some technical reason I don't understand?

EDIT:

Thanks everyone. I was thinking of it wrong, more like a 'sub class' in OOP. Even if something is declared in the base class, you access it through the instance you have. But that relationship is not the same with shared or static.

Static members by definition are declared at the class level, not the instance level, and so accessing a static member using this (or me in VB) doesn't really feel right (and isn't right in C#)

Saying this.something (or me.something) implies you are accessing "something" that's particular to that specific instance, while, again, static members are shared throughout all instances of that class.

Securing encryption keys in C#

7 votes

I am aware of the many cryptography providers that are available in the .NET framework along with the basics of how to use them. This is simple enough.

But my concern is this.

Lets say I want to use these libraries to encrypt XML serialized objects to prevent tampering and the ability of anyone to come along and view the contents of these files.

The problem that I am always left with is that the key to decrypt this data would need to be stored as a constant somewhere in my application. Essentially rendering the entire exercise pointless.

So, how does one store a key for an encryption algorithm securely inside of a disassemblable application?

EDIT: So If I am understanding both answers below correctly. What this means is that essentially any implementation (to be secure) requires it to be readonly or writeonly but never both? Is this correct?

You don't. If the application can access the key, it is just security by obscurity. It is better to authenticate the user in some way (a password is the simplest example), to make sure he is allowed to access the data. You can't let the application do that for you, because it simply isn't trustworthy. Anyone can obtain the information stored in the application.

If the key information is stored somewhere else, a malicious user or application can probably access it, too. If not, then store your data directly to that magical safe place.

Now if you still want to go down that path and store sensitive data without authentication, your best bet - or at least an easy way that is halfway secure - is probably the DPAPI (see the ProtectedData class in System.Security.Cryptography). It will encrypt the data either with the machine key or to the user account key (you can select that). So that a program running on another machine or with another user account can't access it. Windows will try to protect those keys but in effect any application running on the proper machine or with the proper user account may be able to access your data.

What architecture to use to address this SystemOutOfMemoryException while allowing me to instantiate the cells of a sheet?

6 votes

Summary

This question is the follow-up of a a desire to architect a simple spreadsheet API while keeping it user-friendly to those who know Excel well.

To sum it up, this question is related to these below two:
1. How to implement column self-naming from its index?;
2. How to make this custom worksheet initialization faster?.

Objective

To provide a simplified Excel API used as a wrapper over the nevralgic components such as the Application, the Workbook, the Worksheet and the Range classes/interfaces while exposing only the most commonly used object properties for each of these.

Usage example

This usage example is inspired from the unit tests that allowed me to bring this solution up to where it stands now.

Dim file as String = "C:\Temp\WriteTest.xls"

Using mgr As ISpreadsheetManager = New SpreadsheetManager()
    Dim wb as IWorkbook = mgr.CreateWorkbook()
    wb.Sheets("Sheet1").Cells("A1").Value = 3.1415926
    wb.SaveAs(file)
End Using

And now we open it:

Dim file as String = "C:\Temp\WriteTest.xls"

Using mgr As ISpreadsheetManager = New SpreadsheetManager()
    Dim wb as IWorkbook = mgr.OpenWorkbook(file)
    // Working with workbook here...
End Using

Discussion

While instantiating an Excel Workbook:

  1. An instance of a Worksheet is automatically initialized in the Workbook.Sheets collection;
  2. Upon initialization, a Worksheet initializes its Cells through the Range object that can represent one or multiple cells.

These Cells are immediately accessible with all their properties as soon as the Worksheet exists.

My wish is to reproduce this behaviour so that

  1. The Workbook class constructor initializes the Workbook.Sheets collection property with the native sheets;
  2. The Worksheet class constructor initializes the Worksheet.Cells collection property with the native cells.

My problem comes from the Worksheet class constructor while initializing the Worksheet.Cells collection property illustrated at #2.

Thoughts

Following these above-linked questions encountered issues, I wish to figure out another architecture that would allow me to:

  1. Access specific feature of a cell Range when required;
  2. Deliver most commonly used properties through my ICell interface;
  3. Having access to all of the Range cells of a worksheet from its initialization.

While keeping in mind that accessing a Range.Value property is the fastest interaction possible with the underlying Excel application instance using the Interop.

So, I thought of initializing my ReadonlyOnlyDictionary(Of String, ICell) with the name of the cells without immediately wrapping an instance of the Range interface so that I would simply generate the row and column indexes along with the cell's name to index my dictionary, then, assigning the Cell.NativeCell property only when one wants to access or format a specific cell or cell range.

That way, the data in the dictionary would be indexed with the name of the cells obtained from the column indexes generated in the Worksheet class constructor. Then, when one would do this:

Using mgr As ISpreadsheetManager = New SpreadsheetManager()
    Dim wb As IWorkbook = mgr.CreateWorkbook()
    wb.Sheet(1).Cells("A1").Value = 3.1415926 // #1:
End Using

#1: This would allow me to use the indexes from my Cell class to write the given value to the specific cell, which is faster then using its name directly against the Range.

Questions and Concerns

Besides, when working with UsedRange.get_Value() or Cells.get_Value(), this returns Object(,) arrays.

1. So should I just be happy with working with Object(,) arrays for cells, without having the possibility to format it somehow?

2. How to architect these Worksheet and Cell classes so that I have the best performance offered while working with Object(,) arrays, while keeping the possibility that a Cell instance may represent or wrap a single cell Range?

Thanks to any of you who takes the time to read my post and my sincerest thanks to those who answer.

The used architecture has gone through an object class that I named CellCollection. Here's what it does:

Based on these hypothesis:

  1. Given that an Excel worksheet has 256 columns and 65536 lines;

  2. Given that 16,777,216 (256 * 65536) cells needed to be instantiated at a time;

  3. Given that the most common use of a worksheet takes less then 1,000 lines and less than 100 columns;

  4. Given that I needed it to be able to refer to the cells with their addresses ("A1"); and

  5. Given that it is benchmarked that accessing all the values at once and load them into a object[,] in memory as being the fastest way to work with an underlying Excel worksheet,*

I have considered not to instantiate any of the cells, letting my CellCollection property within my IWorksheet interface initialized and empty upon instantiation, except for an existing workbook. So, when opening a workbook, I verify that NativeSheet.UsedRange is empty or return null (Nothing in Visual Basic), otherwise, I have already gotten the used "native cells" in memory so that only remains to add them in my internal CellCollection dictionary while indexing them with their respective address.

Finally, Lazy Initialization Design Pattern to the rescue! =)

public class Sheet : ISheet {
    public Worksheet(Microsoft.Office.Interop.Excel.Worksheet nativeSheet) {
        NativeSheet = nativeSheet;
        Cells = new CellCollection(this);
    }

    public Microsoft.Office.Interop.Excel.Worksheet NativeSheet { get; private set; }

    public CellCollection Cells { get; private set; }
}

public sealed class CellCollection {
    private IDictionary<string, ICell> _cells;
    private ReadOnlyDictionary<string, ICell> _readonlyCells;

    public CellCollection(ISheet sheet) {
        _cells = new Dictionary<string, ICell>();
        _readonlyCells = new ReadonlyDictionary<string, ICell>(_cells);
        Sheet = sheet;
    }

    public readonly ReadOnlyDictionary<string, ICell> Cells(string addresses) {
        get {
            if (string.IsNullOrEmpty(addresses) || 0 = address.Trim().Length)
                throw new ArgumentNullException("addresses");

            if (!Regex.IsMatch(addresses, "(([A-Za-z]{1,2,3}[0-9]*)[:,]*)"))
                throw new FormatException("addresses");

            foreach(string address in addresses.Split(",") {
                Microsoft.Office.Interop.Excel.Range range = Sheet.NativeSheet.Range(address)

                foreach(Microsoft.Office.Interop.Excel.Range cell in range) {
                    ICell c = null;
                    if (!_cells.TryGetValue(cell.Address(false, false), c)) { 
                        c = new Cell(cell);
                        _cells.Add(c.Name, c);
                    }
                }
            }

            return _readonlyCells;
        }
    }

    public readonly ISheet Sheet { get; private set; }
}

Obviously, this is a first try shot, and it works just fine so far, with more than acceptable performance. Humbly though, I feel like it could use some optimizations, though I will use it this way for now, and optimize it later if needed.

After having written this collection, I was able to come to the expected behaviour. Now, I shall try to implement some of the .NET interfaces to make it useable against some IEnumerable, IEnumerable<T>, ICollection, ICollection<T>, etc. so that it may respectively be considered as a true .NET collection.

Feel free to comment and bring constructive alternatives and/or changes to this code so that it may become even greater than it currently is.

I DO hope this will serve one's purpose someday.

Thanks for reading! =)

6 votes

Hi There

My study book makes the following statement about the code below:

**"The computer evaluates the loop condition in the Do...Loop statment to determine whether the loop instructions should be processed. In this case, the inputsales <> String.Empty condition compares the contenst of the input sales variable to the String.Empty value. As you know the String.Empty value represents a zero length, or empty, string if the inputsales variable is empty, the loop condition evaluates to True and the computer process the loop instructions. *If on the other hand the inputsales variable is not empty, the loop condition evaluates to false and the computer skips over the loop instructions.

Based on the code I think it is the opposite: ...that while the inputsales value is not empty it should evaluate to true and process the loop and if it is empty it should evaluate to false and skip the loop? Please see below. Thanks so much for the help!

Option Explicit On
Option Strict On

Imports System.Globalization


Public Class SalesForm

    Private Sub exitButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exitButton.Click
        Me.Close()
    End Sub

    Private Sub calcButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles calcButton.Click
        Const prompt As String = "Enter a sales amount. Click cancel to end."
        Const title As String = "Sales Entry"
        Dim inputsales As String
        Dim sales As Decimal
        Dim salesCounter As Integer
        Dim salesaccumulator As Decimal
        Dim salesAverage As Decimal
        Dim isconverted As Boolean

        inputsales = InputBox(prompt, title, "0")

        **Do While inputsales <> String.Empty
            isconverted = Decimal.TryParse(inputsales, NumberStyles.Currency, NumberFormatInfo.CurrentInfo, sales)

            If isconverted = True Then
                salesCounter = salesCounter + 1
                salesaccumulator = salesaccumulator + sales
            Else
                MessageBox.Show("Please re-entere the sales amount.", "sales Express", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
            inputsales = InputBox(prompt, title, "0")
        Loop**

        If salesCounter > 0 Then
            salesAverage = salesaccumulator / Convert.ToDecimal(salesCounter)
            averageLabel.Text = salesAverage.ToString("C2")
            Label2.Text = salesCounter.ToString
        Else
            averageLabel.Text = "0"
        End If
    End Sub
End Class

You are definitely correct, and the book is wrong (hopefully, the author just reversed the true/false by accident; otherwise, I'd get another book). My suggested correction (with a few additions):

As you know, the String.Empty value represents a zero length, or empty, string. If the inputsales variable is not empty, the loop condition evaluates to True, and the computer processes the loop instructions (and then jumps back to the top of the loop and reevaluates the condition). If, on the other hand, the inputsales variable is empty, the loop condition evaluates to False, and the computer skips over the loop instructions (and continues with the first statement after the loop).

As @xanatos said: Congratulations on catching your first bug in someone else's text. So +1 for the question, and I'd say that this seems promising for your programming career. :-)

.NET compiler limitation for addition?

6 votes

My co-worker and i just found that there seems to be a limitation on the number of parameters that can be used in vb.net code.

What's strange to me is that this code will build but when i run it, it throws an InvalidProgramException saying that the "JIT Compiler encountered an internal limitation".

Has anyone seen anything like this before? Can you point me to why this is happening?

(i'm using .net 4.0 with VS 2010. We found this in VS 2008 and it had a slightly different result.)

Sample code:

    Dim bigVariable As Double = 10.35
    Dim factor As Double = 1.3
    Dim hugeNumberOfArgs As Double = (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) +
(bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor) + (bigVariable * factor)

        Console.WriteLine("Result: " & hugeNumberOfArgs)
        Console.ReadKey()

After further investigation I don't believe this is a compiler issue. The code crashes in Debug and works fine in Retail. I've diff'd the IL a few times and can't come across a discernable difference.

Also this bug repros in C# as well. If you're trying to repro this yourself make sure you pass /debug+ to the command line compiler.

This appears to be a bug in the JIT compilation. One way to prevent the crash in debug mode is to add the following line of code

<Assembly: Debuggable(DebuggableAttribute.DebuggingModes.DisableOptimizations)>

Once this is added the code will execute successfully. This and reproing in both languages strongly suggests that it's a bug in the JIT process.

Cross Platform Alternatives to WPF

6 votes

Hi, all, I'm thinking of porting my application from VB.net to the C# based MONO project, so it can run on both Windows and Mac. However, I am in need of a Mac-friendly alternative to WPF. It has to have very similar functionality. QML (by QT) is not a viable option, as it costs far too much money for us.

Miguel de Icaza recommends MonoMac as a substitute to WPF for Mac as stated here. As he explains there is no plan to implement WPF in mono.

You will have to build two different UI on top of a common engine, but that's generally a good separation of concerns.

There is also a possible common code base for UI with GTK#.

Counting items in a multi-dimensional array

5 votes

If I have the following array:

    Dim Array(4, 10) As String
    Array(0, 0) = "100"
    Array(0, 1) = "200"
    Array(1, 0) = "300"
    Array(1, 1) = "400"
    Array(1, 2) = "500"
    Array(1, 3) = "600"

How do I get the following count:

0 = 2
1 = 4

It sounds like you're trying to count the number of non-Nothing values in each dimension of the array. The following function will allow you to do that

Public Function CountNonNothing(ByVal data As String(,), ByVal index As Integer) As Integer
    Dim count = 0
    For j = 0 To data.GetLength(1) - 1
        If data(index, j) IsNot Nothing Then
            count += 1
        End If
    Next
    Return count
End Function

And it can be invoked like so

Dim count1 = CountNonNothing(Array, 0)
Dim count2 = CountNonNothing(Array, 1)

Convert code from VB into C#

5 votes

I have problem to convert this VB code into C#

Public Event SendNewBid As EventHandler(Of BidEventInfo)

BidEventInfo is a name of class

C# code:

Public event SendNewBid ....??????

public event EventHandler<BidEventInfo> SendNewBid;

for future conversions, you could use this online converter

Simple 2D 'Space Invaders' Clone In Silverlight....

5 votes

I want to make a simple 2d game in Silverlight, but it seems like things have changed since the last time I tried to make a game using mode 13h graphics. Can someone give me a run-down of how you'd go about it.

I just mean at a high-level, focusing on the silverlight-specific aspects; not general game design.

A fictional example might be: 'The main game loop shouldn't be a loop, use a DispatchTimer instead. Use a Canvas as the main drawing object; but realize that we don't bother drawing individual pixels - all of your in-game objects should be represented by controls. Be sure to set the 'UseHardwareFlag' to true'. Etc, etc...

If you want to stick to the mode 13 way of programming have a look at the WriteableBitmap.

Some very nice demos here

I succeeded in porting Wolf3D (2 and a half D) to Silverlight this way. I used the CompositionTarget.Rendering event

EDIT

I also found this, it is less mode 13 and more in line with your example.

How to cleanly deal with different behavior based on polymorphism

5 votes

Suppose I have an interface IFoo with implementation classes VideoFoo, AudioFoo, and TextFoo. Suppose further that I cannot modify any of that code. Suppose that I would then like to write a function that acts differently based on the runtime type of IFoo, such as

Public Class Bar
    Public Shared Sub Fix(ByVal Foo as IFoo)
        If TypeOf Foo Is VideoFoo Then DoBar1()
        If TypeOf Foo Is AudioFoo Then DoBar2()
        If TypeOf Foo Is TextFoo Then DoBar3()

    End Sub
End Class

I would like to refactor this to use overloaded methods:

Sub DoBar(ByVal foo as VideoFoo)
Sub DoBar(ByVal foo as AudioFoo)
Sub DoBar(ByVal foo as TextFoo)

But the only way I see to do something like that would be to write

Sub DoBar(ByVal foo as IFoo)

Then I have to do my "If TypeOf ... Is" again. How can I refactor this to take advantage of the polymorphism of the implementations of IFoo without manually checking the types?

(in VB.NET, though my question applies to C# too)

Well, one option is to simply overload the Fix() method so that you have one overload for each type implementing IFoo. But I suspect you want to accept the interface directly, rather than it's implementing types.

What you're actually looking for is multiple dispatch. Normally, C#/VB use the types of the argument(s) to perform overload resolution at compile time, and dynamic dispatch of the call based on the runtime type of the instance on which the method is called. What you want is to perform overload resolution at runtime based on the runtime types of the arguments - a feature that neither VB.NET or C# directly support.

In the past, I've generally solved this kind of problem using a dictionary of delegates indexed by System.Type:

private readonly Dictionary<Type,Action<IFoo>> _dispatchDictionary;

static Bar()
{
    _dispatchDictionary.Add( typeof(TextFoo),  DoBarTextFoo );
    _dispatchDictionary.Add( typeof(AudioFoo), DoBarAudioFoo );
    _dispatchDictionary.Add( typeof(VideoFoo), DoBarVideoFoo );        
}

public void Fix( IFoo foo )
{
   Action<IFoo> barAction;
   if( _dispatchDictionary.TryGetValue( foo.GetType(), out barAction ) )
   {
      barAction( foo );
   }
   throw new NotSupportedException("No Bar exists for type" + foo.GetType());
}

private void DoBarTextFoo( IFoo foo ) { TextFoo textFoo = (TextFoo)foo; ... }
private void DoBarAudioFoo( IFoo foo ) { AudioFoo textFoo = (AudioFoo)foo; ... }
private void DoBarVideoFoo( IFoo foo ) { VideoFoo textFoo = (VideoFoo)foo; ... }

However, as of C# 4, we can now use the dynamic keyword in C# do essentially do the same thing (VB.NET does not have this feature as of yet):

public void Fix( IFoo foo )
{
    dynamic dynFoo = foo;
    dynamic thisBar = this;

    thisBar.DoBar( dynFoo ); // performs runtime resolution, may throw
}

private void Dobar( TextFoo foo ) { ... /* no casts needed here */ }
private void Dobar( AudioFoo foo ) { ... }
private void Dobar( VideoFoo foo ) { ... }

Note that using the dynamic keyword this way has a price - it requires that the call site be processed at runtime. It essentially spins up a version of the C# compiler at runtime, processes the metadata captured by the compiler, performs runtime analysis of the types, and spits out C# code. Fortunately, the the DLR can typicall cache such call sites effectively after their first use.

As a general rule, I find both of these pattern to be confusing, and overkill for most situations. If the number of subtypes is small and they are all known ahead of time, a simple if/else block can bemuch simpler and clearer.

Should I favour IEnumerable<T> or Arrays?

4 votes

In many projects I work on, whenever I have to return a read only collection, I use the IEnumerable<T> interface and make it type specific like so:

Public ReadOnly Property GetValues() As IEnumerable(Of Integer)
    Get
        'code to return the values'
    End Get
End Property

Most of the time, I return a List but in some functions and read only properties I return an array which also serves the purpose alright by kind courtesy of Extension Methods.

My question is am I violating any design principles by returning IEnumerable<T>s instead of specific types (e.g.: List<T>, HashSet<T>, Stack<T> or Arrays)?

I generally prefer IEnumerable<T> as well. The main thing is to ask yourself what actual (even minimum) functionality is being returned from the method (or passed to it, in the case of a method argument).

If all you need to do is enumerate over a result set, then IEnumerable<T> does exactly that. No more, no less. This leaves you the flexibility to return more specific types in certain cases if need be without breaking the footprint of the method.

Getting CD Drive letter in VB.Net

4 votes

I am using the following code to get a list of the letters for each drive on my computer. I want to get the drive letter of CD Drive from this list. Please advise how to check it.

The code I am using to get list is as below:

In the Form.Load event:

    cmbDrives.DropDownStyle = ComboBoxStyle.DropDownList
    Dim sDrive As String, sDrives() As String
    sDrives = ListAllDrives()
    For Each sDrive In sDrives
    Next
    cmbDrives.Items.AddRange(ListAllDrives())

Public Function ListAllDrives() As String()
    Dim arDrives() As String
    arDrives = IO.Directory.GetLogicalDrives()
    Return arDrives
End Function

Tested, and returns the correct results on my computer:

Dim cdDrives = From d In IO.DriveInfo.GetDrives() _
                Where d.DriveType = IO.DriveType.CDRom _
                Select d

For Each drive In cdDrives
    Console.WriteLine(drive.Name)
Next

Assumes 3.5, of course, since it's using LINQ. To populate the list box, change the Console.WriteLine to ListBox.Items.Add.

What would be considered a VB.NET module in C#?

4 votes

VB.NET has classes and Modules, so my first question is what is the difference? Also, I noticed that C# does not have modules, but just classes, is there something in place of modules or were they removed for C#?

About the closest thing to a VB module would be a static class in C#.

For Example:

In VB.NET

Module SomeModule
    Public Sub DoSomething
        MsgBox("Doing something!")
    End Sub
End Module

Same thing in C#:

public static class DoSomethingFuncs
{
    public static void DoSomething() {
        MessageBox.Show("Doing something!");
    }
}

How should threads update global data in the main program?

4 votes

I am revisiting an old thread of mine.

I want to launch a bunch of threads, each performing the same task, and know in main() when each finishs and it if it was successful or failed.

The solution offered was to use a ConcurrentQueue, but other posts have recommended using a BackgroundWorker Class, or a thread pool.

Is there a definitive answer?

Again, all threads perform the same code and have a pass/fail result. I want to run more than there are available threads so as soon as one thread finishes I will launch another asap - I want tehm to stress a remote systems as much as possible (reather than stressing my local PC with too many threads, so I will need to experiment to determine the optimal number of threads).

VB .NET for specific answer, but general threading advice is also welcome.

BackgroundWorker is a very easy way to manage your running threads. It allows you to report progress back to the UI easily. I don't think there is a definitive answer but BackgroundWorker is designed for this purpose - running background tasks which update the UI as they progress. Here is an example of how to is it.

Is there a difference between StringDictionary class and Dictionary<String,String>

4 votes

System.Collections.Specialized contains StringDictionary http://msdn.microsoft.com/en-us/library/system.collections.specialized.stringdictionary.aspx#Y1626

What's difference with Strong Typed Dictionary in Generics?

StringDictionary comes from .Net 1, which predates generics.

Therefore, unlike Dictionary<String, String>, it doesn't implement any generic interfaces, so it cannot be used with LINQ (unless you Cast())

Also, StringDictionary normalizes all keys to lowercase.
(To make a case-insensitive Dictionary<String, String>, pass StringComparer.OrdinalIgnoreCase; this is also more compatible with Turkey)

RSA: how to generate RSA public and private keys based on a passphrase (.net)

4 votes

Hi all,

I'm working in .net environment (all versions) and using vb.net. I want to generate RSA public and private keys based on a passphrase.

My understanding of RSA algorithm only limited by using a class provided by the .net ie System.Security.Cryptography.RSACryptoServiceProvider Class. I know how to generate random RSA public/private keys and perform encryption/decryption.

But that .net class don't let us creating RSA public/private keys based on a passphrase.

Although I'm using vb.net, anyone with solutions in c#, c, c++ or any .net compatible language are welcomed to contribute as I can access the solution via p/invoke or dll reference.

Thanks in advance!

You won't need RSA if you don't need public key encryption.

Use symmetrical encryption with password-based key derivation function (e.g. AES with PBKDF2). It will be faster and more secure.