Call method .NET from JavaScript - asp.net

I have a method in .NET (GetDataStationParts), which I declare with 2 parameters, I want to call it from a JavaScript, and I use the InvokeMethodAsyn function in this way:
const { data } = require("jquery");
function GetParteScrap()
{
var idestacionjs = document.getElementById('getestacion');
var idmodelojs = document.getElementById('getmodelo');
var tablascrap = DotNet.InvokeMethodAsyn("YMMScrapSystem", "GetDataStationParts", idestacionjs, idmodelojs);
console.log(tablascrap);
}
To do it, I base it on an example on the web but I'm not sure where it gets the DotNet object to then invoke the method, the intention of my code is that after selecting parameters of 2 , go to the database and execute a SQL-level function, which will return a table, with the function GetDataStationParts, I try to give it the functionality to execute my method at the DB level as follows
[JSInvokable]
public async Task<IEnumerable<GetEstacionParte>>GetDataStationParts(int modelo, int estacion)
{
var resul = await _context.Set<GetEstacionParte>().FromSqlInterpolated($"SELECT * FROM dbo.GetEstacionParte({modelo},{estacion})").ToArrayAsync();
return resul;
}
The SQL level function works correctly, but when running the application at the console level in the browser, it throws the following error, where it indicates that the function is not defined
Where could the error be? Thank you for reading

require() is not a feature that is built into the browser. Javascript environment does not understand how to handle require(), In Node.js by Default this function is available.
I suspect you most probably missing some reference here. You can either download require.js from here & link with your application or use below script tag.
<script src="https://requirejs.org/docs/release/2.3.5/minified/require.js"></script>

Related

Blazor Unmarshalled JavaScript interop

To improve performance in Blazor JS Interop calls, synchronous and unmarshalled apis are available
I struggle to find more information regarding the unmarshalled.
For example:
//javascript
JSFunctions.f1 = function (fields) {
var f1 = Blazor.platform.readStringField(fields, 0);
var f2 = Blazor.platform.readStringField(fields, 4);
var f3 = Blazor.platform.readStringField(fields, 8);
};
//F#
[<Inject>]
member val Js: IJSRuntime
let js = this.Js :?> IJSUnmarshalledRuntime
js.InvokeUnmarshalled<ElementReference, string, unit>("JSFunctions.f1", er, txt)
Where are the functions Blazor.platform.* defined?
Which one should be used to retrieve an argument of type ElementReference?
What is the second int parameter of the function readStringField and how should it be used?
Blazor object is a JavaScript object in global namespace (window) which added by blazor.webassembly.js in Blazor WebAssembly or blazor.server.js in Blazor Server. It added at the default template of Blazor Apps at the end of index.html (or _Host.cshtml) by following script:
<script autostart="false" src="_framework/blazor.webassembly.js"></script>
The Blazor object provide Blazor.platform and some useful api for example start() for manual start of Blazor.
This script also add another object named BINDING to global namespace (window.BINDING or simply BINDING).
They provide methods for working with .NET objects directly from JavaScript in unmarshalled way. for example you can read different type of data using
Blazor.platform.read....
You can read objects like ElementReference type object using:
Blazor.platform.readObjectField(fields,index)
Here fields is the input (struct or class) passed to JS function when you invoke it and index is its field offset in struct/class definition. You can read more about field offset in Microsoft documentations here.
Here is some example:
[StructLayout(LayoutKind.Explicit)]
public struct InteropStruct
{
[FieldOffset(0)]
public string Name;
[FieldOffset(8)]
public int Year;
}
You can also return a .Net object directly from JavaScript functions using BINDING as below:
return BINDING.js_string_to_mono_string(`Hello, ${name} (${year})!`);
You can discover more about these two objects in your browser developer tool for example by writing Blazor.platform. or BINDING.:

How does my xUnit test pass when I have Assert.Null(result) and Assert.NotNull(result)?

I refactored some tests in my solution from MSTest to xUnit. Even though all my tests passed using MSTest, there were some changes performed that made me wonder how everything was so easily passing during my refactor.
I put contradictory assertions at the end of a test and debugged. Even though the result looked like what I wanted it to look like (the object was null), it passed both Assertions. How is this possible? What am I doing wrong?
The following is my test. The naming is modified, because this is code I am working on at work, but the modifications end at simple replacing of words. I added comments to show some of my intentions as well as what happened when I debugged the test.
using AutoFixture.Xunit;
using Moq;
using My.Core.Project.Interfaces;
using My.Core.Project].Models;
using My.UI.Project.Factories.Sidebar;
using System;
using System.Threading.Tasks;
using Xunit;
using Xunit.Extensions;
[Theory, AutoData]
public async Task GetReturnedObject_NoReturnedObject_EmptyResult(Guid returnedObjectIdentifier, ReturnedObjectType setupObject)
{
//Arrange
var mockServiceClient = new Mock<IServiceClient>(MockBehavior.Strict);
var returnedObjectIdentifierParameter = returnedObjectIdentifier.ToString(); //Parse logic in the method exists, so I had to make sure the input was not just any string
setupObject = null; //I want the search in the method to not find anything.
mockServiceClient.Setup(c => c.GetReturnedObjectById(It.IsAny<Guid>())).ReturnsAsync(setupObject);
var factory = new Factory();
//Act
var returnedObject = await factory.GetReturnedObject(mockServiceClient.Object, returnedObjectIdentifierParameter); //returnedObject is NULL.
//Assert
Assert.Null(returnedObject); //Hovered over returnedObject. It's NULL.
Assert.NotNull(returnedObject); //Hovered over returnedObject, again. Still NULL. THIS SHOULD FAIL!
}

using export in alloy controller versus attaching functions directly to the '$' scope

here is the code of an alloy controller written in two different ways. Although the both work the same, Which one might be best practice?
example 1 of controller.js:
var currentState = true;
$.getState = function(){
return currentState;
}
example 2 of controller.js:
var currentState = true;
exports.getState = function(){
return currentState;
}
Titanium is based on the CommonJS framework. The exports variable is a special variable used typically to expose a public API in a class object. So when you want to expose a method of doSomething() on the MyModule.js class you would use the exports variable like this:
exports.doSomething() = function(args) {
//Some really cool method here
};
Then reference that class using
var myModule = require('MyModule');
myModule.doSomething();
However when referencing a view object the typical way to reference the is using the $. shortcut. You can see they prefer that method in the official documentation.
http://docs.appcelerator.com/platform/latest/#!/guide/Alloy_XML_Markup
The $ variable holds a reference to your controller instance. It also contains some references to all indexed views (understand, views for which you supplied an index in you xml markup).
Both ways are strictly equivalent as, during the compilation, Alloy will merge the content of the exports with your controller referenced in $. Adding them directly to the instance won't change a thing.
Neverthless, developers are used to see the public API as the set of functions exported via the special variable exports; Thus, I will recommend to keep using it in a clean and clear way (for instance, defining your functions in your module scope, and only expose them at the end or beginning of your controller).
function myFunction1 () { }
function myFunction2 () { }
function myFunction3 () { }
exports.myFunction1 = myFunction1;
exports.myFunction3 = myFunction3;
Thereby, your API is quite clear for people diving into your source code. (A readMe file is also highly recommended :) ).

Multiple asynchronous calls to populate an object

I'm developing a Flex application and am having some trouble working with asynchronous calls. This is what I would like to be able do:
[Bindable] var fooTypes : ArrayCollection();
for each (var fooType : FooType in getFooTypes()) {
fooType.fooCount = getFooCountForType(fooType);
itemTypes.addItem(fooType);
}
The issue I'm running into is that both getFooTypes and getFooCountForType are asynchronous calls to a web service. I understand how to populate fooTypes by setting a Responder and using ResultEvent, but how can I call another service using the result? Are there any suggestions/patterns/frameworks for handling this?
If possible, I Strongly recommed re-working your remote services to return all the data you need in one swoop.
But, if you do not feel that is possible or practical for whatever reason, I would recommend doing some type of remote call chaining.
Add all the "remote calls" you want to make in array. Call the first one. In the result handler process the results and then pop the next one and call it.
I'm a bit unclear from your code sample when you are calling the remote call, but I assume it part of the getFooCountForType method. Conceptually I would do something like this. Define the array of calls to make:
public var callsToMake : Array = new Array();
cache the currently in process fooType:
public var fooType : FooType;
Do your loop and store the results:
for each (var fooType : FooType in getFooTypes()) {
callsToMake.push(fooType);
// based on your code sample I'm unclear if adding the fooTypes to itemTypes is best done here or in the result handler
itemTypes.addItem(fooType);
}
Then call the remote handler and save the foo you're processing:
fooType = callsToMake.pop();
getFooCountForType(fooTypeToProcess);
In the result handler do something like this:
// process results, possibly by setting
fooType.fooCount = results.someResult;
and call the remote method again:
fooType = callsToMake.pop();
getFooCountForType(fooTypeToProcess);

How does ASP.NET AJAX work when retrieving values from the server?

If I want to call a server function from JavaScript to retrieve a name of a person from a database (just as an example)... and I went...
name = myServices.getName(userId);
If I have a script manager with a service reference to a .asmx file that has the web method getName( int userId ) {} then this function should be called properly and would, eventually, return the name for that userId.
Unfortunately, I want to do...
name = myServices.getName(userId);
alert(name);
however, when doing ASP.NET AJAX, it would call the web method and continue executing before waiting for a response from the server (which I understand is the point of AJAX, to stop the browser from freezing while waiting for data)
I need to get the name back from the server before I can continue executing... How can I approach this to fix this issue?
There is a method you can add as a parameter to the service method that will call the method on success where you can do other stuff.
For example:
function test() {
PageMethods.MyMethod("name", OnMyMethodComplete);
}
function OnMyMethodComplete(result, userContext, methodName) {
alert(result);
}
If you want to call a Web method synchronously, you'll need to set up the request manually and use a Sys.Net.XMLHttpSyncExecutor.
Here's an example (see ExecuteSynchronously function).
For a JavaScript solution, you could loop until name has a value. Adjust time-based on latency to keep app responsive
var time = 100;
window.setTimeout(name == '' ? wait : continue, time);
function wait() {
window.setTimeout(name == '' ? wait : continue, time);
}
function continue() {
//code having to do with name
alert(name);
}
Congratulations! You've taken your first step into a larger asynchronous world. I'd definitely go with using the callbacks that CSharpAtl suggested.

Resources