What is the difference between new ActiveXObject() and WScript.CreateObject()? - activex

According to the Microsoft documentation, one can create instances of the COM objects using both the ActiveXObject() and the WScript.CreateObject() functions. It seems like the lines
var objXL = new ActiveXObject("Excel.Application");
and
var objXL = WScript.CreateObject("Excel.Application");
are identical. Is this a true assumption? and if not what is the difference? Examples to show the difference would be highly appreciated.
P.S. The post this has been flagged as a duplicate to is about the difference between VBScript's CreateObject() method and JScript's WScript.CreateObject(). It answers mention the JScript's ActiveXObject() constructor with no further elaborations.

Are they the same?
The short the answer is Yes they are the same (in the sense they perform the same job of instantiating an automation object).
Basically unlike VBScript which has the global function CreateObject() there is no such equivalent in JScript which was based on ECMAScript 3rd Edition. So, Microsoft added its own extension ActiveXObject which does the same job as CreateObject.
Both languages can be hosted in the Windows Scripting Host which gives them access to WScript.CreateObject() which is another method that does exactly the same function but only in the context of the WScript object that is only available through the Windows Scripting Host.
Following up
There has been some debate about whether they are the same, I still stand by my original answer they are the same. However, I will concede that I was comparing VBScript CreateObject() and JScript new ActiveXObject() not Wscript.CreateObject() (which is slightly different).
Let's be clear though, all these functions and objects serve the same purpose which is to instantiate an automation object (COM). To back this up here is the official description of each;
WScript - CreateObject() Method
Creates a COM object
JScript - ActiveXObject Method
Enables and returns a reference to an Automation object
VBScript - CreateObject() Function
Creates and returns a reference to an Automation object
If they were completely the same what would the point of them be? We already have language-specific automation instantiation methods, so what would the point of Wscript.CreateObject() be?
The difference is when called with a second parameter it allows you to specify a prefix that will use to distinguish event handlers for that COM object.
Here is an example taken from this answer that shows how the second argument is used to set a prefix of objIE_ that will then be used to prefix any event handlers associated with that COM object, in this case, the InternetExplorer.Application object.
// JScript
var objIE = WScript.CreateObject("InternetExplorer.Application","objIE_")
objIE.Visible = true
while (objIE.Visible){
WScript.Sleep(500);
}
function objIE_NavigateComplete2(pDisp, URL){
WScript.Echo("You just navigated to", URL)
}
function objIE_OnQuit(){
boolBrowserRunning = false ;
}
It allows an Internet Explorer instance to be opened and the URL navigated to captured through the bound event, once the Internet Explorer Window is closed the script will end.
So while not identical they do perform the same function of instantiating an Automation (COM) object.
Useful Links
Answer to What is the difference between CreateObject and Wscript.CreateObject?

Related

Using Dart as a DSL

I am trying to use Dart to tersely define entities in an application, following the idiom of code = configuration. Since I will be defining many entities, I'd like to keep the code as trim and concise and readable as possible.
In an effort to keep boilerplate as close to 0 lines as possible, I recently wrote some code like this:
// man.dart
part of entity_component_framework;
var _man = entity('man', (entityBuilder) {
entityBuilder.add([TopHat, CrookedTeeth]);
})
// test.dart
part of entity_component_framework;
var man = EntityBuilder.entities['man']; // null, since _man wasn't ever accessed.
The entity method associates the entityBuilder passed into the function with a name ('man' in this case). var _man exists because only variable assignments can be top-level in Dart. This seems to be the most concise way possible to use Dart as a DSL.
One thing I wasn't counting on, though, is lazy initialization. If I never access _man -- and I had no intention to, since the entity function neatly stored all the relevant information I required in another data structure -- then the entity function is never run. This is a feature, not a bug.
So, what's the cleanest way of using Dart as a DSL given the lazy initialization restriction?
So, as you point out, it's a feature that Dart doesn't run any code until it's told to. So if you want something to happen, you need to do it in code that runs. Some possibilities
Put your calls to entity() inside the main() function. I assume you don't want to do that, and probably that you want people to be able to add more of these in additional files without modifying the originals.
If you're willing to incur the overhead of mirrors, which is probably not that much if they're confined to this library, use them to find all the top-level variables in that library and access them. Or define them as functions or getters. But I assume that you like the property that variables are automatically one-shot. You'd want to use a MirrorsUsed annotation.
A variation on that would be to use annotations to mark the things you want to be initialized. Though this is similar in that you'd have to iterate over the annotated things, which I think would also require mirrors.

How to get concrete object of a static method via mirror API?

I have something like this:
class MyClass
{
static void DoSomething(arg1, arg2){...}
}
Via reflection, I am able to get the ClassMirror of this class. From this point, how would I get to the concrete static function so I can call it.
Note that I tried to use:
ObjectMirror.invoke('DoSomething', [arg1, arg2]);
which would initially appear to work, but it doesn't support passing of complex types as arguments, This static function requires a complex type as one of it's arguments.
Ideally, I'd like to get the 'Function' object that represents the static method so I can invoke it directly.
a. The current state of affairs is temporary. The plan is that the mirror API will wrap the arguments with mirrors for you.
b. The API may eventually support a getProperty method that will give you a Future on the function object. However, you will not get a Function object directly, so this won't really make any difference in this case.
c. The core idea is that the API fundamentally works on mirrors. To make it more usable, it should accept non-mirrors as input and wrap them in mirrors for you. It will always return mirrors, and in some cases return futures on these. This is so the API works the same for remote and local cases.
d. Resources for understanding mirrors:
http://www.bracha.org/mirrors.pdf (academic paper, tough going)
http://www.hpi.uni-potsdam.de/hirschfeld/events/past/media/100105_Bracha_2010_LinguisticReflectionViaMirrors_HPI.mp4 (a video, pre-Dart, discusses earlier Mirror systems)
http://gbracha.blogspot.com/2010/03/through-looking-glass-darkly.html (an old, pre-dart, blog post of mine on mirrors)
http://www.wirfs-brock.com/allen/posts/228 (Allen Wirfs-Brock's blog. Allen was a mirror pioneer back in Smalltalk in the 90s)
http://www.wirfs-brock.com/allen/posts/245
You can also search my blog, or Allen Wirf-Brock's for posts on the topic.

How best to expose a class instance in DWScript

I am putting together a built-in script capability using the excellent Pascal DWScript. I have also add my own Delphi-side class definition (TDemo) to DWScript using:
dwsUnit.ExposeRTTI( TDemo.ClassInfo )
This just works and is a great way of quickly adding properties and methods.
I also wish to add an existing instance in a similar way, so I have created my instance FDemo of type TDemo and then performed:
dwsUnit.ExposeInstanceToUnit( 'Demo', 'TDemo', FDemo );
This looks a promising routine to call but I get an AV from an uninitialised unit table. I've also looked in the unit test code of the SVN source to see the use of this function but to no avail. Can anyone point me at what I should add / change?
ExposeInstanceToUnit has to be used from within the TdwsUnit table initialization, see RTTIExposeTests/ExposeInstancesAfterInitTable for some sample code. It allows directly exposing dynamic instances.
The other approach is to use the Instances collection of a TdwsUnit component, you get design-time support, and more controls over your instances and their lifetime.
Also keep in mind you have to make sure the instances you expose will properly behave even if the script misbehaves, f.i. when the user attempts to manually destroys an instance you exposed, and that instance shouldn't be destroyed. By default ExposeRTTI will map the destructors, so you may want to restrict that by specifying eoNoFreeOnCleanup.
edit: a last approach recently added is to use the TdwsRttiConnector, which basically allows exposing and connection to anything that's reachable through RTTI. That's very lightweight in terms of code to setup, but the downside is you don't get any form of compile-time checks.

Looking for robust, general op_Dynamic implementation

I've not been able to find a robust, general op_Dynamic implementation: can anyone point me to one? So far searches have only turned up toys or specific purpose implementations, but I'd like to have one on hand which, say, compares in robustness to C#'s default static dynamic implementation (i.e. handle lots / all cases, cache reflection calls) (it's been a while since I've looked at C#'s static dynamic, so forgive me if my assertions about it's abilities are false).
Thanks!
There is a module FSharp.Interop.Dynamic, on nuget that should robustly handle the dynamic operator using the dlr.
It has several advantages over a lot of the snippets out there.
Performance it uses Dynamitey for the dlr call which implements caching and is a .NET Standard Library
Handles methods that return void, you'll get a binding exception if you don't discard results of those.
The dlr handles the case of calling a delegate return by a function automatically, this will also allow you to do the same with an FSharpFunc
Adds an !? prefix operator to handle invoking directly dynamic objects and functions you don't have the type at runtime.
It's open source, Apache license, you can look at the implementation and it includes unit test example cases.
You can never get fully general implementation of the ? operator. The operator can be implemented differently for various types where it may need to do something special depending on the type:
For Dictionary<T, R>, you'd want it to use the lookup function of the dictionary
For the SQL objects in my article you referenced, you want it to use specific SQL API
For unknown .NET objects, you want it to use .NET Reflection
If you're looking for an implementation that uses Reflection, then you can use one I implemented in F# binding for MonoDevelop (available on GitHub). It is reasonably complete and handles property access, method calls as well as static members. (The rest of the linked file uses it heavily to call internal members of F# compiler). It uses Reflection directly, so it is quite slow, but it is quite feature-complete.
Another alternative would be to implement the operator on top of .NET 4.0 Dynamic Language Runtime (so that it would use the same underlying API as dynamic in C# 4). I don't think there is an implementation of this somewhere out there, but here is a simple example how you can get it:
#r "Microsoft.CSharp.dll"
open System
open System.Runtime.CompilerServices
open Microsoft.CSharp.RuntimeBinder
let (?) (inst:obj) name (arg:'T) : 'R =
// Create site (representing dynamic operation for converting result to 'R
let convertSite =
CallSite<Func<CallSite, Object, 'R>>.Create //'
(Binder.Convert(CSharpBinderFlags.None, typeof<'R>, null)) //'
// Create site for the method call with single argument of type 'T
let callSite =
CallSite<Func<CallSite, Object, 'T, Object>>.Create //'
(Binder.InvokeMember
( CSharpBinderFlags.None, name, null, null,
[| CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null);
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) |]))
// Run the method and perform conversion
convertSite.Target.Invoke
(convertSite, callSite.Target.Invoke(callSite, inst, arg))
let o = box (new Random())
let a : int = o?Next(10)
This works only for instance method calls with single argument (You can find out how to do this by looking at code generated by C# compiler for dynamic invocations). I guess if you mixed the completeness (from the first one) with the approach to use DLR (in the second one), you'd get the most robust implementation you can get.
EDIT: I also posted the code to F# Snippets. Here is the version using DLR: http://fssnip.net/2U and here is the version from F# plugin (using .NET Reflection): http://fssnip.net/2V

What does [Bindable] mean in actionscript?

[Bindable]
/**
* Display output of video device.
*/
public var videoLocal : Video;
Anyone knows?
[Bindable] is a one of several meta tags that you can use in flex ActionScript code. It can be applied to properties, or methods that are marked in any scope. It cannot be used with static class members.
The key to using the [Bindable] meta tag is understanding what is going on under the hood when you use it. Essentially using data binding is a type of shorthand for adding event listeners and dispatching events.
There are two basic forms of the [Bindable] tag. The first is just [Bindable] followed by a var/property declaration. The Second is [Bindable(event="eventname")] followed by either a var/property declaration, a function/method declaration or one half of a getter/setter declaration.
I'll explain the longer notation first since the other builds on the same concept but with even more shorthand.
When you use [Bindable(event="eventname")] you are essentially telling the compiler that this var/property/function/method (call this the instance member) is 'available' to be used as the source for data binding. You are also telling it that when the value of the instance member has been invalidated/changed and it needs to be re-read that the "eventname" event will be dispatched.
In this longer form this all you are doing. You the developer are responsible for actually dispatching the "eventname" event whenever the value needs to be updated in the binding subscribers.
The real efficiency of using data binding comes on the subscribing side. The typical notation you will see in MXML is value="{instance.propertyName}" When you use the notation { } you are telling the compiler to do the following:
Create an event listener that listens to the event named in the bindable meta tag
In that event listener re-read the instance.propertyName and update this value
If you use the shorter form [Bindable], and you add the tag before a property/var, the compiler fills in the blanks and adds some additional functionality to make the property bindable. Essentially you are telling the compiler "add the events and methods you need to make this property bindable"
Now the way to think of what the compiler will do under the hood is this.
make a private version of your var
create an "event" to trigger the binding
create a getter function with scope and name of your original var that returns the private verson of the var when called.
create a setter function with scope and name of your original var that sets the private version of the var when called AND dispatches the triggering event.
In essence the compiler will do much of the work for you.
[Bindable]
public var xyz
is equivalent to
private var _xyz:String;
[Bindable(event="updateXYZValue")]
public function get xyz():String{
return _xyz;
}
public function set xyz(newxyz:String):void{
_xyz = newxyz;
dispatchEvent(new Event("updateXYZValue"));
}
The only functional differences in these is that in the first instance;
you do not know the name of the event that will be dispatched to trigger the binding
there is no way to update the underlying value without triggering the data binding
This second example also demonstrates one special case of the [Bindable] meta tag. This is that when you are applying it to a getter/setter pair defined for the same variable name you need only apply it to one or the other, it will apply to both. Typically you should set it on the getter.
You can use either notation on a function/method however if you do not specify an event the binding will never be triggered so if you are trying to bind to a function you should alway specify an event. It is also possible to specify more than one triggering event by stacking the tag. eg.
[Bindable(event="metaDataChanged")]
[Bindable(event="metaObjectUpdated")]
public function readMyMetaData():MetaDataObject{
var myMetaDataObject:MetaDataObject;
.
.
.
return myMetaDataObject;
}
This would presume that somewhere else you your class you will dispatch this metaDataChanged event or the metaObjectUpdated event when you want trigger the binding.
Also note that with this notation you can tie the binding of any instance member to any event that the instance will dispatch. Even inherited events that you yourself do not generate such as FrameEnter, OnChange, etc...
Data bindings can also be setup and destroyed during runtime. If you are interested in this take a look at the mx.binding.utils classes.
It is used in Databinding with Flex, you can read more about it here
http://livedocs.adobe.com/flex/3/html/help.html?content=databinding_2.html
Creating properties to use as the source for data binding
When you create a property that you
want to use as the source of a data
binding expression, Flex can
automatically copy the value of the
source property to any destination
property when the source property
changes. To signal to Flex to perform
the copy, you must use the [Bindable]
data tag to register the property with
Flex.
As an addition to what Justin said, you can actually use two ways data binding in Flex with the # character. Here's an example:
<s:TextInput id="txt1" text="#{txt2.text}" />
For a working example with source code enabled you can check out this article I wrote a while back:
Two-ways data binding in Flex

Resources