Usage of Object invoke(Object thiz, Object[] args) method in BlackBerry - blackberry

Can anybody please explain me how the arguments in invoke method can use correctly.
browserField.extendScriptEngine("interesting.test", new ScriptableFunction() {
public Object invoke(Object thiz, Object[] args) throws Exception {
Dialog.alert("Done");
return super.invoke(thiz, args);
}
});
I have call above method in the HTML file as follow.
<button type="button" onclick="interesting.test()">Display Alert</button>
When I use following code
System.out.println("# thiz : " + thiz.toString());
result is
[0.0] # thiz : net.rim.device.apps.internal.browser.olympia.dom.ScriptObjectShadow#a2f32d2a
and when I use this code
System.out.println("# args : " + args.length);
the result is
[0.0] # args : 0
which prints on the Console.
I have used both those System.out method inside invoke method. Also I have refer the API documentation and still I could not understand how to pass values to those two arguments and retrieve them.

You could try this, it worked for me
try{
browserField.extendScriptEngine("interesting.test", new ScriptableFunction() {
public Object invoke(Object thiz, static Object[] args) throws Exception {
Dialog.alert(String.valueOf(args[0]).toString());
}
});
} catch(Exception e){
//
}
and then from html do this
<button type="button" onclick="interesting.test('cool')">Display Alert</button>
because those arguments are simply array of objects that can mean having more than one parameter at the same time for flexibility purposes, its kind of similar to the arguments that is used in javascript. So try it out...

Related

Simple Injector throws an error in Caliburn.Micro Bootstrapper.Buildup when calling async method in the viewmodel

I am trying to use Simple Injector as the DI container for Caliburn.Micro. Demo source: https://github.com/nvstrien/WPFDemos
This project has a basic Caliburn.Micro setup with a Simple Injector Container. The ShellView has 1 button and when pressed, an async method is called to get some simulated data.
I am getting this error in Bootstrapper.Buildup.
SimpleInjector.ActivationException: 'No registration for type SequentialResult could be found. Make sure SequentialResult is registered, for instance by calling 'Container.Register<SequentialResult>();' during the registration phase. An implicit registration could not be made because Container.Options.ResolveUnregisteredConcreteTypes is set to 'false', which is now the default setting in v5. This disallows the container to construct this unregistered concrete type. For more information on why resolving unregistered concrete types is now disallowed by default, and what possible fixes you can apply, see https://simpleinjector.org/ructd. '
It has been suggested here that commenting out Bootstrapper.BuildUp should work: Caliburn.Micro Bootstrapper 'BuildUp' method throws exception when Simple Injector is used
However, when doing so, SimpleInjector will still throw an exception.
Any help solving this would be greatly appreciated
My complete Bootstrapper config file looks like this:
public static readonly Container _container = new();
public Bootstrapper()
{
Initialize();
}
protected override void Configure()
{
_container.Register<IWindowManager, WindowManager>();
_container.RegisterSingleton<IEventAggregator, EventAggregator>();
GetType().Assembly.GetTypes()
.Where(type => type.IsClass)
.Where(type => type.Name.EndsWith("ViewModel"))
.ToList()
.ForEach(viewModelType => _container.RegisterSingleton(viewModelType, viewModelType));
_container.Verify();
}
protected override void OnStartup(object sender, System.Windows.StartupEventArgs e)
{
DisplayRootViewFor<ShellViewModel>();
}
protected override IEnumerable<object> GetAllInstances(Type service)
{
// as discussed here: https://stackoverflow.com/questions/32258863/simple-injector-getallinstances-throwing-exception-with-caliburn-micro
//_container.GetAllInstances(service);
IServiceProvider provider = _container;
Type collectionType = typeof(IEnumerable<>).MakeGenericType(service);
IEnumerable<object> services = (IEnumerable<object>)provider.GetService(collectionType);
return services ?? Enumerable.Empty<object>();
}
protected override object GetInstance(System.Type service, string key)
{
return _container.GetInstance(service);
}
protected override IEnumerable<Assembly> SelectAssemblies()
{
return new[] { Assembly.GetExecutingAssembly() };
}
// see: https://stackoverflow.com/questions/37631468/caliburn-micro-bootstrapper-buildup-method-throws-exception-when-simple-inject
// commenting out BuildUp still throws an exception in SimpleInjector.dll
protected override void BuildUp(object instance)
{
InstanceProducer registration = _container.GetRegistration(instance.GetType(), true);
registration.Registration.InitializeInstance(instance);
}
In the ShellViewModel I have 1 method that runs when pressing a button on the ShellView.
public async Task Button1()
{
Debug.Print("Hello world");
var data = await GetSampleDataAsync();
foreach (var item in data)
{
Debug.Print(item);
}
}
public async Task<IEnumerable<string>> GetSampleDataAsync()
{
// method simulating getting async data
var data = new List<string>() { "hello", "world" };
return await Task.FromResult(data);
}
The error occurs when 'await GetSampleDataAsync()' gets called.
When adding the SequentialResult in Bootstrapper.Configure as follows.
protected override void Configure()
{
_container.Register<IWindowManager, WindowManager>();
_container.RegisterSingleton<IEventAggregator, EventAggregator>();
_container.Register<SequentialResult>();
GetType().Assembly.GetTypes()
.Where(type => type.IsClass)
.Where(type => type.Name.EndsWith("ViewModel"))
.ToList()
.ForEach(viewModelType => _container.RegisterSingleton(viewModelType, viewModelType));
_container.Verify();
}
I get the next error:
System.InvalidOperationException
HResult=0x80131509 Message=The configuration is invalid. Creating
the instance for type SequentialResult failed. The constructor of type
SequentialResult contains the parameter with name 'enumerator' and
type IEnumerator<IResult>, but IEnumerator<IResult> is not registered.
For IEnumerator<IResult> to be resolved, it must be registered in the
container. Source=SimpleInjector StackTrace: at
SimpleInjector.InstanceProducer.VerifyExpressionBuilding() at
SimpleInjector.Container.VerifyThatAllExpressionsCanBeBuilt(InstanceProducer[]
producersToVerify) at
SimpleInjector.Container.VerifyThatAllExpressionsCanBeBuilt() at
SimpleInjector.Container.VerifyInternal(Boolean
suppressLifestyleMismatchVerification) at
SimpleInjector.Container.Verify(VerificationOption option) at
SimpleInjector.Container.Verify() at
CaliburnMicroWithSimpleInjectorDemo.Bootstrapper.Configure() in
C:\Users\Niels\source\repos\WPFDemos\CaliburnMicroWithSimpleInjectorDemo\Bootstrapper.cs:line
37 at Caliburn.Micro.BootstrapperBase.StartRuntime() at
Caliburn.Micro.BootstrapperBase.Initialize() at
CaliburnMicroWithSimpleInjectorDemo.Bootstrapper..ctor() in
C:\Users\Niels\source\repos\WPFDemos\CaliburnMicroWithSimpleInjectorDemo\Bootstrapper.cs:line
22
This exception was originally thrown at this call stack:
[External Code]
Inner Exception 1: ActivationException: The constructor of type
SequentialResult contains the parameter with name 'enumerator' and
type IEnumerator<IResult>, but IEnumerator<IResult> is not registered.
For IEnumerator<IResult> to be resolved, it must be registered in the
container.
When I change the methods in my ShellViewModel to be synchronous like this, I don't get any exceptions:
public void Button1()
{
Debug.Print("Hello world");
var data = GetSampleData();
foreach (var item in data)
{
Debug.Print(item);
}
}
public IEnumerable<string> GetSampleData()
{
var data = new List<string>() { "hello", "world" };
return data;
}
It seems to me that the container doesn't get configured properly to work with some implementation in Caliburn.Micro, but the Bootstrapper configuration follows the recommended path. I am unfortunately not able to follow the explanation here: Caliburn.Micro Bootstrapper 'BuildUp' method throws exception when Simple Injector is used Also, what was marked as solution doesn't seem to work in my code sample.
#Steven: Commenting out BuildUp indeed fixed my problem.
I thought that I had tested commenting out BuildUp in my sample project before coming to SO to ask my question, but trying it again now solved my problem. Thank you for putting me back on the right track!
Solution: comment out / delete BootStrapper.BuildUp as was also suggested here: Caliburn.Micro Bootstrapper 'BuildUp' method throws exception when Simple Injector is used
//protected override void BuildUp(object instance)
//{
// InstanceProducer registration = _container.GetRegistration(instance.GetType(), true);
// registration.Registration.InitializeInstance(instance);
//}

Vaadin : how to get return value from javascript methods?

I have one JS method showMessage(message)
function showMessage(message) {
alert(message);
return "Your message is " + message;
}
I can get arguments of method from my component or UI as
JavaScript.getCurrent().addFunction("showMessage", new JavaScriptFunction() {
#Override
public void call(final JSONArray arguments) throws JSONException {
System.out.println("Getting call JS method " + arguments);
}
});
Page.getCurrent().getJavaScript().execute("showMessage(Hello World !)");
So , has there anyway to get return values of JS methods in Vaadin ? If yes , how can I figure it out ?
no you can't return from there
Because of the asynchronous nature of the communication between client and server, no return value can be sent back to the browser.
https://vaadin.com/api/7.2.5/com/vaadin/ui/JavaScriptFunction.html#call(org.json.JSONArray)
To get the return value, you have to actually callback to the server (your defined showMessage method on server side) from your client side showMessage (browser/javascript). I would assume, that your main problem here is naming them both the same (I am not sure, if Vaadin applies here some package name based prefix, but most likely one of your showMessaage methods overrides the other).
You should rename your client's showMessage to something else (requestMessage below) and call your server's showMethod in there.
// client/browser/javascript (remove/rename existing showMessage from your _client_ code)
function requestMessage(m) { showMessage("Requested: "+m) }
// server/vaadin/java
Page.current.javaScript.execute("requestMessage('Hello World')")

not able to handle JSF render exception

Using mojarra 2.1.27 and richfaces 4.3.6 on tomcat7, I was trying to implement my own exception handler for the ajax requests (Following all your advices) but I never get access to the render exception.
I have normal postback exceptions handled through web.xml <error-page> directives, which works fine, and ajax request should go through my custom handler. This seems to work when updating values and invoking the actions, but not with exceptions during rendering phase.
Having this simple ajax command button
<a4j:commandButton execute="#this" action="#{testController.actionButton4}"
render="#form" value="Ajax Post + Render Error"/>
which (amongst others) renders a div with a result
<div id="result">
#{testController.result}
</div>
Is backed by a simple action in my TestController
public String actionButton4() {
result = "action4";
inError = true;
return null;
}
And a simple getter which is used during the render.
public String getResult() {
if (inError) {
inError = false;
throw new RuntimeException("Render error in " + result);
}
return result;
}
My handler does more or less the default behaviour
public void handle() throws FacesException {
dohandle();
getWrapped().handle();
}
public void dohandle() throws FacesException {
FacesContext fc = FacesContext.getCurrentInstance();
PhaseId phaseId = fc.getCurrentPhaseId();
boolean partialRequest = fc.getPartialViewContext().isPartialRequest();
boolean ajaxRequest = fc.getPartialViewContext().isAjaxRequest();
Iterator<ExceptionQueuedEvent> iterator = getUnhandledExceptionQueuedEvents().iterator();
log.trace("Phase id ({})", phaseId);
while (iterator.hasNext()) {
log.trace("Request is partial ({}). Request is ajax ({})", partialRequest, ajaxRequest);
if (!ajaxRequest) {
return;
}
...
}
}
What I see during rendering is a logging exception in the ExtendedPartialViewcontextImpl of richfaces
Jun 25, 2014 10:18:44 AM org.richfaces.context.ExtendedPartialViewContextImpl$RenderVisitCallback logException
SEVERE: /test2.xhtml: Error reading 'result' on type c.n.g.w.controller.TestController
...
Then I see the phase ends and the exception handler is consulted
10:18:44.336 {http-bio-8080-exec-2} TRACE c.n.g.w.generic.LifeCycleListener - END PHASE RENDER_RESPONSE 6
10:18:44.336 {http-bio-8080-exec-2} TRACE c.n.g.w.generic.ExceptionHandler - Phase id (RENDER_RESPONSE 6)
But for some reason there is no unhandled exception in the queue.
I couldn't find anything stating that the RF rendering should react any different that others, but I suspect it could be. Does anyone know more than me here?
UPDATE:
I notice from the client side log that the rendered output is clipped right at the EL tag, so the rendering breaks and commits the partial result for some reason.

Struts2 Junit4 tests accumulate JSON responses with every action execution

I've written a few Junit4 tests, which looks like this :
public class TestCampaignList extends StrutsJUnit4TestCase<Object> {
public static final Logger LOG = Logger.getLogger(TestCampaignList.class.getName());
#Before
public void loginAdmin() throws ServletException, UnsupportedEncodingException {
request.setParameter("email", "nitin.cool4urchat#gmail.com");
request.setParameter("password", "22");
String response = executeAction("/login/admin");
System.out.println("Login Response : " + response);
}
#Test
public void testList() throws Exception {
request.setParameter("iDisplayStart", "0");
request.setParameter("iDisplayLength", "10");
String response = executeAction("/campaign/list");
System.out.println("Reponse : " + response);
}
}
Both actions return JSON results and executeAction javadoc says :
For this to work the configured result for the action needs to be FreeMarker, or Velocity (JSPs can be used with the Embedded JSP plugin)
Seems like it's unable to handle JSON results and hence, the second action execution shows accumulated result, such that result_for_second_action= result1 concatenate result2
Is there a solution to get the executeAction() return the actual JSON response, rather than concatenating JSON responses from all previous executions.
This is happening because you are executing action in #Before method. In that way the setUp method of StrutsJUnit4TestCase is not getting called in between your loginAdmin and test method and you previous request parameters are passed to it again. You can call setUp method by yourself in your tests method.
In your case you can actually call initServletMockObjects method to create new mock servlet objects such as request.
#Test
public void testList() throws Exception {
setUp();
// or
// initServletMockObjects();
request.setParameter("iDisplayStart", "0");
request.setParameter("iDisplayLength", "10");
String response = executeAction("/campaign/list");
System.out.println("Reponse : " + response);
}

Databinding to a DomainDataSource Query Parameter

I need to bind a username to a DomainDataSource QueryParameter. My understanding is that the following does not work:
<RiaControls:DomainDataSource x:Name="MyData" LoadSize="20" QueryName="GetStockByCompany" AutoLoad="True">
<RiaControls:DomainDataSource.DomainContext>
<ds:InventoryDomainContext />
</RiaControls:DomainDataSource.DomainContext>
<RiaControls:DomainDataSource.QueryParameters>
<riadata:Parameter
ParameterName="userName"
Value="{Binding Path=User.Name}" />
</RiaControls:DomainDataSource.QueryParameters>
</RiaControls:DomainDataSource>
I am not opposed to using the C# code-behind part of the page, but I'm not sure what event to put this in.
So far I've tried this:
public Inventory()
{
InitializeComponent();
Loaded += Inventory_Loaded;
}
private void Inventory_Loaded(object sender, RoutedEventArgs e)
{
this.MyData.QueryParameters.Add(new Parameter { ParameterName = "userID", Value = RiaContext.Current.User.Name});
}
But since InitializeComponent() fires first, and loades the data, which causes the DomainDataSource to bomb due to the Query not having any parameters to run... it didn't work.
Next I tried this...
[xaml file]
<RiaControls:DomainDataSource x:Name="MyData" LoadSize="20" QueryName="GetStockByCompany" AutoLoad="True" LoadingData="MyData_LoadingData">
[cs file]
private void MyData_LoadingData(object sender, LoadingDataEventArgs e)
{
this.MyData.QueryParameters.Add(new Parameter { ParameterName = "userID", Value = RiaContext.Current.User.Name});
}
Unfortunately, the event never fired. I'm not sure why.
I even tried this:
[xaml file]
<RiaControls:DomainDataSource x:Name="MyData" LoadSize="20" QueryName="GetStockByCompany" AutoLoad="True" LoadedData="MyData_LoadedData">
[cs file]
private void MyData_LoadedData(object sender, LoadedDataEventArgs e)
{
this.MyData.QueryParameters.Add(new Parameter { ParameterName = "userID", Value = RiaContext.Current.User.Name});
}
But that was just dumb.
I'm at a loss. How do I load this query, with the parameter, as the page loads?
Thanks!
Hmmm I not a specific answer to your problem but I may know a way to avoid the situation entirely.
I noticed you have a method named "GetStockByCompany" that accept the currently logged in user as a parameter...
You can completely remove the need for the parameter and instead on your server side query for "GetStockByCompany" use this in your "Where" part:
this.ServiceContext.User.Identity.Name
Ex - Getting all the albums for the currently logged in user:
album = this.Context.AlbumSet
.Where(n => n.AlbumId == AlbumId)
.Where(n => n.aspnet_Users.UserName == this.ServiceContext.User.Identity.Name)
.First();
Binding the query parameter works, the typical usage is that you bind it directly to controls.
To set the parameter in code behind, give the parameter a name and set the value property. There's no need to add the whole parameter in code behind.

Resources