load body of function from text file at runtime in vb.net - vb.net

I have made a vb project that works with registry and system management but my code is like this:
CheckAnswer(question_id)
it means that each question has own works with sys registry and sys management and I wanted that the program read each question from file at runtime.
my CheckAnswer body function that I made is :
Private Sub CheckAnswer(ByVal id As Integer)
Dim mark As Integer
mark = 0
''''''''''''''''''''''
Select Case id
Case 1
Dim r As Rectangle = Nothing
If GetTaskBarPosition(r, Me.Handle) Then
If r.Y = 0 And r.X = 0 Then mark = 1
End If
Case 2
If My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\", "TaskbarSizeMove", 1) = 0 Then mark = 1
end case
but I wanted to do this work at runtime and say to program that read function from a file not from the source code for flexibility and adding new questions without changing the program source and just with changing the function file.
I have searched this site and others for code generation and the other things like this and code provider. I have get a project from "code project" but give me compile errors.
I do not want to generate separate class code because I have implemented imports and libraries in my own class and I want to say the program just which one of them I want to use in my function file.

It is possible to write VB.Net script files and execute them at runtime using the VBCodeProvider, in the future you will be able to make use of the Roslyn compiler if required.
I have a short code example for compiling and running C# Scripts, to make it work for VB.Net you would simply need to convert the code from C#, and use the VB.Net provider.
Another option would be to use F# which supports script files out-of-the-box (extension .fsx) which can be easily edited and executed.

Related

ZXing.NET EAN8Writer getChecksum

I want to check my (bar)code or get missing checksum number before creating a barcode picture in VB.NET. This is critical parts of minimized example on how this look like:
Imports ZXing
Imports ZXing.Common
Imports ZXing.OneD
...
Dim writer As EAN8Writer = New EAN8Writer
Dim data As String = "1234567" '(0)
Dim check As Integer = UPCEANReader.getStandardUPCEANChecksum(data)
I find that part of code in a various examples on the net. But on my system I get error 'getStandardUPCEANChecksum is not a member of UPCEANReader'. Why this don't work as expected?
Is here any other way to get checksum for such case except to calculate it manually?
The method UPCEANReader.getStandardUPCEANChecksum() is declared as "internal" and can't be accessed from outside the library (without using reflection or similar stuff).
You can copy the source code into your own application if you want to use it.

Remove namespace or classname from VB.Net when used in VBA [duplicate]

Base Reference: Ten Code Conversions for VBA, Visual Basic .NET, and C#
Note: I have already created and imported a *.dll, this question is about aliases.
Let's say the programmatic name of a Test class is TestNameSpace.Test
[ProgId("TestNamespace.Test")]
public class Test ...
Now, say a C# solution has been sealed and compiled into a *.dll and I'm referencing it in a Excel's VBE. Note: at this point I cannot modify the programmatic name as if the *.dll wasn't written by me.
This is in VBA : Instead of declaring a variable like this:
Dim myTest As TestNameSpace.Test
Set myTest = new TestNameSpace.Test
I'd prefer to call it (still in VBE)
Dim myTest As Test
Set myText = new Test
In C# you would normally say
using newNameForTest = TestNamespace.Test;
newNameForTest myTest = new NewNameForTest;
Note: Assume there are no namespace conflicts in the VBA project
Question: is there an equivalent call in VBA to C# using or VB.NET imports aliases?
Interesting question (constantly using them but never thought about their exact meaning). The definition of the Imports statement (same for using) is pretty clear: its only function is shortening the references by removing the corresponding namespaces. Thus, the first question to ask is: has VBA such a thing (namespaces) at all? And the answer is no, as you can read from multiple sources; examples: Link 1 Link 2
In summary, after not having found a single reference to any VBA statement doing something similar to Imports/using and having confirmed that VBA does not consider the "structure" justifying their use (namespaces), I think that I am in a position to say: no, there is not such a thing in VBA.
Additionally you should bear in mind that it wouldn't have any real applicability. For example: when converting a VB.NET code where Imports might be used, like:
Imports Microsoft.Office.Interop.Word
...
Dim wdApp As Application
the code would be changed completely, such that the resulting string will not be so long:
Dim wdApp As Word.Application ' Prefacing the library's display name.
I think that this is a good graphical reason explaining why VBA does not need to have this kind of things: VB.NET accounts for a wide variety of realities which have to be properly classified (namespaces); VBA accounts for a much smaller number of situations and thus can afford to not perform a so systematic, long-named classification.
-------------------------- CLARIFICATION
Imports/using is a mere name shortening, that is, instead of writing whatever.whatever2.whatever3 every time you use an object of the given namespace in a Module/ Class, you add an Imports/using statement at the start which, basically, means: "for all the members of the namespace X, just forget about all the heading bla, bla".
I am not saying that you cannot emulate this kind of behaviour; just highlighting that having an in-built functionality to short names makes sense in VB.NET, where the names can become really long, but not so much in VBA.
The answer is no: there is a built-in VBE feature that recognizes the references added to a project and creates aliases at run-time(VBE's runtime) if there are no name collisions
In case of name conflicts in your registry all . dots will be replaces with _ underscores.
» ProgId's (Programmatic Identifiers)
In COM, it is only used in late-binding. It's how you make a call to create a new object
Dim myObj = CreateObject("TestNamespace.Test")
» EarlyBinding and LateBinding
In early binding you specify the type of object you are creating by using the new keyword. The name of you object should pop up with the VBA's intellisense. It has nothing to do with the ProgId. To retrieve the actual namespace used for your object type - open Object Explorer F2 and locate it there
This article explain where the names come from in Early Binding Section
use the same link for When to use late binding
for MSDN Programmatic Identifiers section please see this

Intellisense not finding vb.net Extension

I created an extension method in VB.NET in Visual Studio 2013 but it will not show up in Intellisense.
Imports System.Security.Claims
Imports System.Runtime.CompilerServices
Imports Connect.Common.Portable
Namespace Authorization
Public Module ClaimsPrincipalExtensions
<Extension()>
Public Function CurrentFirmNumber(ByVal principal As ClaimsPrincipal) As Integer
Dim c As Claim = principal.FindFirst(AuthorizationClaimTypes.LOGGED_IN_FIRM_NUMBER)
If (c IsNot Nothing) Then
Dim firmNumber As Integer = 0
If (Integer.TryParse(c.Value, firmNumber)) Then
Return firmNumber
End If
End If
Return 0
End Function
End Module
End Namespace
I have tried everything I could find on StackOverflow and other sites to solve this to no avail, including everything mentioned here.
In my calling code I include the right namespace, and the compiler and runtime are perfectly happy if I call this extension. That is, the code runs fine and correctly calls the extension method. It is simply intellisense that doesn't show it to me.
However, if I try to reference the method directly using the full namespace, as opposed to from the extended object, it shows up in intellisense.
Any ideas?
UPDATE:
So, it gets weirder. I had a colleague open up the same source and he gets intellisense.
As well, original extensions that used to work for me now have the same intellisense problem. However, if I start typing out the extension name intellisense does see it once it becomes a unique name.
For example, If I type "CurrentPrincipal.Current.C" Intellisense suggests "Claims", but not "CurrentFirmNumber", as that is part of the type. However, if I add a "u" it then suggests "CurrentFirmNumber", which is my extension.

.net load configuration in class library

let's say i have :
1) 1 WindowsForm on "A" Project
2) 1 WindowsForm on "B" Project
3) 1 class library (GAC)
Condition
Both of Project references is same
Part 1 :
I have my.settings in my class library to save configuration with public function
Part 2 :
I create value/configuration from "A" and store it in my class library.
settings has been successfully saved, and load the value/configuration with no errors
Question :
1). Why i can't load the value/configuration from "B" ? NullException shown
First I think, to use my.resources in class library but, my.resources is readonly
2). What best solution to connecting 1 class library to multiple project
code in class library to save value
Public Sub Kucing_simpan(ByVal value As String)
My.Settings.Kucing = value
My.Settings.Save()
End Sub
code in class library to load value
Public Function kucing_ambil()
Dim value As String
value = My.Settings.Kucing
Return value
End Function
code in "A"
dim save as new Zombie.Kencing 'My class Library Name
save.Kucing_simpan(textbox1.text)
code in "B"
dim load as new Zombie.Kencing 'My class Library Name
DataGridView1.Rows(0).Cells(1).Value = load.kucing_ambil
You cant do what you are trying to do - at least not the way you are going about it.
First, you have to understand how/where Settings are saved. With default naming of the app and such, project A - WindowsApplication1 will save its settings to something cryptic such as:
C:\Users\<UserName>\AppData\Local\Microsoft\_
WindowsApplication1_Url_ggn13vigzyicmtfkwaa3vi5tyxn0sy3r\1.0.0.0\user.config
NET creates the hash to make sure that apps with the same name have a different safe location to store settings. So, WindowsApplication3 will have a different hash; this is also how your 17th project with the name WindowsApplication1 doesnt accidentally load or find the settings of WinApp 1-16.
Next, your Settings Class Lib is not a separate application. As a DLL, it is operating as if it was a set of functions and such associated with the App calling it. So when Project A saves settings thru the ClassLib, they are saved to a different location than Project B. Even using a Class Lib, NET uses Application credentials and info to concoct the filename and path.
What you can do is write a Class which defines all the possible settings (or creates a List or Dictionary of them) then save to a fixed, known location such as:
Private Comp As String = "ZiggySoft"
Private Prod As String = "ZiggyWare"
Private settingsFile As String
'...
settingsfile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
settingsfile = Path.Combine(settingsfile, Comp, Prod, "usersettings.dat")
This will result in:
"C:\Users\\AppData\Roaming\ZiggySoft\ZiggyWare\usersettings.dat"
Include the same file in each project (Add Existing Item, maybe pick Add As Link from the dropdown). Now, you can read and write your Settings to a file you are in charge of. You can save/load the entire class or List in 3-5 lines of code if you serialize it.
When Project A loads the settings, it would also get those which only apply to B or J or V, but common ones would and could be shared.

.NET Default Properties Error [duplicate]

This question already has answers here:
Why can I access an item in KeyCollection/ValueCollection by index even if it doesn't implement IList(Of Key)?
(2 answers)
Closed 6 years ago.
I have a VB.NET project where I am able to iterate through the keys and values collections of a dictionary object using an index:
MyDictionary.Keys(idx)
MyDictionary.Values(idx)
When this code is taken from the test project and placed into the real project I get the following error:
'System.Collections.Generic.Dictionary(Of Double, String).KeyCollection' cannot be indexed because it has no default property.
and
'System.Collections.Generic.Dictionary(Of Double, String).ValueCollection' cannot be indexed because it has no default property.
This is using VB.NET and VS 2008. I don't know what the difference would be from one project to the next that would cause this error. The test is a console application and the program is a winforms app.
What conditions would cause the default property of these collections to change?
Edit - Thank you for all of the answers that tell me how to loop through a dictionary. Those, answers, however, do not answer my question of why I can use an index in one project and not the other. Should I not be able to copy and paste the code from one .net project to another and have it work the same? And, no, option strict, is not the cause of the problem.
Edit - Attempt to reproduce what I'm seeing:
Create a new VB.NET Console Application using VS 2008
Copy and paste the following code into the module:
Imports System.Collections
Imports System.Collections.Generic
Module Module1
Public dtf As Dictionary(Of Double, String)
Public Sub BuildDictionary()
dtf = New Dictionary(Of Double, String)
dtf.Add(1.0, "1")
dtf.Add(0.0, "0")
End Sub
Public Sub Search()
For idx As Integer = 0 To dtf.Keys.Count - 1
If dtf.Keys(idx) = 0 Then
Exit Sub
End If
Next
End Sub
Sub Main()
End Sub
End Module
In the line in sub search that says "dtf.Keys(idx) = 0" place your cursor after the right parenthesis and backspace you should get a tooltip that says, "<Extension> ElementAtOrDefault(index as Integer) as Double - index: the zero based element of the index to retrieve.
I am not getting that in my other project. Even though it seem I have the same references and settings.
KeyCollection does not implement indexers like that, you must enumerate through the MyDictionary.Keys.
c#
foreach(double key in MyDictionary.Keys)
Console.Write( MyDictionary[ key ] )
vb
For Each key As Double in MyDictionary.Keys
Console.Write( MyDictionary( key )
Next key
Looping with a for(;i++;) wouldn't be the correct way of going through your hashtable (dictionary) since it is not an array it really has no concept of an array index (array[index])
I bet your real project had OPTION STRICT ON, as all projects should, and that your test project had it OFF. That's why you didn't get a compiler error in your test project.
EDIT: the poster says he has OPTION STRICT ON for both projects. That makes this more interesting.
I still think the most likely reason for this difference is that in one case, the compiler compiled the code and saw the error; but in the other case, the compiler didn't comile the code. Is this the same version of Visual Studio on the same machine at the same time? Same .NET Framework version in both cases?
Are these both the same type of project, for instance, are they both console applications? I ask because ASP.NET Web Site "projects" usually don't attempt to compile code until the code is called. If your test project were such a "project", and if you didn't actualy test the code (that is, if you didn't actually step into this code and see it work), then you might have assumed that the fact you could press F5 meant that all the code was compiled, when it wasn't.
My next thoughts would be to see if MyDictionary was really of the same type in both cases.
Beyond that, if you really need to know why this happened, I'd make a copy of the "real" project, and start changing it to be more and more like the test project. This would probably be a matter of mass deletions at first. I'd keep changing it either until the problem was found, or until the two were identical.
EDIT 2: The default console project imports the System.Linq namespace (see the "References" tab in project properties). This import brings the ElementAtOrDefault extension method into scope. This extension method extends IEnumerable(Of T); in your case IEnumerable(Of Double), which is what the Keys property implements.
What surprises me about this is that VB.NET is automatically applying this extension method. In C#, the method would need to be explicitly named.
If you remove the Import of System.Linq, you'll find that your test application gets the same error as the production application.
The Keys and Values property of Dictionary(Of TKey,TValue) do not have an indexer property. They are implementations of ICollection vs. IList and hence don't support accesses by Index. If you want to iterate through a Dictionary, the best way is a For Each loop.
For Each pair in MyDictionary
Dim key = pair.Key
Dim value = pair.Value
Next
EDIT
Have you checked to make sure that System.Core is referenced in both projects and that you have a project level imports for System.Linq? That's the only thing I can think of that would produce a difference in ElementAtOrDefault which is a method inside of system.Core.
I'm still a bit baffled why that method would be bound to for a simple indexer. Going to look into that