Prevent Recalculating of Functions when applying autofilter in Excel - vba

I am using excel 2013. I have a large sheet which consist of a list of Customers and their information. When I add new customers to this spreadsheet it fills most information by posting the CustomerID to our server, the server returns the customer information in a Json string which is then parsed. A specific function returns the information required i.e. "=Json_get_email(Userid)" will return the email address. All this work very well and is relatively user friendly for the staff in my company to use.
The problem arises when an autofilter is applied. Even if no function is volatile in this, applying an autofilter causes the spreadsheet to recalculate all the functions and what was efficient and quick for a customer or a few customers is now slowing down the spreadsheet like crazy.
I am turning to you to know if there is any way of preventing my functions to be calculated every time a filter is applied.
my best,
Fabien

Something like this will make your sheet much faster:
Function Json_get_email(arg)
Static dict As Object '<< persists between calls
If dict is nothing then set dict = Createobject("scripting.dictionary")
If not dict.exists(arg) Then
'have not seen this value of arg before
'...get the return "email" value for 'arg' here
dict.add arg, email
End If
Json_get_email = dict(arg) 'return the cached value
End Function
Should be no problem caching the return email values between calls which use the same argument value.

Here is the solution I implemented. I want to share it as I have seen that many people had the same issue with UDFs.
It is not perfect but makes it a lot faster as it avoids connecting to the server and parsing the string each time.
I created a public array of booleans indexed by User_ID,
Public Names_in_List(100000000 To 104000000) As Boolean
Function JSon_CustomerName2(UserID As String) As String
If Names_in_List(UserID) = False Then
'The Function Has not yet been run for this ID
'... Do whatever
Names_in_List(UserID) = True 'Update the status
Else
JSon_CustomerName2 = Application.Caller.value 'Reuse the value that was in the cell.
End If
End Function
As always, I had to trade memory for speed but with booleans its only one bit per user.
Many thanks #Tim for your helpful insight.

Related

How do I assign an Excel VBA variable to a Defined Name

How do I return a value from a VBA Function variable to a Defined Name in Excel 2010?
In the example below, I want i to be returned to Excel as a Defined Name Value_Count that can be reused in other formulas, such that if MsgBox shows 7, then typing =Value_Count in a cell would also return 7.
Everything else below is about what I've tried, and why I'd like to do it. If it's inadvisable, I'd be happy to know why, and if there's a better method.
Function process_control_F(raw_data As Variant)
Dim i As Integer
i = 0
For Each cell In raw_data
i = i + 1
Next cell
MsgBox i
End Function
My goal is to have the value returned by the MsgBox be returned instead to a Defined Name that can be reused in other forumulas. However, I cannot get the value to show. I have tried a variety of forms (too numerous to recall, let alone type here) similar to
Names.Add Name:="Value_Count", RefersTo:=i
I am trying to accomplish this without returning a ton of extra info to cells, just to recall it, hence the desire to return straight to a Defined Name.
I'm using a Function rather than Sub to streamline my use, but if that's the problem, I can definitely change types.
I am creating a version of a Statistical Control Chart. My desired end result is to capture a data range (generally about 336 values) and apply a series of control rules to them (via VBA), then return any values that fall outside of the control parameters to Defined Names that can then be charted or otherwise manipulated.
I've seen (and have versions of) spreadsheets that accomplish this with digital acres of helper columns leading to a chart and summary statistics. I'm trying to accomplish it mostly in the background of VBA, to be called via Defined Names to Charts — I just can't get the values from VBA to the Charts.
The interest in using a Function rather than a Sub was to streamline access to it. I'd rather not design a user interface (or use one), if I can just keystroke the function into a cell and access the results directly. However, as pointed out by Jean-François Corbett, this is quickly turning into a circuitous route to my goal. However, I still think it is worthwhile, because in the long-term I have a lot of iterations of this analysis to perform, so some setup time is worth it for future time savings.
With minor changes to your function, you can use its return value to accomplish what you want:
Function process_control_F(raw_data As Variant) As Integer ' <~~ explicit return type
Dim i As Integer
Dim cell As Variant ' <~~~~ declare variable "cell"
i = 0
For Each cell In raw_data
i = i + 1
Next cell
process_control_F = i ' <~~~~ returns the value i
End Function
You can then use that function in formulas. For example:

Properly Handling Large Amounts of Data

I've ventured into extremely unknown territory and I need some advice. I'm building an IRC bot for Twitch that could potentially contain hundreds of thousands of accounts. Previously I used Dictionary(of String, Integer) to store these accounts and their balance in memory, and just wrote them to a text file and saved it to disk. Now I'm storing a lot more data like their online time, whether they are a follower, or subscriber, how much they've donated. So I've started utilizing SQLite to store the accounts and I believe I need to utilize DataGridView with virtualmode to display these accounts and allow the user to edit any data. Am I on the right track so far? My aim is to keep it simple while managing larges amount of data, hopefully that wasn't an oxymoron.
Now I imagine the accounts in the SQLite database will need to be cached so that it's not constantly reading the database from the hard drive when a change needs to be made or when the user is scrolling through his list of accounts in the datagridview(which is in virtualmode). Am I right so far?
If there is another, more simpler method I could utilize please let me know, otherwise can someone help comprehend how I could cache these accounts? I did consider writing them to a Dictionary(of String, String) and then splitting the string when I needed to work with a specific value. Anyways I await your suggestions or comments.
Thank you.
As per my comment above, you need to look into classes. See below for little example...
Public Class Accounts
Public Property AccountID As Integer = 0
Public Property AccountName As String = String.Empty
Public Property IsFollower As Boolean = False
**'Add more properties as needed'**
Public Sub New()
End Sub
End Class
Next you can do a call to your database and get all the id's from the table; you can use these to query the rest of your data for a specific id...
Loop through your id's that you have and get their data...
Dim nAccount As Account = Nothing
For each blah blah blah....
nAccount = query from database... which will return your Account class object...
Now you can add this object (your account class) to a collection; for example a Dictionary(Of Integer, Account) Or ListOf()
As I have mentioned before there are a few different ways to go about this, it just depends on what you need to do and how you want to handle the data.

Force return values to be saved in VB.net

Is there a way in VB.net to force someone to save a value returned from a function?
Here's the reason:
I work with databases, and we have created a function to credit a person's account. However, we want to see the results before we commit them to the database:
Dim trans as List(Of Transaction) = Transaction.createCredit(agreement_id, amount)
However, we don't want anyone at our company to think that the createCredit function will also commit the transactions to the database. Is there a way to ensure that they save the return value?
Thanks in advance!
There is no way to force function return value to be collected by the caller.
This is not VB.NET specific behavior, it works in C# the same way. So this is perfectly valid syntax in VB.NET, with no warnings or errors:
Sub Main()
X()
End Sub
Function X()
Return 0
End Function
What you need is coding standards, unfortunately, you cannot force coding standards, you can only agree on them. There has to be mutual understanding and agreement in this, before you see any benefit from it.
you could rise an event at the end of the Transaction.createCredit function and use this to set a variable isSavedToDb = False
and at some state (probably the closing event) check that variable and call the Save function if needed.

Execute a user-defined function into another cell VBA Excel

I need to automatize a process which execute various (a lot) user-defined function with different input parameters.
I am using the solution of timer API found in I don't want my Excel Add-In to return an array (instead I need a UDF to change other cells) .
My question is the following: "Does anybody can explain to me HOW IT IS WORKING?" If I debug this code in order to understand and change what I need, I simply go crazy.
1) Let say that I am passing to the public function AddTwoNumbers 14 and 45. While inside AddTwoNumber, the Application.Caller and the Application.Caller.Address are chached into a collection (ok, easier than vectors in order not to bother with type). Application.Caller is kind of a structured object where I can find the function called as a string (in this case "my_function"), for example in Application.Caller.Formula.
!!! Nowhere in the collection mCalculatedCells I can find the result 59 stored.
2)Ok, fair enough. Now I pass through the two UDF routines, set the timers, kill the timers.
As soon as I am inside the AfterUDFRoutine2 sub, the mCalculatedCell(1) (the first -- and sole -- item of my collection) has MAGICALLY (??!?!?!!!??) obtained in its Text field exactly the result "59" and apparently the command Set Cell = mCalculatedCells(1) (where on the left I have a Range and on the right I have ... I don't know) is able to put this result "59" into the variable Cell that afterward I can write with the .Offset(0,1) Range property on the cell to the right.
I would like to understand this point because I would like to give MORE task to to inside a single collection or able to wait for the current task to be finished before asking for a new one (otherwise I am over-writing the 59 with the other result). Indeed I read somewhere that all the tasks scheduled with the API setTimer will wait for all the callback to be execute before execute itself (or something like this).
As you can see I am at a loss. Any help would be really really welcomed.
In the following I try to be more specific on what (as a whole)
I am planning to achieved.
To be more specific, I have the function
public function my_function(input1 as string, Field2 as string) as double
/*some code */
end function
I have (let's say) 10 different strings to be given as Field2.
My strategy is as follow:
1)I defined (with a xlw wrapper from a C++ code) the grid of all my input values
2)define as string all the functions "my_function" with the various inputs
3)use the nested API timer as in the link to write my functions IN THE RIGHT CELLS as FORMULAS (not string anymore)
3)use a macro to build the entire worksheet and then retrieve the results.
4)use my xlw wrapper xll to process further my data.
You may wonder WHY should I pass through Excel instead of doing everything in C++. (Sometime I ask myself the same thing...) The prototype my_function that I gave above has inside some Excel Add-In that I need to use and they work only inside Excel.
It is working pretty well IN THE CASE I HAVE ONLY 1 "instance" of my_function to write for the give grid of input. I can even put inside the same worksheet more grids, then use the API trick to write various different my_functions for the different grids and then make a full calculation rebuild of the entire worksheet to obtain the result. It works.
However, as soon as I want to give more tasks inside the same API trick (because for the same grid of input I need more calls to my_function) I am not able to proceed any further.
After Axel Richter's comment I would like to ad some other information
#Axel Richter
Thank you very much for your reply.
Sorry for that, almost surely I wasn't clear with my purposes.
Here I try to sketch an example, I use integer for simplicity and let's say that my_function works pretty much as the SUM function of Excel (even if being an Excel native function I could call SUM directly into VBA but it is for the sake of an example).
If I have these inputs:
input1 = "14.5"
a vector of different values for Field2, for instance (11;0.52;45139)
and then I want to write somewhere my_function (which makes the sum of the two values given as input).
I have to write down in a cell =my_function(14.5;11), in the other =my_function(14.5;0.52) and in a third one =my_function(14.5;45139).
These input changes any time I need to refresh my data, then I cannot use directly a sub (I think) and, in any case, as far as I understand, in writing directly without the trick I linked, I will always obtain strings : something like '=my_function(14.5;0.52). Once evaluated (for example by a full rebuild or going over the written cell and make F2 + return) will give me only the string "=my_function(14.5;0.52)" and not its result.
I tried at the beginning to use an Evaluate method which works well as soon as I write something like 14.5+0.52, but it doesn't work as soon as a function (nor a user-defined function) is used instead.
This is "as far as I can understand". In the case you can enlighten me (and maybe show an easier track to follow), it would be simply GREAT.
So far the comments are correct in that they repeat the simple point that a User-Defined Function called a worksheet can only return a value, and all other actions that might inject values elsewhere into the worksheet calculation tree are forbidden.
That's not the end of the story. You'll notice that there are add-ins, like the Reuters Eikon market data service and Bloomberg for Excel, that provide functions which exist in a single cell but which write blocks of data onto the sheet outside the calling cell.
These functions use the RTD (Real Time Data) API, which is documented on MSDN:
How to create a RTD server for Excel
How to set up and use the RTD function in Excel
You may find this link useful, too:
Excel RTD Servers: Minimal C# Implementation
However, RTD is all about COM servers outside Excel.exe, you have to write them in another language (usually C# or C++), and that isn't the question you asked: you want to do this in VBA.
But I have, at least, made a token effort to give the 'right' answer.
Now for the 'wrong' answer, and actually doing something Microsoft would rather you didn't do. You can't just call a function, call a subroutine or method from the function, and write to the secondary target using the subroutine: Excel will follow the chain and detect that you're injecting values into the sheet calculation, and the write will fail.
You have to insert a break into that chain; and this means using events, or a timer call, or (as in RTD) an external process.
I can suggest two methods that will actually work:
1: Monitor the cell in the Worksheet_Change event:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim strFunc As String strFunc = "NukeThePrimaryTargets" If Left(Target.Formula, Len(strFunc) + 1) = strFunc Then Call NukeTheSecondaryTargets End If End Sub
Alternatively...
2: Use the Timer callback API:
However, I'm not posting code for that: it's complex, clunky, and it takes a lot of testing (so I'd end up posting untested code on StackOverflow). But it does actually work.
I can give you an example of a tested Timer Callback in VBA:
Using the VBA InputBox for passwords and hiding the user's keyboard input with asterisks.
But this is for an unrelated task. Feel free to adapt it if you wish.
Edited with following requirements: It is necessary to run a user defined worksheet function, because there are addins called in this function and those work only within a Excel sheet. The function has to run multiple times with different parameters and its results have to be gotten from the sheet.
So this is my solution now:
Public Function my_function(input1 As Double, input2 As Double) As Double
my_function = input1 + input2
End Function
Private Function getMy_Function_Results(input1 As Double, input2() As Double) As Variant
Dim results() As Double
'set the Formulas
With Worksheets(1)
For i = LBound(input2) To UBound(input2)
strFormula = "=my_function(" & Str(input1) & ", " & Str(input2(i)) & ")"
.Cells(1, i + 1).Formula = strFormula
Next
'get the Results
.Calculate
For i = LBound(input2) To UBound(input2)
ReDim Preserve results(i)
results(i) = .Cells(1, i + 1).Value
Next
End With
getMy_Function_Results = results
End Function
Sub test()
Dim dFieldInput2() As Double
Dim dInput1 As Double
dInput1 = Val(InputBox("Value for input1"))
dInput = 0
iIter = 0
Do
dInput = InputBox("Values for fieldInput2; 0=END")
If Val(dInput) <> 0 Then
ReDim Preserve dFieldInput2(iIter)
dFieldInput2(iIter) = Val(dInput)
iIter = iIter + 1
End If
Loop While dInput <> 0
On Error GoTo noFieldInput2
i = UBound(dFieldInput2)
On Error GoTo 0
vResults = getMy_Function_Results(dInput1, dFieldInput2)
For i = LBound(vResults) To UBound(vResults)
MsgBox vResults(i)
Next
noFieldInput2:
End Sub
The user can input first a value input1 and then input multiple fieldInput2 until he inputs the value 0. Then the results will be calculated and presented.
Greetings
Axel

Improve this ugly piece of code

I'm writing a QR code generator in VB.net
First I check what value (of the QR code version) was chosen by the user.
Each version has fixed count of bits per mode (0001, 0010, 0100, 1000).
Basically what I got now is the following:
Private Function get_number_of_bits() As Integer
Dim bits As Integer
If listVersion.Value < 10 Then
If get_binary_mode(listMode.SelectedItem) = "0001" Then
bits = 10
End If
If get_binary_mode(listMode.SelectedItem) = "0010" Then
bits = 9
End If
If get_binary_mode(listMode.SelectedItem) = "0100" Or _
get_binary_mode(listMode.SelectedItem) = "1000" Then
bits = 8
End If
ElseIf listVersion.Value < 27 Then
If get_binary_mode(listMode.SelectedItem) = "0001" Then
bits = 12
End If
If get_binary_mode(listMode.SelectedItem) = "0010" Then
bits = 11
End If
If get_binary_mode(listMode.SelectedItem) = "0100" Then
bits = 16
End If
If get_binary_mode(listMode.SelectedItem) = "1000" Then
bits = 10
End If
Else
If get_binary_mode(listMode.SelectedItem) = "0001" Then
bits = 14
End If
If get_binary_mode(listMode.SelectedItem) = "0010" Then
bits = 13
End If
If get_binary_mode(listMode.SelectedItem) = "0100" Then
bits = 16
End If
If get_binary_mode(listMode.SelectedItem) = "1000" Then
bits = 12
End If
End If
Return bits
End Function
Which works but of course it is an ugly piece of ..... code :)
What would be a better way to write this?
EDIT
As requested.
listMode is a combobox which is filled with:
Private Function get_encoding_modes() As Dictionary(Of String, String)
Dim modes As New Dictionary(Of String, String)
modes.Add("0000", "<Auto select>")
modes.Add("0001", "Numeric (max. 7089 chars)")
modes.Add("0010", "Alphanumeric (max. 4296 chars)")
modes.Add("0100", "Binary [8 bits] (max. 2953 chars)")
modes.Add("1000", "Kanji/Kana (max. 1817 chars)")
Return modes
End Function
Code for get_binarymode
Private Function get_binary_mode(ByVal mode As String) As String
Dim modes As New Dictionary(Of String, String)
modes = get_encoding_modes()
Dim result As String = ""
Dim pair As KeyValuePair(Of String, String)
For Each pair In modes
If pair.Value = mode Then
result = pair.Key
End If
Next
Return result
End Function
"TL;DR girl" to the rescue! made the code less ugly! learned about LINQ in VB, and how do to (and not do) Lambdas. removed need for reverse dictionary search, removed a lot of repeating yourself, and just made things generally pleasant to work with. :) ♡
Okay, I wanted to take a stab at this, even though Visual Basic isn't my usual thing. However, there were some things that I thought I could improve, so I decided to take a stab. First of all, I created a solution and implemented some basic functionality because I am not fluent in VB and figured it would be easier to do that way. If you're interested, the entire solution can be found here: UglyCode-7128139.zip
I created a little sample form and tried to include everything I could glean from the code. Here's a screenshot:
This little app was really all I used to test the code; but even though I used this as target for the code I wrote, I think I came up with some good ways of dealing with things that can easily be made more generic. All of it is currently implemented in the main form code file, but there's nothing preventing it being pulled out into some more generic helper classes.
First, I tackled the lookups. One thing I wasn't sure of was the number of the third Version that could be selected, since it's covered by the Else part of the first big If statement in the question. This wasn't a problem for the lookup I created, since there was only the one unknown value. I chose 0 but it should probably be updated to the real value if there is one. If it's really just a default, then 0 should be fine for our purposes.
I guess first, let's look at the lookup for number of bits, and the lookup for encoding:
Lookups
You'll note that my lookups and a helper function are declared as Public Shared. I did this because:
* neither the lookups nor the helper function requires knowing anything about a specific instance of the class it belongs to.
* it allows you to create the item once for the entire application, so you avoid having to create it anew each time.
* multiple creations isn't an issue for this application, but I just did it on principle: for large lookups and/or applications which created many instances of a class containing a lookup, the memory and processing requirements can become burdensome.
BitsLookup:
' Maps from a Version and Mode to a Number of Bits
Public Shared BitsLookup _
As New Dictionary(Of Tuple(Of Integer, String), Integer) From
{
{VersionAndMode(10, "0001"), 10},
{VersionAndMode(10, "0010"), 9},
{VersionAndMode(10, "0100"), 8},
{VersionAndMode(10, "1000"), 8},
{VersionAndMode(27, "0001"), 12},
{VersionAndMode(27, "0010"), 11},
{VersionAndMode(27, "0100"), 16},
{VersionAndMode(27, "1000"), 10},
{VersionAndMode(0, "0001"), 14},
{VersionAndMode(0, "0010"), 13},
{VersionAndMode(0, "0100"), 16},
{VersionAndMode(0, "1000"), 12}
}
The idea here is very simple: instead of representing the lookup in a procedural manner, via the big If statement or via Select Case, I tried to see what the code was really doing. And from what I can tell this is it. Representing it in this kind of structure seems to me to fit better with the actual meaning of the data, and it allows us to express our ideas declaratively (what to do) rather that imperatively (how to do it). VB's syntax is a little bulky here but lets go through the parts.
Tuple(Of Integer, String)
A Tuple is just a convenient way to group data items. Until I saw it in .NET I had only heard of it in the context of a relational database. In a relational database a Tuple is approximately equivalent to a row in a table. There are a few differences, but I'll avoid going off-track here. Just be sure you know that a Tuple is not always used in the same sense as it is here.
But, in this case, it seemed to me that the data was organized as a lookup of the number of bits, based upon both the version and mode. Which comes first is not really relevant here, since either here (or in any procedural lookup), we could just as easily reverse the order of the items without it making a difference.
So, there is a unique "thing" that determines the number of bits, and that "thing" is the combination of both. And, a perfect collection type to use when you have a unique thing (Key) that lets you look up something else (Value) is of course the Dictionary. Also note that, a Dictionary represents something very much like a database table with three columns, Version, BinaryMode, and NumberOfBits or similar. In a database you would set a key, in this case a primary key and/or index, and your key would be the combination of both Version and BinaryMode. This tells the database that you may only ever have one row with the same values for those fields, and it therefore allows you to know when you run a query, you will never get two rows from one set of values for each.
As New Dictionary(Of Tuple(Of Integer, String), Integer) From
In VB this is the way to create a Dictionary using an initializer: create a New Dictionary(Of T1, T2) and then use the From keyword to tell it that an initializer list is coming. The entire initializer is wrapped in curly braces, and then each item gives a comma separated .Key and .Value for the item.
{VersionAndMode(10, "0001"), 10},
Now, the first item in our Dictionary is a Tuple(Of Integer, String). You can create a tuple either with something like New Tuple(Of T1, T2)(Item1Val, Item2Val) or something like Tuple.Create(Of T1, T2)(Item1Val, Item2Val). In practice, you will usually use the .Create method, because it has one very nice feature: it uses type inference to determine which type you actually create. In other words, you can also call Tuple.Create(Item1Val, Item2Val), and the compiler will infer T1 and T2 for you. But, there is one main reason that I created this helper function instead:
Public Shared Function _
VersionAndMode(Version As Integer, Mode As String) _
As Tuple(Of Integer, String)
Return Tuple.Create(Of Integer, String)(Version, Mode)
End Function
And that's because Tuple doesn't tell you anything about the data you are containing. I might even be tempted in a production application to even create a VersionAndMode class that simply Inherits Tuple<Of Integer, String) just because it's a lot more descriptive.
That pretty much covers the lookup initialization. But what about the actual lookup? Well, let's ignore for a moment where the values are coming from, but so, now the lookup is trivial. The complexity of the If statement in the original is now contained in what I believe is a much more descriptive fashion, it's a declarative way of stating the same information in that procedure. And with that out of the way, we can just focus on what we're doing instead of how we're doing it: Dim NumberOfBits = BitsLookup.Item(Version, Mode). Well, I do declare. :)
There's another lookup, the EncodingModes lookup, and there's more to be said about that, so I'll cover it in the next section.
The Methods
Once we have the lookup in place, we can take a look at the other methods. Here are the ones I implemented.
Number Of Bits Lookup
So, here's what's left of the big If conglomeration:
Public ReadOnly Property NumberOfBits As Integer
Get
Return BitsLookup.Item(
VersionAndMode(Version, BinaryMode)
)
End Get
End Property
There's not really much left to say about this one.
Form Initialization Method
When you have a nice designer, it's tempting to try to do everything there so there's no code to write. However, in our case all the data we need is already contained in the lookups we created. If we were to simply enter the items into the listbox as strings, we'd end up not only repeating ourselves, violating one of the general principles of development (DRY, Don't Repeat Yourself), but we're also losing the nice connections we already have set up with our data.
So, let's take a look at that last lookup:
Public Shared EncodingModes As New Dictionary(Of String, String) From
{
{"0000", "<Auto Select>"},
{"0001", "Numeric (max. 7089 chars)"},
{"0010", "Alphanumeric (max. 4296 chars)"},
{"0100", "Binary [8 bits] (max. 2953 chars)"},
{"1000", "Kanji/Kana (max. 1817 chars)"}
}
Here, again, we just have a declarative way of saying the same thing that was said in the method that created the data imperatively, and again, it's advantageous because we only need to create it one time, and after that look data up based on the key. Here our Key is the "Encoding Mode" and the Value holds the text to displayed for any particular Key. But, so, what happens if we just enter the text into our ListBox in the forms designer?
Well, two things. First, we have entered it twice now. Second, is now we either would have to create a different lookup to go back, or, we have to go against the grain in the way a Dictionary is used. It's not impossible, but as you can see in the original get_binary_mode function, it's not very clean either. Plus, we've lost the advantages of the declarative nature of the Dictionary.
So, how do we use the existing lookup to create our ListBox items without repeating ourselves? Well, one thought would be to just grab the Values and put them in a list, and then putting that in the .Items field on the ListBox. But, see, we didn't solve the other problem; still we have to go backward, from Value to Key (which in a Dictionary isn't even guaranteed to be unique).
Fortunately, there's a solution: using ListBox.DataSource. This allows us to take many different data structures, and feed them to the listbox (nom nom), rather than being limited to List<T> and things that implement IList. But this doesn't necessarily select the proper items for display, so what do we do if it displays the wrong property? Well, the final missing piece is ListBox.DisplayMember where we set the name of the property to be used for display.
So, here's the code we can use to set up our listboxes:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
listboxVersion.DataSource =
BitsLookup.Keys.Select(
Function(VAM As Tuple(Of Integer, String)) _
VAM.Item1()
).
Distinct().ToList()
If listboxVersion.Items.Count > 0 _
Then listboxVersion.SelectedIndex = 0
listboxMode.DisplayMember = "Item1"
listboxMode.DataSource =
EncodingModes.AsQueryable().Select(
Function(KVP As KeyValuePair(Of String, String)) _
Tuple.Create(KVP.Key, KVP.Value)
).
ToList()
If listboxMode.Items.Count > 0 _
Then listboxMode.SelectedIndex = 0
End Sub
So, I'm using functionality from LINQ here to get my data in whatever form makes sense from the lookups, setting that as the .DataSource, and then telling the ListBox which member to display. I love it when I get to tell things what to do. :) Now, I can't possibly do justice to Lambda Epxressions here, but let me take a quick stab. So, the first listbox is set up like so:
listboxVersion.DataSource =
BitsLookup.Keys.Select(
Function(VAM As Tuple(Of Integer, String)) _
VAM.Item1()
).
Distinct().ToList()
Each individual part is fairly understandable, and if you've worked with SQL or other types of queries, I'm sure this doesn't seem too unfamiliar. But, so, the problem with the way we have our data stored right now is that we only have the versions numbers that are in the Tuples in the BitLookup. Worse yet, there are several keys in the lookup that have each value contained in them. [Note that this is likely a sign that we should have that information's primary store somewhere else; it's ok for it to be part of something else, but we really shouldn't usually have data stored such that the primary store of the data contains duplicated information.]
As a reminder of what one of the rows looks like:
{VersionAndMode(10, "0001"), 10},
So, there are two things we have to accomplish here. Since the UI representation is the same as the actual number here, we don't have to worry about making something other than a list to hold the data. First, we need to figure out how to extract the values from the Keys of that lookup, and second, we need to figure a way to make sure that we don't have multiple copies of the data in our list.
Let's think about how we would do this if we were doing it imperatively. We'd say, ok, computer, we need to look through all the keys in the lookup. (ForEach). Then, we'd look at each one in turn, and take Item1's value (that's the property storing the version number), then probably check to see if it already existed in the list, and finally, if it was not already there (.IndexOf(item) < 0) we would add it. And this would be okay! The most important thing is that this gives the right behavior, and it is quite understandable.
However, it does take up space, and it's still very much concerned with how it's getting done. This would eliminate, for instance, improving performance without mucking about with the procedure itself. Ideally, we would want to be able to just tell the computer what to do, and have it hand it to us on a jewel-encrusted gold platter. (That's better than a silver one any day, right?) And this is where LINQ and Lambda expressions come in.
So, let's look at that code again:
listboxVersion.DataSource =
BitsLookup.Keys.Select(
Function(VAM As Tuple(Of Integer, String)) _
VAM.Item1()
).
Distinct().ToList()
We're using one of the LINQ extension methods .Select on the Key collection of the lookup, which does about what it sounds like: it selects something based on each item in the Key collection, and puts it all together into a nice collection for us. We're also using the .Distinct() extension on the result, which ensures that there's no more than one of each item in the list, and finally, we're using the ToList() method which puts everything into a list.
Inside the select is where the Lambda Expression comes in:
Function(VAM As Tuple(Of Integer, String)) _
VAM.Item1()
Caveat: VB only supports Lambda Expressions for things like this, not Lambda Statements. The difference is that a Lambda Expression does not specify a return type, and does not have an End Function. You'll notice I used a space, underscore pattern at the end of the first line, this is because Lambda Expressions must all be on one line, and the " _" tells the compiler to consider the next line to be continued as if it were one line. For full details on the restrictions, see Lambda Expressions (Visual Basic).
The parentheses on VAM.Item1() were inserted there for me by VB, but they are not required. But this function is what tells the .Select method which item to put into the new collection for each item in the source collection, and it also tells it what type should be collected (in this case an Integer). The default collection type for most of the common LINQ functions, including Select in this case is IEnumerable(T1), and in this case, since we are returning an Integer, the compiler can infer the type of the resulting collection, an IEnumerable(Integer). Distinct() remove duplicates and also returns IEnumerable(Integer), and ToList() returns a List(Integer) from an IEnumerable(Integer).
And that's type we need to set for our ListBox, so we're done with that!
And, also, there's the listbox with the Encoding Mode:
listboxMode.DataSource =
EncodingModes.AsQueryable().Select(
Function(KVP As KeyValuePair(Of String, String)) _
Tuple.Create(KVP.Key, KVP.Value)
).
ToList()
This code works the very same way: we take the EncodingModes lookup Dictionary with items like {"0000", "<Auto Select>"},, we perform a Select to get an IEnumerable returned to us, the function takes a single line (KeyValuePair) from the dictionary, but then it does something a little different. It returns a Tuple with the Key and Value both! Why becomes apparent in the final section, but the important thing is that we're returning something that has both the pieces of data in it, and this is in fact the solution to the problem with figuring out how to get the data we need from the listbox.
So, we're in the home stretch. Here are the last couple of items we use to set the textbox with the number of bits:
Private ReadOnly Property Version As Integer
Get
Dim SelectedVersion As Integer = _
listboxVersion.SelectedItem
Return SelectedVersion
End Get
End Property
This property just returns the current value from the ListBox, which contains the values we pulled out of the lookup in the setup.
Private ReadOnly Property BinaryMode As String
Get
Dim EncodingMode As Tuple(Of String, String) = _
listboxMode.SelectedItem
Dim RetVal As String = "0001"
If EncodingMode.Item1 <> "0000" _
Then RetVal = EncodingMode.Item1
Return RetVal
End Get
End Property
And this property pulls the BinaryMode, but notice: there's no need to use the Dictionary in reverse: since we used a DataSource, we can simply pull out the selected item, cast it to the data type we put in, and then we can get out the associated bit of data without ever having to go back to the Dictionary.
Just by the fact that the user selected a particular item, we know what the corresponding binary key is, and return that. And, the other cool thing about that is that even if there were duplicate Values in the Dictionary, there would be no ambiguity about which was the proper value. (Now, the user wouldn't know, and that's a problem, but can't solve everything at once. :D)
The one little hitch in that property was what to do if the EncodingMode turned out to be '0000'. (That had a value of "<Auto Select>" in the Values, and is not accounted for by the lookup.) So, I auto selected it to be "0001"! I'm sure a more intelligent manner would be chosen for a real application, but that's good enough for me, for now.
Pulling (Putting?) It All Together
Well, the very last piece of the puzzle, the thing that actually gets the number of bits and sets it to the TextBox on the form:
Private Sub btnSelect_Click(sender As System.Object, e As System.EventArgs) _
Handles btnSelect.Click
txtNumberOfBits.Text = NumberOfBits.ToString()
End Sub
So, all we had to do is take the NumberOfBits field which returns the number of bits based on the items the user has selected for Version and EncodingMode. Kinda anti-climactic, huh?
Well, sorry for the length, I hope this has been helpful, I know I learned a few things. :)
I'll suggest this 'improvement'.
get_binary_mode() gets called once. a bit of a performance gain.
Your 3 cases for listVersion.value are still 3, but easier to read. When you need to add a 4th, it's a simple job to add another Case and Exit Select. Be sure to keep the Exit Select statements in case a value like 9 comes along, as it satisifes both <10 and <27.
a separate function and separation of logic for each case (under 10, under27, etc). This should be more maintainable in the future.
When something needs changing, we know exactly where to go, and it's very localized.
Obviously my naming conventions need some work to have the intent expressed in more human readable/understandable terms.
certainly this answer contains more lines of code. I'd rather read & maintain smaller self-contained functions that do one thing (and one thing well). YMMV.
you could go one step further and get rid of the local variable bits. Simply Return AnalyzeUnderXX().
Private Function get_number_of_bits() As Integer
Dim mode As String = get_binary_mode(listMode.SelectedItem)
Dim bits As Integer
Select Case Convert.ToInt32(listVersion.Value)
Case Is < 10
bits = AnalyzeUnder10(mode)
Exit Select
Case Is < 27
bits = AnalyzeUnder27(mode)
Exit Select
Case Else
bits = AnalyzeDefault(mode)
End Select
Return bits
End Function
Private Function AnalyzeUnder10(input As String) As Integer
Select Case input
Case "0001"
Return 10
Case "0010"
Return 9
Case "0100" Or "1000"
Return 8
End Select
End Function
Private Function AnalyzeUnder27(input As String) As Integer
Select Case input
Case "0001"
Return 12
Case "0010"
Return 11
Case "0100"
Return 16
Case "1000"
Return 10
End Select
End Function
Private Function AnalyzeDefault(input As String) As Integer
Select Case input
Case "0001"
Return 14
Case "0010"
Return 13
Case "0100"
Return 16
Case "1000"
Return 12
End Select
End Function