A guide on incorporating LINQ in the Microsoft ClearScript V8 platform

Currently, I am making use of microsoft.clearscript.v8 in ASP.Net Core MVC. The following code snippet can be found in my Home controller:

public async Task<IActionResult> Index()
{
    using (var engine1 = new V8ScriptEngine())
    {
        engine1.AddHostType(typeof(JavaScriptExtensions));
        engine1.DocumentSettings.AccessFlags = DocumentAccessFlags.EnableFileLoading;
        string scriptPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "js", "NewScript.js");
        string scriptContent = System.IO.File.ReadAllText(scriptPath);
        engine1.Execute(scriptContent);
        dynamic data = engine1.Evaluate("NewLinq();");
        return View();
    }
}

The above code is located in NewScript.js file

function NewLinq() {
  const rawData = [
    { "id": 1, "name": "John", "age": 25 },
    { "id": 2, "name": "Jane", "age": 30 }      
  ];

  var result = rawData.filter(person => person.age > 25);  
  return result;
}

An error is being thrown by the code:

UnderlyingSystemType = '((Microsoft.ClearScript.ScriptItem)data).UnderlyingSystemType' threw an exception of type 'System.NotImplementedException'

I am seeking guidance on how to resolve this error and successfully implement linq functionality.

Answer №1

The issue you're encountering stems from a constraint in the ClearScript library when attempting to directly engage with the dynamic type produced by JavaScript execution. Instead of utilizing dynamic, consider casting the result data to a more explicit type.

Here is the adjusted code:

HomeController:

public async Task<IActionResult> Index()
{
    using (var engine1 = new V8ScriptEngine())
    {
        engine1.AddHostType(typeof(JavaScriptExtensions));
        engine1.DocumentSettings.AccessFlags = DocumentAccessFlags.EnableFileLoading;
        string scriptPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "js", "NewScript.js");
        string scriptContent = System.IO.File.ReadAllText(scriptPath);
        engine1.Execute(scriptContent);
        
        string jsonData = engine1.Evaluate("NewLinq();").ToString();

        var data = JsonConvert.DeserializeObject<List<Person>>(jsonData);

        return View(data);
    }
}

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

NewScript.js:

function NewLinq() {
  const rawData = [
    { "id": 1, "name": "John", "age": 25 },
    { "id": 2, "name": "Jane", "age": 30 }      
  ];

  var result = rawData.filter(person => person.age > 25);  
  return JSON.stringify(result); 
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Please provide either a string or an object containing the proper key for TypeScript

Within my project, the languageSchema variable can either be a string or an object containing the 'Etc' key. The corresponding interface is defined as follows: let getLanguageSchema = (language: string): string => languagesSchemas[language]; ...

Is it possible to include ternary in the "homepage" section of the package.json file?

When making API calls in production, they will be on the same domain as where my app is hosted, so it's necessary to include "homepage": "." in the package.json. However, when working locally from localhost, I need to make API calls to the production ...

Identify unique MongoDb instances within an array of data

My list contains various unique items - search = alluk.distinct('Object of search') I am interested in counting each item individually. Presently, I am counting them manually in the following way - alluk.find({'Object of search':&ap ...

A step-by-step guide to displaying image upload previews using React

I am currently working on developing an image upload form with the use of Next.js/React.js. The goal is to allow users to assign tags to each uploaded image and display a preview of the image using 'URL.createObjectURL'. Although the uploading pr ...

Finding elements in an array based on a specific string contained within a property

I am currently working on filtering JSON data to specifically search for job roles that begin with a particular string. The structure of the JSON is as follows : "periods": [ { "periodName": "Week1", "teamName": "Tango", ...

loading xml data into a table partially using jquery

Currently, I am utilizing AJAX to load and parse XML data. I have constructed a table where I am inserting the data from the XML using a loop. The issue lies in the fact that only around 3000 rows are being inserted into the table even though the XML conta ...

Retrieving the value of a nested JSON object with a dynamic key

Currently, I am attempting to log a JSON key that is dynamic to the console. However, there is another nested object inside the main object that I also need to access a value from. The key of this nested object contains special characters, so I have been u ...

Animating transitions on a dynamic Bootstrap navbar using jQuery

I have the code attached here, and I successfully changed the color of the navbar and logo when scrolling down. However, I am looking to add a transition effect when this change occurs. I experimented with various transition options in CSS, but unfortunat ...

Is it possible to eliminate additional properties from an object using "as" in Typescript?

I am looking for a way to send an object through JSON that implements an interface, but also contains additional properties that I do not want to include. How can I filter out everything except the interface properties so that only a pure object is sent? ...

What counterpart in JavaScript resembles the .NET Standard Class Library?

As someone transitioning from a background in .NET to learning Vue.js, I'm curious about the best way to create classes that handle business logic for me. Specifically, I want to be able to fetch information from an API, format it as needed and easily ...

Update the state when a button is clicked and send a request using Axios

Currently in my front end (using react): import '../styles/TourPage.css'; import React, { Component } from 'react'; import axios from 'axios' class TourPage extends Component { constructor(props) { super(p ...

Having trouble accessing `event.target.value` when selecting an item from the autocomplete feature in Material-UI with the

*** UPDATED CODE BASED ON RECOMMENDATIONS *** I am currently in the process of familiarizing myself with material-ui. I have been exploring how to incorporate event handling with material-ui components, specifically by combining an autocomplete feature wit ...

Monitoring user engagement using Socket.io and Firebase

In my Node/Express app, I am working on monitoring active users without using sessions. The app relies on an external API for handling JWT tokens that are directly passed to the client for storing and subsequent API requests. To track active users, I am u ...

Even after trying to hide the legend in a Radar Chart using the configuration option `legend: {display: false}` in chart.js, the legend

Having trouble removing legend from Radar Chart in chart.js even when using legend: {display : false}. The code is being utilized and then displayed with HTML/JS. Here is the provided code snippet: var options5 = { type: 'radar', data: { ...

Route is searching for static files in the incorrect directory

There seems to be a specific route, /admins/:id, that is looking for static files in /public/admins/ instead of /public/. This issue is causing 404 errors and preventing the js and css files from loading on this page. All other routes are correctly fetchin ...

extract data obtained from an AJAX call

I am working on an ajax request in my code: var rootURL = "http://localhost/myapp/api/api.php"; $.ajax({ type: 'GET', url: rootURL + '/favourites', dataType: "json", success: function(list) { }, error: f ...

React-Redux is throwing a TypeError due to its incapability of reading the property 'map' which is undefined

I'm still fairly new to diving into React and Redux, and I find myself a bit puzzled. My main objective is to populate HTML with a plethora of JSON data through GET requests. Utilizing react and redux to control the state of these objects, however, i ...

Map does not provide zero padding for strings, whereas forEach does

Currently working on developing crypto tools, I encountered an issue while attempting to utilize the map function to reduce characters into a string. Strangely enough, one function works perfectly fine, while the other fails to 0 pad the string. What could ...

Concerns arise regarding the preprocessor directive for the ImgUrl attribute of the Image in ASP.NET

I'm looking to extract the ID value from a QueryString and append it to the ImgUrl path using the following code: <asp:Image ID="imgImageNormal" runat="server" ImageUrl='<%# string.Format("ImageHandler.ashx?ID={0}",Request.QueryString["ID" ...

Employ the symbol ""q" within a repetition sequence

When trying to retrieve data from a Mssql server, I encountered an issue with a function that contains a loop. The function returns some data to the callback, and now I need to figure out how to store this data from kriskowal's "q" into the resultset ...