Correctly handling custom messages using WTL - message-queue

I've written a multi-threaded WTL util to stress test an in-house service.
Comms threads signal to the main thread that they've quit, so the main thread can delete their corresponding object.
They make the signal as so:
PostThreadMessage(m_dwParentThreadId, WM_THREADQUIT, 1, m_dwNetThreadId);
My problem is how to deal with the custom message I've defined .
WM_THREADQUIT is #define'd as WM_USER + 10
I wanted to use an entry in the message map to call a handler, e.g.:
BEGIN_MSG_MAP(CMainDlg)
MESSAGE_HANDLER( WM_INITDIALOG, OnInitDialog )
MESSAGE_HANDLER( WM_THREADQUIT, OnThreadQuit )
...
REFLECT_NOTIFICATIONS()
END_MSG_MAP()
However, OnThreadQuit is never called.
The only way I can handle it is by calling the handler explicitly in PreTranslateMessage:
virtual BOOL CMainDlg::PreTranslateMessage(MSG* pMsg)
{
if( pMsg->message == WM_THREADQUIT )
{
BOOL blHandled;
OnThreadQuit(pMsg->message, pMsg->wParam, pMsg->lParam, blHandled);
return TRUE;
}
return CWindow::IsDialogMessage(pMsg);
}
I'm sure this isn't the correct way to do it ...
I'd love to know the correct way- can someone help!?

As stated in the doc Messages sent by PostThreadMessage are not associated with a window. As a general rule, messages that are not associated with a window cannot be dispatched by the DispatchMessage function.
Set your HWND in pMsg->hwnd and ::DispatchMessage() will deliver it to your WndProc:
virtual BOOL CMainDlg::PreTranslateMessage(MSG* pMsg)
{
if (pMsg->message == WM_THREADQUIT)
{
pMsg->hwnd = m_hWnd;
return FALSE; // continue processing
}
return CWindow::IsDialogMessage(pMsg);
}

Related

is there a name for this conditional-checking technique?

so, theres a technique I use in a fair amount of programming languages and projects; and I'm wondering if it has a general, language-agnostic "official" term to describe it.
basically, I nicknamed it "trip switch checking." Its where if you need to check that several variables have specific values, possibly of different types, you first set a boolean to "false" and then in either a loop or several if statements, you check what you need to by setting the boolean to true if any of the other variables don't meet your requirements.
I call it trip-switching because the boolean remains false if the "switch" isn't "tripped," using an analogy from a common safety mechanism on industrial machinery where if something moves too far or gets too close or etc. a physical switch is actually bumped into and it shuts the whole thing down. the idea is not to switch it back off until the obstruction is cleared- the machine cant turn itself back on automatically.
pseudocode example, a function that returns true if the trip switch wasn't hit:
function tripswitchcheck()
{
boolean tripswitch = false
if(idontnwantthis == true)
{
tripswitch = true
}
if(iwantthis == false)
{
tripswitch = true
}
//...etc...basically do stuff to check stuff. if any values are undesired, true the tripswitch.
return !tripswitch
}
It may be bad practice depending on the language and nature of the project, but it works, and that's outside of the scope of this question.
First of all, why would you not just have a positive flag in that example:
function tripswitchcheck()
{
boolean success = true;
if(idontnwantthis == true)
{
success = false;
}
if(iwantthis == false)
{
success = false;
}
//...etc...basically do stuff to check stuff. if any values are undesired, falsify success
return success
}
Secondly, why check the conditions if you already know you have failure. Say that we don't have a forward goto in the language, or else, or early returns (or we don't want to return because something else is done based on the success flag before returning):
function tripswitchcheck()
{
boolean success = true;
if(idontnwantthis == true)
{
success = false;
}
if(success && iwantthis == false) // if success is false, fall through
{
success = false;
}
if(success && !othercondition()) // likewise
{
success = false;
}
//...etc...
return success
}
There are reasons not to use else if some of the conditions make use of earlier results.
Anyway, this just comes from basic logic and scientific reasoning: we have a hypothesis and look for reasons why it is not true.
The name for it is perhaps "single exit rule" and such: the function exits through a single return statement.

Forge tool handleButtonDown and handleButtonUp functions not getting called

I was looking at the sample code for the tutorial at https://forge.autodesk.com/blog/custom-window-selection-forge-viewer-part-iii which is located at https://github.com/Autodesk-Forge/forge-rcdb.nodejs/blob/master/src/client/viewer.components/Viewer.Extensions.Dynamic/Viewing.Extension.SelectionWindow/Viewing.Extension.SelectionWindow.Tool.js as well as the documentation at https://developer.autodesk.com/en/docs/viewer/v2/reference/javascript/toolinterface/ --- Most of these functions are getting called properly in my tool such as handleSingleClick, handleMouseMove, handleKeyDown, and so on, but two of them are not getting hit -- handleButtonDown and handleButtonUp. I was using viewer version 3.3.x but I have updated to use 4.0.x thinking that that might help to resolve the problem, but the same issue occurs in both versions. Thanks for any help.
The following code block from theAutodesk.Viewing.ToolController#__invokeStack(), _toolStack stands for activated tools in the ToolController, the method stands for callback functions started with handle, i.e. handleSingleClick, handleMouseMove, handleKeyDown, handleButtonDown, handleButtonUp, etc.
for( var n = _toolStack.length; --n >= 0; )
{
var tool = _toolStack[n];
if( tool[method] && tool[method](arg1, arg2) )
{
return true;
}
}
Based on my experience, if there is a handle function such as handleButtonDown or handleButtonUp executed before your custom tools' and returned true, then your handles will never be called.
Fortunately, Forge Viewer (v3.2) starts invoking a priority mechanism for custom tools registered in ToolController. ToolController will use the priority number to sort the tools in it, and the priority number of each tool is 0 by default. You can override the priority to make your tools be hit before other tools like this way, to add a function getPriority() to return a number greater than 0:
this.getPriority = function() {
return 100;
};
I found out that when using ES6 and the class syntax, extending your tool from Autodesk.Viewing.ToolInterface will prevent the overrides to work properly, probably because it is not implemented using prototype in the viewer source code.
You can simply create a class and implement the methods that are of interest for your tool:
// KO: not working!
class MyTool extends Autodesk.Viewing.ToolInterface {
getName () {
return 'MyTool'
}
getNames () {
return ['MyTool']
}
handleButtonDown (event, button) {
return false
}
}
// OK
class MyTool {
getName () {
return 'MyTool'
}
getNames () {
return ['MyTool']
}
handleButtonDown (event, button) {
return false
}
}

Run replace script in Google App Maker

I would like to add a server script that replaces special characters when a textbox is filled. The info for the "onValueEdit" routine states:
This script will run on the client whenever the value of this widget is edited by the user. The widget can be referenced using parameter widget and the new value of the widget is stored in newValue. Unlike onValueChange(), this runs only when a user changes the value of the widget; it won't run in response to bindings or when the value is set programmatically.
Therefore I have built the following server script that should take the text from the textbox, overwrite the special characters and replace the text in the textbox. But when I add the script to "onValueEdit" event, Google App Maker returns "function is undefined".
function cleanup(input, output) {
if (input !== null) {
output = input.trim();
output = output.replace('ß','ss');
output = output.replace('ä','ae');
output = output.replace('ö','oe');
output = output.replace('ü','ue');
return output;
}
}
In case you want to make this changes only on client side the ritgh way to do it will be adding this code to the onValueEdit event handler:
// onValueEdit input's event handler
if (newValue !== null) {
output = newValue.trim();
output = output.replace('ß','ss');
...
widget.value = output;
}
If you need to securely enforce this override prior to persisting to database, then you need to go with Model Events:
// onBeforeCreate and onBeforeSave events
if (record.FieldToChange !== null) {
record.FieldToChange = record.FieldToChange.trim();
record.FieldToChange = record.FieldToChange.replace('ß','ss');
...
}
With this approach you don't need any client code since all changes made on server should automatically sync back to client.

WinJS variable/object scope, settings, and events?

I am not sure what the proper heading / title for this question should be. I am new to WinJS and am coming from a .NET webform and winclient background.
Here is my scenario. I have a navigation WinJS application. My structure is:
default.html
(navigation controller)
(settings flyout)
pages/Home.html
pages/Page2.html
So at the top of the default.js file, it sets the following variables:
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
var nav = WinJS.Navigation;
It seems like I cannot use these variables anywhere inside my settings flyout or any of my pages:ready functions. They are only scoped to the default.js?
In the same regard, are there resources on the interwebs (links) that show how to properly share variables, events, and data between each of my "pages"?
The scenario that I immediately need to overcome is settings. In my settings flyout, I read and allow the user to optionally set the following application setting:
var applicationData = Windows.Storage.ApplicationData.current;
var localSettings = applicationData.localSettings;
localSettings.values["appLocation"] = {string set by the user};
I want to respond to that event in either my default.js file or even one of my navigation pages but I don't know where to "listen". My gut is to listen for the afterhide event but how do I scope that back to the page where I want to listen from?
Bryan. codefoster here. If you move the lines you mentioned...
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
var nav = WinJS.Navigation;
...up and out of the immediate function, they'll be in global scope and you'll have access to them everywhere. That's one of the first things I do in my apps. You'll hear warnings about using global scope, but what people are trying to avoid is the pattern of dropping everything in global scope. As long as you control what you put in there, you're fine.
So put them before the beginning of the immediate function on default.js...
//stuff here is scoped globally
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
var nav = WinJS.Navigation;
(function () {
//stuff here is scoped to this file only
})();
If you are saving some data and only need it in memory, you can just hang it off the app variable instead of saving it into local storage. That will make it available to the whole app.
//on Page2.js
app.myCustomVariable = "some value";
//on Page3.js
if(app.myCustomVariable == "some value") ...
Regarding your immediate need:
like mentioned in the other answer, you can use datachanged event.
Regards sharing variables:
If there are variables that you would like to keep global to the application, they can be placed outside the anonymous function like mentioned in the Jeremy answer. Typically, that is done in default.js. Need to ensure that scripts using the global variables are placed after the script defining the global variable - in default.html. Typically - such variable will point to singleton class. For example: I use it in one of my apps to store authclient/serviceclient for the backend service for the app. That way - the view models of the multiple pages need not create instance of the object or reference it under WinJS namespace.
WinJS has also concept of Namespace which lets you organize your functions and classes. Example:
WinJS.Namespace.define('Utils.Http',
{
stringifyParameters: function stringifyParameters(parameters)
{
var result = '';
for (var parameterName in parameters)
{
result += encodeURIComponent(parameterName) + '=' + encodeURIComponent(parameters[parameterName]) + '&';
}
if (result.length > 0)
{
result = result.substr(0, result.length - 1);
}
return result;
},
}
When navigating to a page using WinJS.Navigation.navigate, second argument initialState is available as options parameter to the ready event handler for the page. This would be recommended way to pass arguments to the page unless this it is application data or session state. Application data/session state needs to be handled separately and needs a separate discussion on its own. Application navigation history is persisted by the winjs library; it ensures that if the app is launched again after suspension - options will be passed again to the page when navigated. It is good to keep the properties in options object as simple primitive types.
Regards events:
Typically, apps consume events from winjs library. That can be done by registering the event handler using addEventListener or setting event properties like onclick etc. on the element. Event handlers are typically registered in the ready event handler for the page.
If you are writing your own custom control or sometimes in your view model, you may have to expose custom events. Winjs.UI.DOMEventMixin, WinJS.Utilities.createEventProperties can be mixed with your class using WinJS.Class.mix. Example:
WinJS.Class.mix(MyViewModel,
WinJS.Utilities.createEventProperties('customEvent'),
WinJS.UI.DOMEventMixin);
Most often used is binding to make your view model - observable. Refer the respective samples and api documentation for details. Example:
WinJS.Class.mix(MyViewModel,
WinJS.Binding.mixin,
WinJS.Binding.expandProperties({ items: '' }));
Here is what I ended up doing which is kinda of a combination of all the answers given:
Created a ViewModel.Settings.js file:
(function () {
"use strict";
WinJS.Namespace.define("ViewModel", {
Setting: WinJS.Binding.as({
Name: '',
Value: ''
}),
SettingsList: new WinJS.Binding.List(),
});
})();
Added that file to my default.html (navigation container page)
<script src="/js/VMs/ViewModel.Settings.js"></script>
Add the following to set the defaults and start 'listening' for changes
//add some fake settings (defaults on app load)
ViewModel.SettingsList.push({
Name: "favorite-color",
Value: "red"
});
// listen for events
var vm = ViewModel.SettingsList;
vm.oniteminserted = function (e) {
console.log("item added");
}
vm.onitemmutated = function (e) {
console.log("item mutated");
}
vm.onitemchanged = function (e) {
console.log("item changed");
}
vm.onitemremoved = function (e) {
console.log("item removed");
}
Then, within my application (pages) or my settings page, I can cause the settings events to be fired:
// thie fires the oniteminserted
ViewModel.SettingsList.push({
Name: "favorite-sport",
Value: "Baseball"
});
// this fires the itemmutated event
ViewModel.SettingsList.getAt(0).Value = "yellow";
ViewModel.SettingsList.notifyMutated(0);
// this fires the itemchanged event
ViewModel.SettingsList.setAt(0, {
Name: "favorite-color",
Value: "blue"
});
// this fires the itemremoved event
ViewModel.SettingsList.pop(); // removes the last item
When you change data that needs to be updated in real time, call applicationData.signalDataChanged(). Then in the places that care about getting change notifications, listen to the datachanged on the applicationData object. This is also the event that is raised when roaming settings are synchronized between computers.
I've found that many times, an instant notification (raised event) is unnecessary, though. I just query the setting again when the value is needed (in ready for example).

NPAPI Plugin[FireFox]: Invoke() / HasProperty() / HasMethod() not getting called

I am developing NPAPI Plugin for Firefox on windows. here is the my java script:
document.addEventListener('load', documentLoad, true);
function loadPlugin(doc)
{
var objWebMon = doc.getElementById("my_firefox");
if(!objWebMon)
{
var objWebMonEmbed = doc.createElement('embed');
objWebMonEmbed.setAttribute('id', 'my_firefox');
objWebMonEmbed.setAttribute('type', 'application/npplugin');
objWebMonEmbed.setAttribute('style', 'height: 10px; width:10px; display:block;');
if(doc.body)
{
doc.body.insertBefore(objWebMonEmbed, doc.body.firstChild);
}
}
}
function documentLoad(event) {
try
{
var doc = event.originalTarget; // doc is document that triggered "onload" event
loadPlugin(doc);
var myplugin = doc.getElementById('my_firefox');
if(myplugin)
{
myplugin();
myplugin.myAction();
}
} catch(err)
{
}
}
as I am calling myplugin()
bool ScriptablePluginObject::InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result)
gets called sucessfully but on calling function myplugin.myAction()
bool ScriptablePluginObject::Invoke(NPIdentifier name, const NPVariant *args,
uint32_t argCount, NPVariant *result)
function doesn't called. I have declared myAction inside ScriptablePluginObject::HasProperty(NPIdentifier name) even HasProperty method is not getting called.
Inside catch block i am getting this error. TypeError: fasso.myAction is not a function.
Here are a couple of things to try:
Use an object tag instead of an embed -- I've had more consistent success with object tags, despite the wide popularity of using embed
Never ever ever set the type of an object or embed tag before you add it to the DOM -- doing so causes it to instantiate the plugin and then puts it in a kinda weird state when it gets moved. I don't think this is causing your issue this time, but it's worth trying.
You may need a slight delay between inserting hte plugin into the DOM and using it. Try adding a setTimeout with a delay of 50ms and accessing the plugin in the callback function.
Honestly, #3 is the one I think most likely will make a difference, but I present the other two as they have bitten me on weird things in the past. Good luck!