How to hook up Microsoft Forms 2.0 event handlers using JScript - enterprise-architect

I'm trying to add a customized UI page to Sparx EA. It provides adding ActiveX controls via scripting. Using JScript, I've done this, but since ActiveX has to be registered on each client, I'd rather use Microsoft Forms, already installed on all clients.
I've successfully built the UI, appearance wise, by adding a "Forms.Form.1" ActiveX object, and adding text boxes, labels & buttons to the controls property of the created form.
These objects support events, but I can't figure out how to assign an event handler.
Here is the JScript code I used to get the screen layout:
function _addControl(parentControl, controlProgId, controlName, left, top, width, height){
var newControl = parentControl.controls.add(controlProgId, controlName,1);
newControl.Name=controlName;
newControl._SetLeft(left);
newControl._SetTop(top);
newControl._SetWidth(width);
newControl._SetHeight(height);
return newControl;
}
function main(){
//Create main form
var form = Repository.AddTab("ScriptedForm", "Forms.Form.1");
if (null != form){
//Add control
var textBox1 = _addControl(form, "Forms.TextBox.1","TextBox1", 18,21,94,93);
var textBox2 = _addControl(form, "Forms.TextBox.1","TextBox2", 120, 21, 91, 93);
var btnTest = _addControl(form, "Forms.CommandButton.1", "btnTest", 60, 140, 90, 30);
btnTest.Caption = "Test";
//Here's where I assign the click event, but it's unhappy.
btnTest.add_Click(this.TextBox1_Click);
}
}
function TextBox1_Click(Object){
Session.Prompt("Click", promptOK);
}
The add_Click event expects a parameter of type CommandButtonEvents_ClickEventHandler.
There's nothing I can create that could be submitted as the parameter. I tried creating a JScript class duplicating the interface, but no joy.

I think you are running into several problems here at once.
(1) Process Lifetime
As far as I understand your question and its context, you are somehow manually executing a JScript script. Doing this EA will internally start SScripter.exe. You see this in the Debug window:
The process is effectively terminated after the script finishes (and thus also terminating any event handlers you might have registered in your UserControl or Form object).
(2) Passing a JScript object instance as a .NET delegate
If you could somehow extend the lifetime of the script environment, and if you could pass something to your event you will realise that any object in your JScript code will be passed as a System.__ComObject to the .NET runtime inside EA. Therefore you cannot just register an event handler.
However when you evaluate the object from .NET you will find out it is not an IDispatch interface:
MemberNames:
ToString,
GetLifetimeService,
InitializeLifetimeService,
CreateObjRef,
Equals,
GetHashCode,
GetType
TargetInvocationException#mscorlib: 'COM target does not implement IDispatch.'
I did a small test with the code below:
function MyClass(name)
{
this.name = name;
}
MyClass.prototype.Invoke = function(value)
{
Session.Output("name " + value);
return true;
}
function main()
{
var myClass = new MyClass("Hotzenplotz");
myClass.Invoke("some Value");
var ctrl = new ActiveXObject("IMASE.TestUserControl2");
ctrl.Repository = Repository;
ctrl.JavaScriptObject = myClass;
}
[ProgId(Global.ADDIN_NAME + Global.DOT + "TestUserControl2")]
[Guid("87156dd9-e947-44bf-92a9-e9554a5b1844")]
[ComVisible(true)]
public partial class TestUserControl2 : ActivexControl
{
public static string TabName { get; } = Global.ADDIN_NAME;
private static readonly Lazy<string> _controlId = new Lazy<string>(() =>
{
var attribute = typeof(TestUserControl).GetCustomAttribute<ProgIdAttribute>();
return attribute.Value;
});
private Timer timer;
public static string ControlId = _controlId.Value;
public Repository Repository { get; set; }
public object JavaScriptObject { get; set; }
public TestUserControl2()
{
timer = new Timer();
timer.Elapsed += TimerEvent;
timer.Interval = 5000;
timer.Enabled = true;
timer.Start();
}
~TestUserControl2()
{
Logger.Default.TraceInformation("I'm gonna die ... " + this.GetHashCode());
}
private void OnDispose(object sender, EventArgs e)
{
timer.Dispose();
}
private void TimerEvent(object source, ElapsedEventArgs e)
{
Logger.Default.TraceInformation("I'm still alive ... " + this.GetHashCode());
if(null == JavaScriptObject) return;
try
{
var memberNames = JavaScriptObject.GetType().GetMembers(BindingFlags.Instance|BindingFlags.FlattenHierarchy|BindingFlags.Public).Select(p => p.Name);
Logger.Default.TraceInformation("memberNames: " + string.Join(", ", memberNames));
var result = JavaScriptObject.GetType().InvokeMember("Invoke", BindingFlags.InvokeMethod, null, JavaScriptObject, new object[] {"arbitraryString"});
Logger.Default.TraceInformation("result: " + result);
}
catch (Exception ex)
{
Logger.Default.TraceException(ex);
}
}
}
(3) Another approach
Create a UserControl inside your addin (using WinForm or Forms) and use ClearScript as a ScriptEngine.
Pass Session and Repository from a EA script to your control (or do it otherwise such as a menu to wprk around the lifetime problem) and have either your forms code load a script from the repository (or any other source). Then react on your event handlers to execute your JScript code as needed. I create a simple example that shows how to call a control from an EA JScript and call another JScript from inside your forms code that in turn will log to the Debug session or regular scripting output window:
function main()
{
var ctrl = new ActiveXObject("IMASE.TestUserControl2");
ctrl.Repository = Repository;
ctrl.Session = Session;
Session.Prompt("wait", promptOK);
}
main();
Inside your form code you invoke your JScript with Repository and other objects like this:
public Repository Repository { get; set; }
public object Session { get; set; }
using (var engine = new JScriptEngine())
{
engine.AddHostObject("Repository", this.Repository);
engine.AddHostObject("Session", this.Session);
engine.Execute("Session.Output('Repository.ConnectionString: ' + Repository.ConnectionString);");
}
Here is an output of the above scripting interactions:
Side note: I personally do not see the need for using forms as we can dynamically register ActiveX controls at AddIn startup. For code on doing this you can have a look at the following gist:
https://gist.github.com/dfch/6a27bb1b9320c93456cee6d5b2b9d551
In addition, if you are using ClearScript as the script host, you can directly connect to your (UI) events from your script code as described in question #16 of the ClearScript FAQtorial.

Related

MVVM: OnBindingContextChange: PropertyChanged not firing in new view model

I am coding a Xamarin app and doing my best to adhere to MVVM, which I actually really like
I commonly have ContentPages containing references to Views.
I set the binding context to a VM in the Page, and then make use of OnBindingContextChanged in the view
This allows me to use PropertyChanged method to then respond to display logic conditions for my View
I've used it several times successfully but I am baffled why an additional implementation isn't working
Page looks like this
public partial class BindingTextPage : ContentPage
{
public BindingTextPage()
{
InitializeComponent();
this.BindingContext = new ViewModels.LocationsViewModel();
}
}
View looks like this
private LocationsViewModel_vm;
public BindingTestView()
{
InitializeComponent();
System.Diagnostics.Debug.WriteLine("Debug: Initialised BindingTesView view");
}
protected override void OnBindingContextChanged()
{
System.Diagnostics.Debug.WriteLine("Debug: BindingTest: OnBindingContextChanged: Context " + this.BindingContext.GetType());
_vm = BindingContext as LocationsViewModel;
_vm.PropertyChanged += _vm_PropertyChanged;
}
private void _vm_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
try
{
System.Diagnostics.Debug.WriteLine("Debug: BindingTest: Method called");
System.Diagnostics.Debug.WriteLine("Debug: BindingTest: Property " + e.PropertyName);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Debug: BindingTestView: Error changing context " + ex.Message);
}
}
Extract of view model, very simply in this case setting a string and hence changing a property, which I would have expected would then cause PropertyChange to fire?
public LocationsViewModel()
{
tempMessage = "this is from the view model";
}
public string tempMessage
{
get
{
return _tempMessage;
}
set
{
_tempMessage = value;
OnPropertyChanged(nameof(tempMessage));
}
}
My debug statements when it boots up shows that OnBindingContextChange is being called, but in this one instance _vm_PropertyChanged never fires? I'd expect tempMessage being set to do so?
The order of events in your code is the following
Constructor of LocationsViewModel is called
From your constructor, you are setting tempMessage
The setter of tempMessage calls OnPropertyChanged, since the event is null at the time being, it's not fired
Constructor of LocationsViewModel is left
Page.BindingContext is set
OnBindingContextChanged is called
LocationsViewModel.PropertyChanged is subscribed by your page
Since the event is raised (or it's tried to) before your page subscribes to, your page simply does not get informed about the event being raised. If you set the value after the event has been subscribed to, the handler will be called as expected.
e.g.
protected override void OnBindingContextChanged()
{
_vm = BindingContext as LocationsViewModel;
_vm.PropertyChanged += _vm_PropertyChanged;
_vm.tempMessage = "Hello, world!"; // clichée , I know
}

Execute Pick Point from Windows Form in ArcGIS

I have a windows form which is launched with an ESRI AddIn button (ArcGIS 10.2 and Windows 7). On my form I have a button to pick a point from the Map. I have added an ESRI BaseTool class to the project, which has an OnMouseDown event.
The problem is that I cannot get the Tool to run. Note that the tool is not on the ArcGIS Command Bar (like the button is) but the tool is still found by the Find(uid) process.
When the Tool was added to the project (using the ArcGIS Add BaseTool process) it didn't update the .esriaddinx file. I had to do that manually.
My Addin file is:
<AddIn language="CLR4.0" library="HVLR_Processing.dll" namespace="HVLR_Processing">
<ArcMap>
<Commands>
<Button id="RMS_HVLR_Processing_clsHVLR_Processing" class="clsHVLR_Processing" ...
<Tool id="HVLR_PickTool" class="clsMapPick" category="Add-In Controls" caption="" message="" tip="" image="" />
</Commands>
</ArcMap>
The clsMapClick code contains the OnMouseDown event.
To start the process I have tried many methods. I can retrieve the Tool but when I execute it (or assign it to the CurrentTool) nothing happens.
UID pUID;
ICommandItem pCmdItem;
ICommand pCmd;
clsMapPick pPick;
ITool pTool;
try
{
this.WindowState = FormWindowState.Minimized;
m_pApp.CurrentTool = null;
pUID = new UIDClass();
pUID.Value = "HVLR_PickTool";
pCmdItem = m_pApp.Document.CommandBars.Find(pUID, false, false);
if (pCmdItem != null)
{
m_pApp.CurrentTool = pCmdItem; // Nothing happens
m_pApp.CurrentTool.Execute(); // Nothing happens
m_pApp.CurrentTool.Refresh();
}
}
catch (Exception ex)
Can anyone tell me how to get this tool to execute?
OK. Big stuff-up. You can't add a BaseTool to an ESRI AddIn; it's a COM object. What has to be done is:
Create a new ESRI Tool class.
Add a boolean variable to the class to indicate the mousedown event has fired.
In the OnUpdate method put some code to continue until the mousedown event has fired.
Create an OnMouseDown event handler by starting to type protected void On... and itellisense will allow you to select the event you want to track.
Put the code you want to run in the OnMouseDown event handler and also set the boolean value to true.
Code:
public class clsMapPick : ESRI.ArcGIS.Desktop.AddIns.Tool
{
private bool m_bIsFinished = false;
private int m_iXPixel = -1;
private int m_iYPixel = -1;
//private string m_sError = "";
//private bool m_bSuccess = true;
public clsMapPick()
{
}
protected override void OnActivate()
{
base.OnActivate();
return;
}
protected override void OnUpdate()
{
if (m_bIsFinished)
{
m_bIsFinished = false;
frmHVLR.m_dX = m_iXPixel;
frmHVLR.m_dX = m_iYPixel;
}
}
protected override void OnMouseDown(MouseEventArgs arg)
{
base.OnMouseDown(arg);
m_iXPixel = arg.X;
m_iYPixel = arg.Y;
m_bIsFinished = true;
}
}
In the form where the button for clicking on the map is fired:
string sError = "";
dPickedX = 0;
dPickedY = 0;
UID pUID;
ICommandItem pCmdItem;
ICommandBars pCmdBars;
ICommand pCmd;
ITool pTool;
try
{
this.WindowState = FormWindowState.Minimized;
pCmdBars = m_pApp.Document.CommandBars;
pUID = new UIDClass();
pUID.Value = HVLR_Processing.ThisAddIn.IDs.clsMapPick;
pCmdItem = pCmdBars.Find(pUID);
if (pCmdItem != null)
{
m_pApp.CurrentTool = pCmdItem;
//pCmdItem.Execute();
dPickedX = m_pMxDoc.CurrentLocation.X;
dPickedY = m_pMxDoc.CurrentLocation.Y;
}
return sError;
}
This is working fine for me now, the Tool class is being called but the OnMouseDown event isn't being fired.
If you know why I'd appreciate it.

log4net: How to distinguish between different forms on the same UI thread?

is there a way (NDC, Properties, ...?) to have a name/id per form that is included in all log4net messages, so I can distinguish between the forms in all log messages?
I have many service methods etc. that are used in all my forms, and I'd like to see e.g. that a service was called as a result of user input in what form (think multiple nonmodal similar forms (same class), running in the same UI thread, containing a button, and in the button's Click-Event, a service method is called. Inside the service method, there are logging calls. In the log messages, I'd like to have a property containing the information of in exactly which form instance the button was clicked in).
I don't want to modify ALL logging calls. The examples in the web for log contexts / NDC all only talk about multiple clients / asp.net requests / etc., not multiple forms in 1 thread.
Thanks,
Tim
To do this, set the properties in the form's Activated event to what you want to log:
private void Form1_Activated(object sender, System.EventArgs e)
{
// for example
log4net.GlobalContext.Properties["Name"] = this.GetType().Name;
log4net.GlobalContext.Properties["Id"] = this.Id;
}
The in your logging configuration, you can reference the properties in the PatternLayout for each appender:
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{Name} : %property{Id} : [%level]- %message%newline" />
</layout>
Edit: to preserve multiple values, use a stack, as in this unit test which outputs:
Now in TestClass1 Now in TestClass2
using log4net.Appender;
using log4net.Config;
using log4net.Core;
using log4net.Layout;
using NUnit.Framework;
namespace log4net.Tests
{
[TestFixture] // A NUnit test
public class log4net_Stacks
{
[SetUp]
public void Setup()
{
ConsoleAppender ca = new ConsoleAppender
{
Layout = new PatternLayout("%property{demo}"),
Threshold = Level.All
};
ca.ActivateOptions();
BasicConfigurator.Configure(ca);
}
[Test]
public void Stacks_Demo()
{
new TestClass1().Method1();
LogManager.GetLogger("logger").Debug("");
ThreadContext.Stacks["demo"].Clear();
}
private abstract class BaseTestClass
{
protected static void AddToStack(string message)
{
ThreadContext.Stacks["demo"].Push(message);
}
}
private class TestClass1 : BaseTestClass
{
public void Method1()
{
AddToStack("Now in " + GetType().Name);
var tc2 = new TestClass2();
tc2.Method2();
}
}
private class TestClass2 : BaseTestClass
{
public void Method2()
{
AddToStack("Now in " + GetType().Name);
}
}
}
}

Chain multiple 2 step file uploads with Rx

I am attempting to upload multiple files from a Silverlight client directly to Amazon S3. The user chooses the files from the standard file open dialog and I want to chain the uploads so they happen serially one at a time. This can happen from multiple places in the app so I was trying to wrap it up in a nice utility class that accepts an IEnumerable of the chosen files exposes an IObservable of the files as they are uploaded so that the UI can respond accordingly as each file is finished.
It is fairly complex due to all the security requirements of both Silverlight and AmazonS3. I'll try to briefly explain my whole environment for context, but I have reproduced the issue with a small console application that I will post the code to below.
I have a 3rd party utility that handles uploading to S3 from Silverlight that exposes standard event based async methods. I create one instance of that utility per uploaded file. It creates an unsigned request string that I then post to my server to sign with my private key. That signing request happens through a service proxy class that also uses event based async methods. Once I have the signed request, I add it to the uploader instance and initiate the upload.
I've tried using Concat, but I end up with only the first file going through the process. When I use Merge, all files complete fine, but in a parallel fashion rather than serially. When I use Merge(2) all files start the first step, but then only 2 make their way through and complete.
Obviously I am missing something related to Rx since it isn't behaving like I expect.
namespace RxConcat
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Timers;
public class SignCompletedEventArgs : EventArgs
{
public string SignedRequest { get; set; }
}
public class ChainUploader
{
public IObservable<string> StartUploading(IEnumerable<string> files)
{
return files.Select(
file => from signArgs in this.Sign(file + "_request")
from uploadArgs in this.Upload(file, signArgs.EventArgs.SignedRequest)
select file).Concat();
}
private IObservable<System.Reactive.EventPattern<SignCompletedEventArgs>> Sign(string request)
{
Console.WriteLine("Signing request '" + request + "'");
var signer = new Signer();
var source = Observable.FromEventPattern<SignCompletedEventArgs>(ev => signer.SignCompleted += ev, ev => signer.SignCompleted -= ev);
signer.SignAsync(request);
return source;
}
private IObservable<System.Reactive.EventPattern<EventArgs>> Upload(string file, string signedRequest)
{
Console.WriteLine("Uploading file '" + file + "'");
var uploader = new Uploader();
var source = Observable.FromEventPattern<EventArgs>(ev => uploader.UploadCompleted += ev, ev => uploader.UploadCompleted -= ev);
uploader.UploadAsync(file, signedRequest);
return source;
}
}
public class Signer
{
public event EventHandler<SignCompletedEventArgs> SignCompleted;
public void SignAsync(string request)
{
var timer = new Timer(1000);
timer.Elapsed += (sender, args) =>
{
timer.Stop();
if (this.SignCompleted == null)
{
return;
}
this.SignCompleted(this, new SignCompletedEventArgs { SignedRequest = request + "signed" });
};
timer.Start();
}
}
public class Uploader
{
public event EventHandler<EventArgs> UploadCompleted;
public void UploadAsync(string file, string signedRequest)
{
var timer = new Timer(1000);
timer.Elapsed += (sender, args) =>
{
timer.Stop();
if (this.UploadCompleted == null)
{
return;
}
this.UploadCompleted(this, new EventArgs());
};
timer.Start();
}
}
internal class Program
{
private static void Main(string[] args)
{
var files = new[] { "foo", "bar", "baz" };
var uploader = new ChainUploader();
var token = uploader.StartUploading(files).Subscribe(file => Console.WriteLine("Upload completed for '" + file + "'"));
Console.ReadLine();
}
}
}
The base observable that is handling the 2 step upload for each file is never 'completing' which prevents the next one in the chain from starting. Add a Limit(1) to that observable prior to calling Concat() and it will working correctly.
return files.Select(file => (from signArgs in this.Sign(file + "_request")
from uploadArgs in this.Upload(file, signArgs.EventArgs.SignedRequest)
select file).Take(1)).Concat();

How to avoid View specific code in my ViewModel

My application has a menu option to allow the creation of a new account. The menu option's command is bound to a command (NewAccountCommand) in my ViewModel. When the user clicks the option to create a new account, the app displays a "New Account" dialog where the user can enter such data as Name, Address, etc... and then clicks "Ok" to close the dialog and create the new account.
I know my code in the ViewModel is not correct because it creates the "New Account" dialog and calls ShowDialog(). Here is a snippet from the VM:
var modelResult = newAccountDialog.ShowDialog();
if (modelResult == true)
{
//Create the new account
}
how do i avoid creating and showing the dialog from within my VM so I can unit test the VM?
I like the approach explained in this codeproject article:
http://www.codeproject.com/KB/WPF/XAMLDialog.aspx
It basically creates a WPF Dialog control that can be embedded in the visual tree of another window or usercontrol.
It then uses a style trigger that causes the dialog to open up whenever there is content in the dialog.
so in you xaml all you have to do is this(where DialogViewModel is a property in you ViewModel):
<MyControls:Dialog Content = {Binding DialogViewModel}/>
and in you ViewModel you just have to do the following:
DialogViewModel = new MyDialogViewModel();
so in unit testing all you have to do is:
MyViewModel model = new MyViewModel();
model.DialogViewModel = new MyDialogViewModel();
model.DialogViewModel.InputProperty = "Here's my input";
//Assert whatever you want...
I personally create a ICommand property in my ViewModel that sets the DialogViewModel property, so that the user can push a button to get the dialog to open up.
So my ViewModel never calls a dialog it just instantiates a property. The view interprets that and display a dialog box. The beauty behind this is that if you decide to change your view at all and maybe not display a dialog, your ViewModel does not have to change one bit. It pushes all the User interaction code where it should be...in the view. And creating a wpf control allows me to re-use it whenever I need to...
There are many ways to do this, this is one I found to be good for me. :)
In scenarios like this, I typically use events. The model can raise an event to ask for information and anybody can respond to it. The view would listen for the event and display the dialog.
public class MyModel
{
public void DoSomething()
{
var e = new SomeQuestionEventArgs();
OnSomeQuestion(e);
if (e.Handled)
mTheAnswer = e.TheAnswer;
}
private string mTheAnswer;
public string TheAnswer
{
get { return mTheAnswer; }
}
public delegate void SomeQuestionHandler(object sender, SomeQuestionEventArgs e);
public event SomeQuestionHandler SomeQuestion;
protected virtual void OnSomeQuestion(SomeQuestionEventArgs e)
{
if (SomeQuestion == null) return;
SomeQuestion(this, e);
}
}
public class SomeQuestionEventArgs
: EventArgs
{
private bool mHandled = false;
public bool Handled
{
get { return mHandled; }
set { mHandled = value; }
}
private string mTheAnswer;
public string TheAnswer
{
get { return mTheAnswer; }
set { mTheAnswer = value; }
}
}
public class MyView
{
private MyModel mModel;
public MyModel Model
{
get { return mModel; }
set
{
if (mModel != null)
mModel.SomeQuestion -= new MyModel.SomeQuestionHandler(mModel_SomeQuestion);
mModel = value;
if (mModel != null)
mModel.SomeQuestion += new MyModel.SomeQuestionHandler(mModel_SomeQuestion);
}
}
void mModel_SomeQuestion(object sender, SomeQuestionEventArgs e)
{
var dlg = new MyDlg();
if (dlg.ShowDialog() != DialogResult.OK) return;
e.Handled = true;
e.TheAnswer = dlg.TheAnswer;
}
}
The WPF Application Framework (WAF) shows a concrete example how to accomplish this.
The ViewModel sample application shows an Email Client in which you can open the “Email Account Settings” dialog. It uses dependency injection (MEF) and so you are still able to unit test the ViewModel.
Hope this helps.
jbe
There are different approaches to this. One common approach is to use some form of dependency injection to inject a dialog service, and use the service.
This allows any implementation of that service (ie: a different view) to be plugged in at runtime, and does give you some decoupling from the ViewModel to View.