Monday, October 27, 2008

Using MFC ActiveX in other technologies

Hello...
For a while now, I've been using a Microsoft MFC ActiveX in diffrent tehnologies like .NET, web - JavaScript and MFC.

For the first two is kind of easy to import an activex inside yout project...

For .NET you either add a reference to a COM.. that is the ActiveX that is using a .NET Framework tool - aximp - to create two wrappers.
Inside Javascript, you will use the <object> tag and after that you can call diffrent methods exposed by that activeX...
For catching an event in JS you have to write this code...
<script for="ActiveX_ID" event="EventName()">...code here...</script>

What about MFC? How can we call a method inside a MFC Application.
The answer is very simple if you used MFC and COM before.
A CWnd or a COleControlSite object has a InvokeHelper method.
virtual void AFX_CDECL InvokeHelper(
DISPID dwDispID,
WORD wFlags,
VARTYPE vtRet,
void* pvRet,
const BYTE* pbParamInfo,
...
);

You should look inside MSDN for details... Here I'm going to show you how can you invoke a property or a method.
For getting a field inside a property:
VARIANT vtResult;
this->GetDlgItem(IDC_ACTIVEXCTRL)->InvokeHelper(propertyId, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&vtResult, NULL);

where propertyId is the ID of the property(the same is for setting a value of a property).

For invoking a method, with one or more than one parameter, you can use:
static BYTE params[] = VTS_BSTR VTS_BSTR;
unsigned long result = 0;
this->GetDlgItem(IDC_ACTIVEXCTRL)->InvokeHelper(methodId, DISPATCH_METHOD, VT_I4, (void*)&result, params,
(LPCSTR)parameter1, (LPCSTR)parameter2);

where parameter1 and parameter2 are two BSTRs.

Well.. that's about it...
Happy coding!!!

Thursday, October 23, 2008

Complementary Knapsack problem

Hello..
Every programmer (or almost every programmer) heard of the faimos problem called, The knapsack problem. This problem can be formulated in math way: Having a set of numbers, find a subset of numbers this set and their sum are under or equal than a given value?
The solution of this is very simple and there are many web-sites where you can find the implementaion or the pseudo-code.

We name "Complementary Knapsack problem" the problem where we must find a subset that sum is greater than a given value and the difference of the sum and the given number is minimum.
I've done some research using Google and I found nothing(maybe I haven't searched enough).

The solution of this problem is solving the Knapsack problem for the a value equal with: sum of all numbers in set minus the given value. Because this problem offers an optimal solution, if we remove from out set of numbers the result of this problem, we find our subset and if we sum them we get a number grater that the given value and the difference is minimum.