Calling function of Exe project in referenced aticvex project in vb6 - vb6

Calling function of Exe project in referenced aticvex project in vb6
I have one AtiveX project in VB6 (Lets call it A )
i have another Exe project in VB6 (Lets call it B )
Project A is referenced in Project B
but now i have a requirement that i want to call function of B inside A
is there a way Can we do it in VB6?
if yes what do i need to search.Already tried searching on Google but not sure i could explain what to search
As i didn't work much on VB6 so i am kind a stuck here what to do

First off let me say that when you run into this problem it is often a sign that the code organization could be improved. Perhaps some modules in A actually should be in B, or they could be broken down in a more modular way that would resolve the problem. I would first encourage you to think about the problem this way.
That said, there are technical ways of doing what you want, I've suggested some examples below.
One approach to this is to utilize an interface. The interface would be provided by A.dll and the class used to implement it is provided by B.exe.
This is rough pseudocode just to sketch out the concept.
Within project A:
Create a class to act as an interface (called ISample). Within ISample have at least one sub or function defined, so you would have ISample.SomeProcedure.
Elsewhere in project A, you need some property or procedure SomeClassInA.RunSampleFunction which will accept an object of type ISample and then call SomeFunction.
Within project B:
Create another class SampleImplementation which Implements the ISample interface. This means it will have an actual concrete implementation of SomeFunction.
From B, create a new object of type SampleImplementation and then pass it to the code in A:
Dim impl As SampleImplementation
Dim objectFromA As SomeClassInA
Set impl = New SampleImplementation
Set objectFromA As New SomeClassInA
' Pass the object from B to A, where A can call its methods:
objectFromA.SomeProcedure impl
This avoids circular references and is a generally object-oriented pattern which I've used before. I will note however that the interface concept in VB6 has some annoyances that you'll have to live with, but for something like this it can be a good tool.
A different approach would be to have a class in A which exposes an event. You can then declare an object from that class in B using WithEvents and attach an event handler to the class. The event handler is just a procedure which exists in B, but now can be called by A.
Events in VB6 also have some limitations (specifically that the WithEvents object has to be within global scope IIRC) but you can usually live with / work around those problems as well.
The interface approach may be more general and a more powerful way to share information between A and B, but the event approach could be quicker to get working. Depends a lot on the specifics of what you need to accomplish.

Related

How to create a wrapper DLL/Type Library in VB6?

In my previous question, I asked why I kept getting the error message bad DLL calling convention when trying to call functions from a DLL. The general consensus was that I needed to change the calling convention to cdecl. Makes sense.
Unfortunately, I cannot place it right there on the function declaration importation. I had to either "create a wrapper DLL" or "create a type library for the DLL."
I am very unfamiliar with VB as my main focus at work is C# and this is the first time working in the language for a very long time. I'm not sure exactly how to accomplish this task.
I'm also confused as to how a wrapper DLL helps things. Supposedly I can't decorate a function import with cdecl in my code but if I move that exact function import to a new VB6 DLL and then reference that DLL it suddenly works?
I actually think this question was better on the topic.
To sum up, you can "place it right there on the function declaration importation", but the VB6 IDE doesn't know how to debug such a thing. But the compiler deals with it just fine. Once you compile it into a dll then your main project can access the functionality that was compiled.
Perhaps you are asking how to move these into a dll? If that is the case, you need to create a new Project of type "ActiveX Dll". Name it something like PwrUSB. Next, add a class (or rename the default/empty one if it is provided) to something like PwrUSBApi. Next, in the properties window, set the class to GlobalMultiUse. In a module called MDeclares, drop in all of your declarations:
'from your other post...
Public Declare Function InitPowerDevice CDecl Lib "PwrDeviceDll.dll" (ByRef firmware() As Byte) As Long
Back in your PwrUSBApi class:
'forward your calls to the dll
Public Function InitPowerDevice (ByRef firmware() As Byte) As Long
InitPowerDevice = MDeclares.InitPowerDevice(firmware)
End Function
You could create a more fully fledged object model from the API, but I'd start with this simple wrapper until you sort out all of the APIs.
Oh yeah, back in your main project you'd add a reference your new wrapper PwrUSB.dll in the Project menu. Then in the code you would use it something like this:
Dim numOfDevices as Long
Dim firmware() As Byte
Redim firmware(0 to 31)
numOfDevices = PwrUSB.InitPowerDevice(firmware)
Good luck.
A wrapper DLL in VB6 would still need to use the CDecl decorator or else a typelib created to deal with the DLL's function signatures.
The only advantage in creating a VB6 wrapper for this is to make it easier to debug the calling program from within the VB6 IDE, where CDecl has no effect. The wrapper would be small, and created once as a native code DLL, making CDecl effective there.
See your other thread(s) for additional answers. I suspect your real problem is that you were not passing the right kind of argument.

Registering all types in Assembly for Unity

I'm working on a large Asp.Net MVC3 application (>50 views) and we are currently planning on using Unity for our dependency injection framework. For ease of maintenance, I would like to be able to query the assembly to find all of the base types, then register them with Unity.
Based on sample code from the Unity MVC3 Project for registering all controllers, I tried the following code -
var orchestratorTypes = (from t in Assembly.GetCallingAssembly().GetTypes()
where typeof(IOrchesratorBase).IsAssignableFrom(t) &&
!t.IsAbstract
select t).ToList();
orchestratorTypes.ForEach(t => container.RegisterType(t);
When I run the application I get the following error message
The current type, WwpMvcHelpers.BaseClasses.IOrchesratorBase, is an interface and cannot be constructed. Are you missing a type mapping?
If I register the class using individually, as below -
container.RegisterType<IOrchesratorBase, HomeOrchestrator>();
Everything works correctly. Is there a way to do this so that I don't have to register each type individually?
EDIT
Per request, my inheritance hierarchy is
HomeOrcestrator <- IOrchesratorBaseList<LocalModel>
<- OrchesratorBase<LocalModel> <- IOrchesratorBase
The usage in the controller is
public class HomeController : ControllerListBase <HomeOrchestrator, LocalModel>
{
public HomeController() {}
public HomeController(IOrchesratorBase homeOrchestrator) {
this.Orchestrator = (HomeOrchestrator) homeOrchestrator;
}
The LINQ to get the types appears to work. I don't think that's your problem.
You'll get a similar error if you just write
container.RegisterType(typeof(HomeOrchestrator));
and call container.Resolve<IOrchesratorBase>().
In other words, RegisterType(t) is not the same as RegisterType<I, T>().
The real question is, what are you resolving and how do you want it resolved? Your query is finding implementors of IOrchesratorBase. Are your injection constructor parameters of that type? If so, what's Unity supposed to do when 20 types implement that interface?
Can you provide more information on your class/interface hierarchy, constructor parameters, and what you expect/want to happen?
(I'd refactor to change IOrchesratorBase to IOrchestratorBase, BTW.) :)
Edit
Based on the edited question, the problem is that, in order to resolve a HomeController, Unity is looking for a type registration for IOrchesratorBase. It determines the interface type by the parameter types of the constructor with the most parameters.
If you write container.RegisterType<IOrchesratorBase, HomeOrchestrator>() the answer is obvious - Unity will construct an instance of HomeOrchestrator and inject it.
Now, is there more than one type that implements IOrchesratorBase? If so, and you register both of them (explicitly), Unity will use whichever one you register last. That may not be what you want.
If you have multiple controllers, each taking a different interface type in their constructors (with only one implementation per interface), you'll need to figure out what each interface type is and re-run your LINQ registration for each one. That could be done via reflection - find the orchestrators or the controllers.
If you have multiple controllers, each taking the same interface type in their constructors and you want different implementations for each, you've got a problem. You'd have to register named types and determine the names somehow, or something similar.
Unity isn't magic. It can't figure out your intentions.
Addendum
Unity can operate in a convention-over-configuration mode; see Using Unity With Minimal Configuration.

vb6 : accessing registry values

I'm writing a simple vb6 button which tests the access of the registry values.
I have the following:
Private Function registry_read(key_path, key_name) as variant
Dim registry as object
set registry = CreateObject("WScript.shell")
registry_read = registry.regread(key_path & key_name)
End function
Private Sub Command1_Click()
MsgBox registry_read("HKEY_LOCAL_MACHINE\SOFTWARE\PROCESS\frmMain_Values\", "Version")
end Sub
I have Project Menu -> References
and select Microsoft WMI Scripting V1.1 Library selected
and Windows Script Host Object Model referenced
however my msgbox is still coming up blank. I did check the registry path and it is correct. any ideas?
thanks in advance.
You need to comment out the line 'on error resume next' while you are developing. If an error is occurring, you will not be able to see the details. It could be not found or access denied etc.
Also there are two ways to reference an object. Early binding ie Dim rs as new adobdb.recordset and late binding set rs = CreateObject("Adodb.recordset"). The first method (early binding) forces you to declare a reference and the second (late) does not. There are advantages and disadvantages to both (ie early binding is faster, gives intellisense, easier debugging, etc) http://word.mvps.org/faqs/interdev/earlyvslatebinding.htm
#bugtussle While your statements are correct, wqw's statements are also. Whether you use the New keyword or CreateObject actually hasn't anything to do with whether an object is early or late bound. What does matter is whether you declare the object variable with a registered type or not. I believe that you actually explain this correctly in your article.
I'd like to mention also that your article is well-written and has good information, but IMHO contains also a couple of minor inaccuracies. What you call "Dual Interface" binding in your article (and explain well) is generally referred to as "vTable" or "very early" binding. VB6 supports vTable binding where possible.
Now, as you have said, the sole requirement to be a COM class is that the class must implement iUnknown. A "dual interface" simply means a COM class that implements both iUnknown and iDispatch: a COM class that supports late binding must implement the latter. VB doesn't directly support COM objects that don't implement iDispatch (having some COM classes that don't support late binding and some that do would pretty clearly be problematical in VB); in other words VB only supports COM classes that implement a dual interface. (However, there are tricks using SendMessage's GETOLEINTERFACE message that bypass the requirement.)
Also, it isn't quite that iUnknown is bypassed altogether, it is that iUnknown.QueryInterface() is bypassed, instead going directly to the virtual table. iUnknown.AddRef() is still called, of course.
Regarding New vs. CreateObject: VB has an optimization strategy for classes defined within a project that are instantiated within that project using the New keyword. However, there are also important differences between the two if you are using a class outside of a project context; this page http://msdn.microsoft.com/en-us/library/Aa241758 does a good job of summarizing them.
I'm curious as well to know what error the OP got. :)

CodeIgniter: Decision making for creating of library & helper in CodeIgniter

After developing in CodeIgniter for awhile, I find it difficult to make decisions when to create a custom library and when to create a custom helper.
I do understand that both allow having business logic in it and are reusable across the framework (calling from different controller etc.)
But I strongly believe that the fact that CI core developers are separating libraries from helpers, there has to be a reason behind it and I guess, this is the reason waiting for me to discover and get enlightened.
CI developers out there, pls advise.
i think it's better to include an example.
I could have a
class notification_lib {
function set_message() { /*...*/}
function get_message() {/*...*/}
function update_message() {/*...*/}
}
Alternatively, i could also include all the functions into a helper.
In a notification_helper.php file, i will include set_message(), get_message(), update_message()..
Where either way, it still can be reused. So this got me thinking about the decision making point about when exactly do we create a library and a helper particularly in CI.
In a normal (framework-less) php app, the choice is clear as there is no helper, you will just need to create a library in order to reuse codes. But here, in CI, I would like to understand the core developers seperation of libraries and helpers
Well the choice comes down to set of functions or class. The choice is almost the same as a instance class verses a static class.
If you have just a simply group of functions then you only need to make a group of functions. If these group of functions share a lot of data, then you need to make a class that has an instance to store this data in between the method (class function) calls.
Do you have many public or private properties to store relating to your notification messages?
If you use a class, you could set multiple messages through the system then get_messages() could return a private array of messages. That would make it perfect for being a library.
There is a question I ask myself when deciding this that I think will help you as well. The question is: Am I providing a feature to my framework or am I consolidating?
If you have a feature that you are adding to your framework, then you'll want to create a library for that. Form validation, for example, is a feature that you are adding to a framework. Even though you can do form validation without this library, you're creating a standard system for validation which is a feature.
However, there is also a form helper which helps you create the HTML of forms. The big difference from the form validation library is that the form helper isn't creating a new feature, its just a set of related functions that help you write the HTML of forms properly.
Hopefully this differentiation will help you as it has me.
First of all, you should be sure that you understand the difference between CI library and helper class. Helper class is anything that helps any pre-made thing such as array, string, uri, etc; they are there and PHP already provides functions for them but you still create a helper to add more functionality to them.
On the other hand, library can be anything like something you are creating for the first time, any solution which might not be necessarily already out there.
Once you understand this difference fully, taking decision must not be that difficult.
Helper contains a group of functions to help you do a particular task.
Available helpers in CI
Libraries usually contain non-CI specific functionality. Like an image library. Something which is portable between applications.
Available libraries in CI
Source link
If someone ask me what the way you follow when time comes to create Helpers or Libraries.
I think these differences:
Class : In a nutshell, a Class is a blueprint for an object. And an object encapsulates conceptually related State and Responsibility of something in your Application and usually offers an programming interface with which to interact with these. This fosters code reuse and improves maintainability.
Functions : A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value. You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.
So go for Class i.e. libraries if any one point matches
global variable need to use in two or more functions or even one, I hate using Global keyword
default initialization as per each time call or load
some tasks are private to entity not publicly open, think of functions never have public modifiers why?
function to function dependencies i.e. tasks are separated but two or more tasks needs it. Think of validate_email check only for email sending script for to,cc,bcc,etc. all of these needs validate_email.
And Lastly not least all related tasks i.e. functions should be placed in single object or file, it's easier for reference and remembrance.
For Helpers : any point which not matches with libraries
Personally I use libraries for big things, say an FTP-library I built that is a lot faster than CodeIgniters shipped library. This is a class with a lot of methods that share data with each other.
I use helpers for smaller tasks that are not related to a lot of other functionality. Small functions like decorating strings might be an example. Or copying a directory recursively to another location.

How to construct two objects, with each other as a parameter/member

I have two classes that each need an instance of each other to function. Ordinarily if an object needs another object to run, I like to pass it in the constructor. But I can't do that in this case, because one object has to be instantiated before the other, and so therefore the second object does not exist to be passed to the first object's constructor.
I can resolve this by passing the first object to the second object's constructor, then calling a setter on the first object to pass the second object to it, but that seems a little clunky, and I'm wondering if there's a better way:
backend = new Backend();
panel = new Panel(backend);
backend.setPanel();
I've never put any study into MVC; I suppose I'm dealing with a model here (the Backend), and a view or a controller (the Panel). Any insights here I can gain from MVC?
It's time to take a look at MVC. :-) When you have a model-view-controller situation, the consensus is that the model shouldn't be aware of the view-controller (MVC often plays out as M-VC), but the view is invariably aware of the model.
If the model needs to tell the view something, it does so by notifying its listeners, of which it may have multiples. Your view should be one of them.
In a circular construction scenario I'd use a factory class/factory method. I would normally make the construction logic private to the factory (using friend construct, package level protection or similar), to en sure that no-one could construct instances without using the factory.
The use of setter/constructor is really a part of the contract between the two classes and the factory, so I'd just use whichever's convenient.
As has been pointed out, you really should try to find a non-circular solution.
First of all, contrary to what others has said here, there's no inherent problem with circular references. For example, an Order object would be expected to have a reference to the Customer object of the person who placed the Order. Similarly, it would be natural for the Customer object to have a list of Orders he has placed.
In a refernce-based language (like Java or C#) there's no problem, at all. In a value-based language (like C++), you have to take care in designing them.
That said, you design of:
backend = new Backend();
panel = new Panel(backend);
backend.setPanel(panel);
It pretty much the only way to do it.
It's better to avoid circular references. I would personally try to rethink my objects.
panel = new Panel(backend);
You do this in this routine something like
Public Sub Panel(ByVal BackEnd as BackEnd)
Me.MyBackEnd = BackEnd
BackEnd.MyPanel = Me
End Sub
You don't need BackEnd.SetPanel
It is better to use Proxies. A proxy links one object to another through raising a Event. The parent hands the child a proxy. When the child needs the parent it calls a GetRef method on the proxy. The proxy then raises a event which the parent uses to return itself to the proxy which then hands it to the child.
The use of the Event/Delegate mechanism avoids any circular reference problems.
So you have (assuming that the backend is the 'parent' here)
Public Sub Panel(ByVal BackEnd as BackEnd)
Me.MyBackEnd = BackEnd.Proxy
BackEnd.MyPanel = Me
End Sub
Public Property MyBackEnd() as BackEnd
Set (ByVal Value as BackEnd)
priBackEndProxy = BackEnd.Proxy
End Set
Get
Return priBackEndProxy.GetRef
End Get
End Property
Here is a fuller discussion on the problem of circular references. Although it is focused on fixing it in Visual Basic 6.0.
Dynamic Memory Allocation
Also another solution is aggregating Panel and BackEnd into another object. This is common if both elements are UI Controls and need to behave in a coordinated manner.
Finally as far as MVC goes I recommend using a a Model View Presenter approach instead.
Basically you have your Form Implement a IPanelForm interface. It registers itself with a class called Panel which does all the UI logic. BackEnd should have events that Panel can hook into for when the model changes. Panel handles the event and updates the form through the IPanelForm interface.
User clicks a button
The form passes to Panel that the user clicked a button
Panel handles the button and retrieves the data from the backend
Panel formats the data.
Panel uses IPanelForm Interface to show the data on the Form.
I've been delaying implementing the lessons learned here, giving me plenty of time to think about the exact right way to do it. As other people said, having a clear separation where the backend objects have listeners for when their properties change is definitely the way to go. Not only will it resolve the specific issue I was asking about in this question, it is going to make a lot of other bad design smells in this code look better. There are actually a lot of different Backend classes (going by the generic class names I used in my example), each with their own corresponding Panel class. And there's even a couple of places where some things can be moved around to separate other pairs of classes into Backend/Panel pairs following the same pattern and reducing a lot of passing junk around as parameters.
The rest of this answer is going to get language specific, as I am using Java.
I've not worried a whole lot about "JavaBeans," but I have found that following basic JavaBean conventions has been very helpful for me in the past: basically, using standard getters and setters for properties. Turns out there's a JavaBean convention I was unaware of which is really going to help here: bound properties. Bound properties are properties available through standard getters and setters which fire PropertyChangeEvents when they change. [I don't know for sure, but the JavaBeans standard may specify that all properties are supposed to be "bound properties." Not relevant to me, at this point. Be aware also that "standard" getters and setters can be very non-standard through the use of BeanInfo classes to define a JavaBean's exact interface, but I never use that, either.] (The main other JavaBean convention that I choose to follow or not as appropriate in each situation is a no-argument constructor; I'm already following it in this project because each of these Backend objects has to be serializable.)
I've found this blog entry, which was very helpful in cluing me into the bound properties/PropertyChangeEvents issue and helping me construct a plan for how I'm going to rework this code.
Right now all of my backend objects inherit from a common class called Model, which provides a couple of things every backend in this system needs including serialization support. I'm going to create an additional class JavaBean as a superclass of Model which will provide the PropertyChangeEvent support that I need, inherited by every Model. I'll update the setters in each Model to fire a PropertyChangeEvent when called. I may also have JavaBean inherited by a couple of classes which aren't technically Models in the same sense as these but which could also benefit from having other classes registered as listeners for them. The JavaBean class may not fully implement the JavaBean spec; as I've said, there are several details I don't care about. But it's good enough for this project. It sounds like I could get all this by inheriting from java.awt.Component, but these aren't components in any sense that I can justify, so I don't want to do that. (I also don't know what overhead it might entail.)
Once every Model is a JavaBean, complete with PropertyChangeEvent support, I'll do a lot of code cleanup: Models that are currently keeping references to Panels will be updated and the Panels will register themselves as listeners. So much cleaner! The Model won't have to know (and shouldn't have known in the first place) what methods the Panel should call on itself when the property updates.

Resources