What is the method for executing a custom command within the scope of a tree view item?

I am trying to implement a custom "ping" function in my VS Code Extension that will send the details of a selected treeview object. Despite looking at various examples, I have been unable to properly build and register the command. Although I can invoke the command, I am struggling to retrieve the information of the selected item.

    let InfrastructureInfo = vscode.commands.registerCommand(
        'infrastructure.info',
        async (resource) => {
            vscode.window.showInformationMessage('Ping Host Infrastructure. ....');
            let strMessage: string = PingAgent(resource);
            MessageUtils.showInfoMessage(strMessage);
        }
    );
    context.subscriptions.push(ctmInfrastructureInfo);

The function is being called, but how can I access the object's details? Please refer to the screenshot below for more clarity.

Kind regards,

Answer №1

Utilizing the unique tree node ID sent by the call, my custom command interacts with the JSON data saved in the global extension storage to retrieve necessary information and locate the corresponding node. Additional details required for the command are also extracted from the JSON.

While there may be alternative methods, this is the approach I have implemented successfully:

export function pingAgent(node: vscode.TreeItem, context: vscode.ExtensionContext) {

    if (processNumber < 9999) {
        processNumber++;
    }
    else {
        processNumber = 1;
    }
    let procNumString: string = strPrefix + processNumber.toString().padStart(4, "0");
    let strMessage: string = "";
    let responseMessage: string | undefined;
    let responseMessageError: string | undefined;
    let responseMessageBase: string | undefined;

    let ctmInfrastructureCache: string = context.globalState.get('ctmInfrastructureCache');
    let tree: json.Node = json.parseTree(ctmInfrastructureCache);
    let nodeKey: string | undefined = "";

    // this is the node # within the TreeView 
    let offsetTemp: number = Number(node.toString());
    // this is the node # with additional information, relative to the initial node #
    let offset: number = Number(offsetTemp) + 10;

    // Get parent
    const pathTemp = json.getLocation(ctmInfrastructureCache, offsetTemp).path;
    const valueNodeTemp = json.findNodeAtLocation(tree, pathTemp);
    let ctmResourceType = getResourceType(valueNodeTemp);

    // Get CTM node name
    const path = json.getLocation(ctmInfrastructureCache, offset).path;
    const valueNode = json.findNodeAtLocation(tree, path);
    const nodeid = valueNode.value.toString();

    if (ctmResourceType === "ctm.agent") {
        let ctmDatacenterName = getDatacenterName(valueNodeTemp);

        try {
            nodeKey = valueNode.parent.children[0].value;
        } catch (error) {
            nodeKey = null;
        }

        strMessage = "Awaiting Agent Status of: '" + nodeid + "' managed by: " + ctmDatacenterName;
        OutputUtils.getOutputChannel().appendLine(procNumString + ' Message  : ' + strMessage);

        let jsonStrA = CtmTools.cmdPingAgent(ctmDatacenterName, nodeid);
        let jsonStrB = json.parse(jsonStrA.replace(/\n/g, ''));


        try {
            responseMessageBase = jsonStrB["message"].toString();
            // eslint-disable-next-line no-empty
        } catch { }

        try {
            responseMessageError = jsonStrB["errors"][0]["message"];
            // eslint-disable-next-line no-empty
        } catch { }

        if (responseMessageBase) {
            responseMessage = responseMessageBase;
        } else if (responseMessageError) {
            responseMessage = responseMessageError;
        }

        let reStrA = "unavailable";
        let reStrB = "available";
        let reStrC = "Failed";

        if (responseMessage.includes(reStrA)) {
            strMessage = 'Status : ' + responseMessage;
            MessageUtils.showWarningMessage(strMessage);
        } else if (responseMessage.includes(reStrB)) {
            strMessage = 'Status : ' + responseMessage;
            MessageUtils.showInfoMessage(strMessage);
        } else if (responseMessage.includes(reStrC)) {
            strMessage = 'Status : ' + responseMessage;
            MessageUtils.showErrorMessage(strMessage);
        } else {
            strMessage = 'Status : ' + responseMessage;
            MessageUtils.showWarningMessage(strMessage);
        }

        OutputUtils.getOutputChannel().appendLine(procNumString + ' Message  : ' + responseMessage);

    }
}

Warm regards

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

When initialized within an object, Angular may identify a field as undefined

Whenever I attempt to access a property of the object named "User," it shows up as undefined. However, upon logging the complete object to the console, the field appears with the necessary data. Here is the console log output: perfil.component.ts:42 unde ...

"Exploring the relationship between Typescript and Angular: transforming variables within different

Ever since I made the switch from JavaScript to TypeScript (Version 2.1.5), I have been facing an issue with the code that filters date selection. Despite my efforts, I haven't been able to find a good fix for it yet. Here are the two date-pickers: F ...

How can I use JavaScript to update the content inside HTML tags with a specific string?

I have a situation where I need to replace a string in two different ways Input: Parameters-->string, AnnotationName, input Case 1: And I should input <i>Annotaion</i> as <b>input</b> Output : { displayData: `And I should inp ...

The ESLINT_NO_DEV_ERRORS flag appears to be ineffective in my Typescript project

Currently, my project involves using the following tools: Yarn Typescript Create React App ESLint Make (Makefile) Fish shell During development, I encounter ESLint errors that prevent my project from compiling. To run my project, I use make run, which es ...

Looking to extract the expiration date from an x509 certificate?

I am currently engaged in a project that involves retrieving and displaying certificate information from an Azure integration account using Angular/Typescript. One of the requirements is to show the decoded public certificate to users to extract important ...

Having trouble with implementing Spotify OAuth in NextJS?

I am in the process of creating a music website portfolio using Spotify and NextJS. I want to incorporate music playback on the website, but I am encountering issues with Spotify authentication. When I click the login button, I receive a 405 HTTP status er ...

Issue with React/Next.js input field rejecting commas

I'm experiencing a problem with an input field in my React application that was developed using Next.js. The issue arises specifically when using an iPad device, where the input field behaves inconsistently when dealing with commas. When using deskto ...

Exploring the power of Javascript for number lookup

I am currently working on a coding project using TypeScript and JavaScript to locate a specific number provided by the user within a list. The goal is to display whether or not the number is present in the list when the 'search' button is pressed ...

Opening a modal in Angular2+ when selecting an item from ngx-chips (tag-input)

I need to implement a functionality where clicking on a tag in a dropdown should trigger the opening of a modal window in my Angular application. Below is the code snippet related to this feature: <div class="force-to-the-bottom"> <tag-input [ ...

It appears that tsc is failing to recognize the "exclude" directives specified in the tsconfig.json file

I'm having difficulty with tsc recognizing my tsconfig.json file and compiling my .ts files. I keep encountering duplication errors that I'm trying to prevent using my tsconfig.json. Here's what I have: package.json tsconfig.json typings.j ...

rxjs in Angular2 is missing the observable.interval function

Currently, I am attempting to utilize the interval method of an observable; however, I consistently encounter the following error message: Property 'interval' does not exist on type 'Observable<any>'. I have included the follow ...

Modify the color of Material UI's Select Component's IconComponent

Currently in my project, I am utilizing MUI's Select Component with the LanguageIcon as the designated IconComponent. My goal is to change the color of this icon from black (default) to white, but I have been unsuccessful in my attempts. I attempte ...

Sharing information between components in Angular 4 and .NET Core applications

I am new to Angular and .NET Core. I have successfully created a web api using .NET Core, which is called from an Angular 4 application. Currently, everything is working smoothly. However, after submitting a form that inserts records into the database, I w ...

The value of "metadata" is not a valid export entry for Next.js

After I installed Next.js 14 with TypeScript, I encountered an error related to my metadata type definition. import type { Metadata } from "next"; export const metadata: Metadata = { title: "next app", description: "next app 1 ...

Using a static class reference as a parameter in a generic type leads to a error

Before I submit a ticket on github, I want to double-check that I'm not making any mistakes. The issue should be clear enough: class A {} class B { static A = A; } function foo<T>(arg: T) {} // this is valid const b = new B.A; // "B" only ...

How about utilizing React's conditional rendering feature?

I'm currently working on a component that displays tournaments and matches, and I'm facing a challenge in implementing a filter option for users to select tournaments by 'league', while still displaying all tournaments if no 'leagu ...

The Angular Node server is responding with the error message "You have entered 'undefined' instead of a stream."

Using angular 9 + universal has been smooth sailing until I encountered an issue after building the app with npm run build:ssr and attempting to run it using node: node dist/app/server/main.js. The error message that popped up in the terminal was: Node ...

Encountering issues with Socket.io: consistently experiencing websocket connection failures along with persistent 404 errors on the

I am facing issues with setting up a websocket using socket.io. The server-side seems to be making a GET call successfully, but on the client-side, I am getting a 404 error: GET http://localhost:6543/socket.io/?uuid=258c4ab9-b263-47ca-ab64-83fe99ea03d4& ...

What are the steps to set up a dictionary with predetermined values?

My task is to create a pre-defined dictionary where the key represents a city and the value is an array of zones in that city. Here is my attempt: export const cityToZone: { [city: string]: Array<string> } = [ {city:'New York', [&apos ...

Setting up data in Firebase can be challenging due to its complex structure definition

https://i.stack.imgur.com/iclx7.png UPDATE: In my firebase structure, I have made edits to the users collection by adding a special list called ListaFavorite. This list will contain all the favorite items that users add during their session. The issue I a ...