After working some time in VB.NET I would like to get rid of Microsoft.VisualBasic dependencies.
Since with text files and string manipulation goes easy here I don't know what to do.
Is it possible to write equivalent code in VB.NET without using Microsoft.VisualBasic namespace and how this code should look like?
Dim fnum As Integer = FreeFile()
FileOpen(fnum, "Setup\myadmin", OpenMode.Random, OpenAccess.ReadWrite, OpenShare.Shared, Len(idstruct))
FilePut(fnum, idstruct, 1) 'structure data to file in record 1
FileClose(fnum)
As much as I sympathise with your desire to remove all references to the Microsoft.VisualBasic namespace, and as much as I think that doing so has value, sometimes it's just not worth the trouble. The namespace does contain some useful tools which are not easily reproduced without it.
For instance, the TextFieldParser comes to mind. It allows you to easily read CSV and fixed-width files. There is no other class like it in the .NET framework. So, is it worth it to reinvent the wheel just so that you don't reference the Microsoft.VisualBasic namespace? I would argue that it's not worth it.
While it would be possible to reproduce the behavior of FileGet and FilePut using FileStream and the StreamReader, StreamWriter, BinaryReader, and BinaryWriter classes, it's probably not worth all the trouble. The FileGet and FilePut methods are provided specifically for backwards compatibility, so if compatibility with old systems is your goal, as much as it pains me to say it, using FileGet and FilePut is an appropriate solution.
However, some of this advice hinges on the type of data. If, for instance, the structure only contains fixed width strings, that would be very easy to duplicate with the StreamReader and StreamWriter, or with the TextFieldParser. Or, if it contains just integers, perhaps it will be easy to reproduce with the BinaryReader and BinaryWriter.
However, even if you can easily reproduce the logic using other non-VB-only classes, doing so doesn't gain you anything. In fact, your code will be more complicated and it will be less self-documenting. When you see code using FileGet and FilePut, not only is it easy to tell what is being done, but it is also obvious that it is for backwards compatibility. If you replace them with your own logic, the necessity for backwards compatibility would not be obvious without adding comments to the code.
If you don't like looking at them, which I can certainly understand, it may be worth wrapping them in a wrapper class. For instance, you could create a data-access style class with load/save methods which internally just use FileGet and FilePut. Doing so would be good practice anyway. That way, if you ever choose to store the data in a different format, or a different data source (such as a database), you could change it in the one class without having to rewrite all of your code.
One other thing I've just found is this MSDN page about My.Computer.FileSystem:
http://msdn.microsoft.com/en-us/library/0b485hf7%28v=vs.90%29.aspx
which I found was referred to from the MSDN page on FilePut:
http://msdn.microsoft.com/en-us/library/0s9sa1ab%28v=vs.90%29.aspx
From posts like this one It's my understanding that it's just a wrapper for System.IO anyway, but it supposedly provides a "more convenient and understandable" interface to the underlying IO functions.
If you're referring to your use of the LEN() function (which is the only thing I can see that refers to Microsoft.VisualBasic namespace, unless I'm missing something), then you can just use String.Length instead. E.g. idstruct.Length, assuming idstruct is a String.
Look at System.IO.FileStream. The approach is a bit different, but it is quite simple.
Dim fs As New FileStream(mUserFile, FileMode.XXX, FileAccess.XXX)
or:
Using fs as New FileStream....
End Using
The main thing that will change is that rather than writing a structure, you would convert it to an array of bytes (Count would be the length of your array, offset 0 in your example):
fs.Write(byt(), lOffset, lCount)
You COULD wrap it all up in a class to emulate the old random access file method if there it a lot of legacy code to support. There is also a BinaryReader and BinaryWriter and you could also look into serialization if the data is large but mostly static.
Related
I have one VB6 ActiveX DLL that exposes a class INewReport. I added some new methods to this class and I was able to rebuild it and keep binary compatibility.
I have a second DLL that exposes a class clsNewReport, which implements the first class using:
Implements RSInterfaces.INewReport
Since I added new methods to INewReport, I had to also add those new methods to clsNewReport.
However, when I try to compile the second DLL, I get the binary-compatibility error "...class implemented an interface in the version-compatible component, but not in the current project".
I'm not sure what is happening here. Since I'm only adding to the class, why can't I maintain binary compatibility with the second DLL? Is there any way around this?
I think this is a correct explanation of what is happening, and some potential workarounds.
I made up a test case which reproduced the problem in the description and then dumped the IDL using OLEView from the old & new DLL which contained the interface.
Here is a diff of the old (left) and new IDL from INewReport:
Important differences:
The UUID of interface _INewReport has changed
A typedef called INewReport___v0 has been added which refers to the original UUID of the interface
(I assume that this is also what is happening to the code referred to in the question.)
So now in the client project the bincomp DLL refers to the original interface UUID; but that UUID only matches against a different name (INewReport___v0 instead of INewReport) than it did originally. I think this is the reason VB6 thinks there is a bincomp mismatch.
How to fix this problem? I've not been able to do anything in VB6 that would allow you to use the updated interface DLL with the client code without having to break bincomp of the client code.
A (bad) option could be to just change the client DLL to use project compatibility... but that may or may not be acceptable in your circumstances. It could cause whatever uses the client DLL to break unless all the consumers were also recompiled. (And this could potentially cause a cascade of broken bincomp).
A better but more complex option would be to define the interface in IDL itself, use the MIDL compiler to generate a typelib (TLB file), and reference that directly. Then you would have full control over the interface naming, etc. You could use the IDL generated from OLEView as a starting point for doing this.
This second option assumes that the interface class is really truly an interface only and has no functional code in it.
Here's how I setup a case to reproduce this:
Step 1. Original interface definition - class called INewReport set to binary compatible:
Sub ProcA()
End Sub
Sub ProcB()
End Sub
Step 2. Create a test client DLL which implements INewReport, also set to binary compatible:
Implements INewReport
Sub INewReport_ProcA()
End Sub
Sub INewReport_ProcB()
End Sub
Step 3: Add ProcC to INewReport and recompile (which also registers the newly built DLL):
(above code, plus:)
Sub ProcC()
End Sub
Step 4: Try to run or compile the test client DLL - instantly get the OP's error. No need to change any references or anything at all.
I was able to recreate your problem, using something similar to DaveInCaz's code. I tried a number of things to fix it, probably repeating things you've already tried. I came up with a possible hypothesis as to why this is happening. It doesn't fix the problem, but it may throw some additional light on it.
Quoting from This doc page:
To ensure compatibility, Visual Basic places certain restrictions on changes you make to default interfaces. Visual Basic allows you to add new classes, and to enhance the default interface of any existing class by adding properties and methods. Removing classes, properties, or methods, or changing the arguments of existing properties or methods, will cause Visual Basic to issue incompatibility warnings.
Another quote:
The ActiveX rule you must follow to ensure compatibility with multiple interfaces is simple: once an interface is in use, it can never be changed. The interface ID of a standard interface is fixed by the type library that defines the interface.
So, here's a hypothesis. The first quote mentions the default interface, which suggests that it may not be possible to alter custom interfaces in any way. That's suggested by the second quote as well. You're able to alter the interface class, because you are essentially altering its default interface. However, when you attempt to alter the implementing class in kind, to reflect the changes in your interface, your implementation reference is pointing to the older version of the interface, which no longer exists. Of course, the error message doesn't hint at this at all, because it appears to be based on the idea that you didn't attempt to implement the interface.
I haven't been able to prove this, but looking at DaveInCaz's answer, the fact that the UUID has changed seems to bear this idea out.
Where in the VB6/VBA project references do Array(), LBound(), and UBound() come from..? When I'm typing in code, they don't appear in the Autocomplete list (ctrl+space), they don't get autocompleted, and they must be typed out completely before the text editor recognizes them. And only when a left-parenthesis is typed will ToolTipText pop up with the command syntax. Also, they do not appear anywhere in Object Explorer.
There's probably a basic concept in play here that I'm not aware of. And it makes me wonder, what other commands/statements/keywords are hidden in the same way..? Is there a list somewhere..? I googled for info but didn't find anything, probably because I don't know what I'm looking for and using the wrong search terms.
I ask these questions because I have the habit of prefixing many VB6 built-in functions like this: VBA.Left(), VBA.Len, VBA.Instr(), and so on. But I can't figure out what reference prefeix to use with Array(), LBound(), and UBound(), or perhaps they're so basic to VB6 that they don't have one.
I do this prefixing because years ago I was working on a large project, and there were functions I was trying to use with the same name in different reference libraries. I was a newbie and it took me a while to figure out, and it was causing tremendous problems since the functions were just NOT working the way I thought they were supposed to. It was then that I developed the prefixing habit after I figured it out. It's just easier that way, and always ensures the expected functions are being used.
The reason that they don't appear as IntelliSense options (and also why they don't appear in the Object Browser) is that they aren't declared in the VBE7.dll typelib for some reason that's beyond me. The Array function is implemented in the .dll as rtcArray. The utility of knowing that is dubious, in that its sole argument is a ParamArray, which means that if you called it directly from VBE7.dll you would need to create an array to have it feed you back the same array... This partially explains why it isn't on the typelib - a COM call would need to do the same thing, and the marshaling would basically be doing the same thing as what you'd expect the function to return.
LBound and UBound don't even appear as functions in the export table, so my guess is that they are handled more like "keywords" than first class functions internally. This makes some sense, in that it's fairly trivial to check the bounds of a SAFEARRAY if you have a pointer to the automation struct (you just index into the rgsabound array at the end of it and read the cElements and lLbound from it. Again a guess, but I'd assume that this allows for flexibility in letting LBound and UBound function with both fixed length and variable length arrays. In the fixed case, the array is basically managed as a block of memory with an indexer (more like a VT_CARRAY than a VT_SAFEARRAY). I'd imagine that handling this internally was easier or more convenient than providing first-class functions.
You won't find Debug in the Object Browser either, nor its methods Assert and Print.
You won't find Statements that are used like methods, like Open, Close, Get and Put, which is why you don't get any Intellisense when you use those statements, and the syntax must be memorized.
You will find Load and Unload as members of VBA.Global, but it's not clear what they belong to otherwise, and their arguments are late-bound Objects. The VBA documentation states that Load and Unload are Statements, even though the Object Browser shows them as Methods.
Keep in mind that you can move the order of references and it will make a difference. Try moving VBA to the top or near the top of your list of references. I believe that if something else also defines a BASIC keyword, it steals it, in a sense. I once had Right disappear and because I was not aware of the order of references, had to change all references of Right to VBA.Right. It's possibly the same with the ubound, lbound, or array.
Background: Classes that inherit from Monobehaviour can't be serialized.
Premise: A way to save the data (variables/fields and their values) of a MonoBehaviour script so it can be serialized, and deserialize it again and use this data to "fill in" a corresponding MonoBehaviour script's variable/field values.
Tried so far:
Having a serializable "wrapper/container" class that has the same fields as the MB script, but does not inherit from MB. Works nicely but every MV script needs it's own wrapper class and it's own wrapping function.
Serializing a List<FieldInfo> and fill it with the MB's fields... Works 30%;
The FieldInfos get added but are of the wrong Type, and
When deserialzing their values can't be accessed because an instance of a class is needed, but only a list is available
I feel like it can't be that hard but my Reflection skills and related are limited but seeing as saving/loading is a rather common feature I hope there is either someone who did it or someone who can point me in the right direction.
There is no easy way to serialize a MonoBehaviour using a BinaryFormatter built in .NET. There are a few options you can consider:
Using a Memento Patter. That is (more or less) what you have tried to achieve using a wrapper. Momento assumes a saving and restoring internal state of objects, so serialization is one of techniques.
Using Unity Serialization, by declaring the methods:
void Serialize(){}
void Deserialize(){}
In your MonoBehaviour script, so within the methods you will choose the properties/fields you want to serialize/deserialize.
There is an interesting framework, source code is on GitHub. It has a custom serialization framework that lets you serialize almost anything (not only monobehaviors). I have never used it, here is the forum page on Unity3d forum, I believe it's worth a look.
The answer to the question is: ScriptableObject. That's what they're for.
Put your variables in a ScriptableObject and Unity will handle the serialisation and give you a custom editor and other nice features. Recommended.
I have a Util module in my VB.NET program that has project-wide methods such as logging and property parsing. The general practice where I work seems to be to call these methods directly without prefixing them with Util. When I was new to VB, it took me a while to figure out where these methods/functions were coming from. As I use my own Util methods now, I can't help thinking that it's a lot clearer and more understandable to add Util. before each method call (you know immediately that it's user-defined but not within the current class, and where to find it), and is hardly even longer. What's the general practice when calling procedures/functions of VB modules? Should we prefix them with the module name or not?
Intellisense (and "Goto Definition") should make it trivial to find where things are located, but I always preface the calls with a better namespace, just for clarity of reading. Then it's clear that it's a custom function, and not something built in or local to the class you're working with.
Maybe there's a subtle difference I'm missing, but I tend to use shared classes instead of modules for any code that's common and self-contained - it just seems easier to keep track of for me, and it would also enforce your rule of prefacing it, since you can't just call it from everywhere without giving a namespace to call it from.
I usually put the complete namespace for a shared function, for readibility.
Call MyNameSpace.Utils.MySharedFunction()
Util is such a generic name.
Example from the .Net framework. You have System.Web.HttpUtility.UrlEncode(...). Usually you refer to this as HttpUtility.UrlEncode since you have an import statement at the top.
The name of the class which has the static utility methods should be readable and explainable. That is good practice. If you have good class names they might just as well reside in a Utils namespace, but the class name should not be Utils.
Put all your logging in a Logger class. All your string handing in a StringUtils class etc. And try to keep the class names as specific as possible, and I'd rather have more classes with fewer functions than the other way around.
I'm about to start translating my vb.net application, and I don't want to use the default methods provided by Visual Studio to do so. I need my application to be very light, and it nearly doubles it size to use the resources option.
Therefore, I'm planning to use some thing like a class, of which I would have one instance per language. Since I don't want to distribute language files as separate files (I'd rather have them hard-coded), I would like to find an easy way to check if every field of the class is initialized. I was thinking of something like an Interface, where I would do something like this:
Public Interface Language
Dim HelloMsg As String
Dim GoodbyeMsg As String
End Interface
Public class English Implements Language
HelloMsg = "Hello!"
GoodbyeMsg = "Goodbye!"
End Class
It's obviously not the right way to do it (although I could use properties instead of vars), but I was wondering whether the was a way to have the compiler check that everything is translated and warn about it if not.
Anyway, maybe is there a much better way to handle this problem ?
Thanks a lot!
CFP.
I'm not convinced that you should dump the resource-based localization approach just because your app has grown in size. Indeed, it could've grown from 100 Kb to 200 Kb, but this is it! It won't grow this much more. And 200 Kb is nothing nowadays.
So my advice is to reconsider and go resource-based route.
I've decided to use a singleton class that loads a translation file, with a method that loops through all items on a form and translate on-the-fly. See Create Synchronicity source code for more details (more specifically TranslateControl in this code file)