### List Environment Snapshots (JSON Example) Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/backups-api Example JSON output for listing environment snapshots. It includes details like limit, offset, total count, and a list of snapshot objects, each with its own metadata. ```json { "limit": 5, "offset": 0, "total": 32, "snapshots": [ { "snapshot_id": "5deda9e2-f882-4925-830c-45e73c57366e", "model_version": "8.12.7.11687", "comment": "Uploaded snapshot", "expires_at": "2021-08-05T18:38:41.000Z", "state": "completed", "status_message": "Completed extraction", "created_at": "2021-05-05T18:38:41.000Z", "finished_at": "2021-05-05T18:40:12.000Z", "updated_at": "2021-05-05T18:40:12.000Z" }, { "snapshot_id": "bf45ed4d-3308-4fb9-876b-36453ba149bf", "model_version": "8.12.7.11687", "comment": "Automatically created nightly snapshot", "expires_at": "2021-05-18T01:41:27.000Z", "state": "completed", "status_message": "Completed backup creation", "created_at": "2021-05-04T01:41:27.000Z", "finished_at": "2021-05-04T01:45:47.000Z", "updated_at": "2021-05-04T01:45:47.000Z" } ] } ``` -------------------------------- ### Example Widget Configuration Values Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/pluggable-widgets-config-api-10 An example representing the JavaScript object structure of configured values passed to a widget, corresponding to the defined property schema. ```javascript { caption: "My graph", dataCaption: "Points", dataPoints: [ { x: 0, y: 10 }, { x: 1, y: 12 }, { x: 2, y: 5 } ] } ``` -------------------------------- ### Example GET Request for Restore Status Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/backups-api This example demonstrates how to make a GET request to the Mendix API to retrieve the status of a specific data restore operation. It requires ProjectId, EnvironmentId, and RestoreId in the URL, along with authentication headers. ```http GET /api/v2/apps/b5f19af7-7453-465e-b9a1-d7556f524c1e/environments/d436e0cd-6200-4ac5-b858-849a6ddbb56a/restores/11076b79-9df4-45d8-ac4b-dd79617138f5 Host: deploy.mendix.com Content-Type: application/json Mendix-Username: richard.ford51@example.com Mendix-ApiKey: 26587896-1cef-4483-accf-ad304e2673d6 ``` -------------------------------- ### Get Environment Settings - Example Output Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/deploy-api An example JSON output representing the settings of a Mendix application environment, including constants, custom settings, and scheduled events. ```JSON { "Constants" : [{ "Name" : "MyFirstModule.BooleanConstant" , "DataType" : "_Boolean" , "Value" : "false" , "DeployedValue" : "false" },{ "Name" : "MyFirstModule.DateTime" , "DataType" : "DateTime" , "Value" : "2013-12-20T16:02:32" , "DeployedValue" : "2013-12-20T16:02:32" }], "CustomSettings" : [], "ScheduledEvents" : [{ "Name" : "MyFirstModule.Monitor_Scheduled_event" , "DeployedValue" : "Disabled" , "Value" : "Disabled" }] } ``` -------------------------------- ### Example Widget Values Configuration (JavaScript) Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/pluggable-widgets-config-api An example of a JavaScript object representing the configured values for a widget, based on the provided XML structure. This object shows how data points and other properties would be represented when passed to the `getProperties` function. ```javascript { caption: "My graph", dataCaption: "Points", dataPoints: [ { x: 0, y: 10 }, { x: 1, y: 12 }, { x: 2, y: 5 } ] } ``` -------------------------------- ### Set Environment Settings - Example Output Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/deploy-api An example JSON output representing the updated settings of a Mendix application environment after a POST request. ```JSON { "Constants" : [{ "Name" : "MyFirstModule.BooleanConstant" , "DataType" : "_Boolean" , "Value" : "true" , "DeployedValue" : "false" },{ "Name" : "MyFirstModule.DateTime" , "DataType" : "DateTime" , "Value" : "2013-12-20T16:02:32" , "DeployedValue" : "2013-12-20T16:02:32" }], "CustomSettings" : [], "ScheduledEvents" : [{ "Name" : "MyFirstModule.Monitor_Scheduled_event" , "DeployedValue" : "Disabled" , "Value" : "Enabled" }] } ``` -------------------------------- ### Start Environment Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/deploy-api Starts a specific Mendix environment for a given application. This operation can optionally synchronize the database automatically. ```APIDOC ## POST /api/1/apps//environments//start ### Description Starts a specific environment that is connected to a specific app to which the authenticated user has access as a regular user. These environments can be found via the "Nodes overview" screen in the Mendix Platform. ### Method POST ### Endpoint https://deploy.mendix.com/api/1/apps//environments//start ### Parameters #### Path Parameters - **AppId** (String) - Required - The unique identifier of the application. - **Mode** (String) - Required - The mode of the environment (e.g., Test, Acceptance, Production). #### Query Parameters None #### Request Body - **AutoSyncDb** (Boolean) - Optional - Define whether the database should be synchronized automatically with the model during the start phase of the app. ### Request Example ``` POST /api/1/apps/calc/environments/Acceptance/start Host: deploy.mendix.com Content-Type: application/json Mendix-Username: richard.ford51@example.com Mendix-ApiKey: 26587896-1cef-4483-accf-ad304e2673d6 { "AutoSyncDb" : true } ``` ### Response #### Success Response (200) - **JobId** (String) - The identifier that can be used to track the progress of the start action. #### Response Example ```json { "JobId" : "02df2e50-0e79-11e4-9191-0800200c9a66" } ``` #### Error Codes - **200 ALREADY_STARTED**: Cannot start app. App is already running. - **400 INVALID_APPID**: Invalid AppId. - **404 APP_NOT_FOUND**: App not found. - **500 NO_MDA_HAS_BEEN_DEPLOYED**: Cannot start app. There is no MDA deployed. - **500 APP_ALREADY_HAS_A_STARTING_JOB**: Cannot start app. There is already a starting job id found. ``` -------------------------------- ### Example Widget XML for Property Configuration Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/pluggable-widgets-config-api An example of a widget XML snippet demonstrating the structure for defining properties, property groups, and nested object properties. This XML serves as a basis for generating the corresponding JavaScript object configuration. ```xml Graph caption The caption of this graph Data caption The caption of the data set Data points X value Y value ``` -------------------------------- ### Initialize Webview and Handle Messages in C# Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/csharp-extensibility-api-10/build-todo-example-extension Implements the InitWebView method to host a web interface within Studio Pro. It sets the webview address and handles incoming messages for adding, changing status, and clearing to-do items. This method is crucial for enabling two-way communication between the webview and the extension logic. ```csharp public override void InitWebView(IWebView webView) { webView.Address = new Uri(_baseUri, "index"); webView.MessageReceived += (_, args) => { var currentApp = _getCurrentApp(); if (currentApp == null) return; if (args.Message == "AddToDo") { var toDoText = args.Data["toDoText"]?.GetValue() ?? "New To Do"; AddToDo(currentApp, toDoText); webView.PostMessage("RefreshToDos"); } if (args.Message == "ChangeToDoStatus") { var toDoId = args.Data["id"]!.GetValue(); var newIsDone = args.Data["isDone"]!.GetValue(); ChangeToDoStatus(currentApp, toDoId, newIsDone); webView.PostMessage("RefreshToDos"); } if (args.Message == "ClearDone") { ClearDone(currentApp); webView.PostMessage("RefreshToDos"); } }; } ``` -------------------------------- ### Get Start Environment Status Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/deploy-api Retrieves the status of a previously initiated environment start action. ```APIDOC ## GET /api/1/apps//environments//start/ ### Description Retrieve the status of the start environment action. ### Method GET ### Endpoint https://deploy.mendix.com/api/1/apps//environments//start/ ### Parameters #### Path Parameters - **AppId** (String) - Required - The unique identifier of the application. - **Mode** (String) - Required - The mode of the environment (e.g., Test, Acceptance, Production). - **JobId** (String) - Required - The identifier of the start job to track. #### Query Parameters None #### Request Body None ### Request Example ``` GET /api/1/apps/calc/environments/Acceptance/start/02df2e50-0e79-11e4-9191-0800200c9a66 Host: deploy.mendix.com Content-Type: application/json Mendix-Username: richard.ford51@example.com Mendix-ApiKey: 26587896-1cef-4483-accf-ad304e2673d6 ``` ### Response #### Success Response (200) - **Status** (String) - Possible values are Starting and Started. #### Response Example ```json { "Status" : "Starting" } ``` #### Error Codes - **400 INVALID_PARAMETERS**: Not enough parameters given. Please set AppId and Mode parameters. - **400 INVALID_ENVIRONMENT**: Could not parse environment mode 'mode'. Valid options are Test, Acceptance, Production or the name of a flexible environment. - **404 ENVIRONMENT_NOT_FOUND**: Environment not found. - **404 NO_SUCH_STARTJOB**: Job not found. - **500 NO_PACKAGE**: Cannot start app. There should be a package configured for this environment. - **500 ALREADY_LOCKED**: Cannot start app. There is already a lock on this environment. - **500 ALREADY_STARTED**: Cannot start app. App is already running. - **500 DB_SYNC_FAILED**: Cannot start app. Synchronization of database failed. - **500 INVALID_DB_STRUCTURE**: Cannot start app. The database is out-of-sync with the model. Please set AutoSyncDb parameter to true to synchronize the database automatically on startup. - **500 MISSING_CONSTANT**: Cannot start app. Missing one or more constant values. - **500 INSECURE_ADMIN_PASSWORD**: Cannot start app. There is a user with administrator role with password '1'. This is not allowed. - **500 STARTUP_ACTION_FAILED**: Cannot start app. Startup action failed. - **500 START_FAILED**: Cannot start app: result (detail status). ``` -------------------------------- ### Implement Constructor Injection and Pane Lifecycle Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/csharp-extensibility-api-11/build-todo-example-extension Shows the use of ImportingConstructor for dependency injection and overriding the Id property and Open method to integrate with the Studio Pro lifecycle. ```csharp [ImportingConstructor] public ToDoListDockablePaneExtension(ILogService logService) { _logService = logService; } public override string Id => PaneId; public override DockablePaneViewModelBase Open() { return new ToDoListDockablePaneViewModel(WebServerBaseUrl, () => CurrentApp, _logService) { Title = "To Do List" }; } ``` -------------------------------- ### Get All User Accounts Response (JSON) Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/user-management-api Example JSON response for 'Get All User Accounts in Your Company', showing the total user count and a list of user OpenIDs. ```JSON { "users": [ { "openId": "https://mxid2.mendix.dev/mxid2/id?id=daba46fc-692c-4622-adb4-981fcfb0dec9" }, { "openId": "https://mxid2.mendix.dev/mxid2/id?id=c8101ad7-bdfb-48b1-b212-99fa86f8cdb0" }, { "openId": "https://mxid2.mendix.dev/mxid2/id?id=f3ecda3f-1cd4-4571-92d9-5c53bd80c542" }, { "openId": "https://mxid2.mendix.dev/mxid2/id?id=344a8193-bbe0-4b31-b7ae-de701eccf030" }, { "openId": "https://mxid2.mendix.dev/mxid2/id?id=51b54074-a66c-4337-8488-aac89bf47a2d" }, { "openId": "https://mxid2.mendix.dev/mxid2/id?id=6043d3ed-517f-43fc-bfb5-1062afe24858" } ], "count": 6 } ``` -------------------------------- ### Configure Build and Manifest Files Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/web-extensibility-api-11/message-passing-api Updates the build configuration to include multiple entry points and updates the manifest to map these entry points to the extension's UI components. ```javascript const entryPoints = [ { in: 'src/main/index.ts', out: 'main' } ] entryPoints.push({ in: 'src/ui/tab.tsx', out: 'tab' }) entryPoints.push({ in: 'src/ui/pane.tsx', out: 'pane' }) ``` ```json { "mendixComponent": { "entryPoints": { "main": "main.js", "ui": { "tab": "tab.js", "pane": "pane.js" } } } } ``` -------------------------------- ### Get User OpenID by Email Response (JSON) Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/user-management-api Example JSON response for the 'Get OpenID of User Account' API call, containing the OpenID of the requested user. ```JSON { "openId": "https://mxid2.mendixcloud.com/mxid2/id?id=bdddd12c-cc93-4600-82e4-88baa5314y79" } ``` -------------------------------- ### Create Menu Extension for Studio Pro in C# Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/csharp-extensibility-api-10/build-todo-example-extension Registers a new menu item in the Studio Pro toolbar to launch the To-Do list extension. It uses the MEF Export attribute and IDockingWindowService to trigger the display of the extension pane. ```csharp using System.Collections.Generic; using System.ComponentModel.Composition; using Mendix.StudioPro.ExtensionsAPI.UI.DockablePane; using Mendix.StudioPro.ExtensionsAPI.UI.Menu; using Mendix.StudioPro.ExtensionsAPI.UI.Services; namespace Mendix.ToDoExtension; [Export(typeof(Mendix.StudioPro.ExtensionsAPI.UI.Menu.MenuExtension))] public class ToDoListMenuBarExtension : MenuExtension { private readonly IDockingWindowService _dockingWindowService; [ImportingConstructor] public ToDoListMenuBarExtension(IDockingWindowService dockingWindowService) { _dockingWindowService = dockingWindowService; } public override IEnumerable GetMenus() { yield return new MenuViewModel("To Do List", () => _dockingWindowService.OpenPane(ToDoListDockablePaneExtension.PaneId)); } } ``` -------------------------------- ### Implement Client-Side Logic and Message Handling Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/csharp-extensibility-api-10/build-todo-example-extension This JavaScript file manages the To-Do list state and handles communication with the host application using the window.chrome.webview API. ```javascript function postMessage(message, data) { window.chrome.webview.postMessage({ message, data }); } window.chrome.webview.addEventListener("message", handleMessage); postMessage("MessageListenerRegistered"); async function handleMessage(event) { const { message, data } = event.data; if (message === "RefreshToDos") { await refreshToDos(); } } async function refreshToDos() { let todosResponse = await fetch("./todos"); let todos = await todosResponse.json(); let todoDiv = document.getElementById("todo"); let doneDiv = document.getElementById("done"); let todoItems = []; let doneItems = []; for (const todo of todos.ToDos) { let item = document.createElement("div"); let checkbox = document.createElement("input"); checkbox.type = "checkbox"; checkbox.id = `todo-${todo.Id}`; checkbox.checked = todo.IsDone; checkbox.addEventListener("click", () => { postMessage("ChangeToDoStatus", { id: todo.Id, isDone: !todo.IsDone }); }); let label = document.createElement("label"); label.htmlFor = checkbox.id; label.innerText = todo.Text; item.replaceChildren(checkbox, label); if (todo.IsDone) { doneItems.push(item); } else { todoItems.push(item); } } todoDiv.replaceChildren(...todoItems); doneDiv.replaceChildren(...doneItems); } async function addToDo(){ let addToDoInput = document.getElementById("addToDoInput"); const toDoText = addToDoInput.value; postMessage("AddToDo", { toDoText }); addToDoInput.value = ""; } document.getElementById("addToDoButton").addEventListener("click", addToDo); document.getElementById("clearDoneButton").addEventListener("click", () => { postMessage("ClearDone"); }); await refreshToDos(); ``` -------------------------------- ### Get Start Environment Status Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/deploy-api Retrieves the current status of a previously triggered environment startup job. Uses the JobId returned from the start request to poll for completion. ```HTTP GET /api/1/apps/calc/environments/Acceptance/start/02df2e50-0e79-11e4-9191-0800200c9a66 Host: deploy.mendix.com Content-Type: application/json Mendix-Username: richard.ford51@example.com Mendix-ApiKey: 26587896-1cef-4483-accf-ad304e2673d6 ``` -------------------------------- ### Retrieve Repository Commits via HTTP GET Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/app-repository-api Examples of making an authenticated GET request to the Mendix Repository API to retrieve commit history. The requests demonstrate usage of URL-encoded branch names and pagination parameters. ```HTTP GET /v1/repositories/c0af1725-edae-4345-aea7-2f94f7760e33/branches/trunk/commits?limit=20&cursor=Rmlyc3RQYWdlQ3Vyc29y HTTP/1.1 Host: repository.api.mendix.com Accept: */* Authorization: MxToken hZUPhAV4ELPrRm7U7JAKf5BnxJk6q7dcsvFdw6ZR4wRYdv7egHjwHEYBwXY4RkSZrAWde3XqVAQkxZNPysvHcpquA9sK9bsKmcTN ``` ```HTTP GET /v1/repositories/c0af1725-edae-4345-aea7-2f94f7760e33/branches/branches%2Fdevelopment/commits?limit=20&cursor=Rmlyc3RQYWdlQ3Vyc29y HTTP/1.1 Host: repository.api.mendix.com Accept: */* Authorization: MxToken hZUPhAV4ELPrRm7U7JAKf5BnxJk6q7dcsvFdw6ZR4wRYdv7egHjwHEYBwXY4RkSZrAWde3XqVAQkxZNPysvHcpquA9sK9bsKmcTN ``` -------------------------------- ### Implement Container Preview Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/pluggable-widgets-config-api-9 Demonstrates the implementation of a Container component using the getPreview function. This example shows how to group multiple Text components vertically with a border. ```typescript export const getPreview = (_values: WidgetPreviewProps, _isDarkMode: boolean, _version: number[]) => ( { type: "Container", borders: true, children: [ { type: "Text", content: "I am on top" }, { type: "Text", content: "I am on the bottom" } ] }); ``` -------------------------------- ### GET /api/1/apps//environments//access-logs/ Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/deploy-api Downloads a log of all the end-users who have started a session in the app on the selected date. ```APIDOC ## GET /api/1/apps//environments//access-logs/ ### Description Downloads a log of all the end-users who have started a session in the app on the selected date. ### Method GET ### Endpoint https://deploy.mendix.com/api/1/apps//environments//access-logs/ ### Parameters #### Path Parameters - **AppId** (String) - Required - Subdomain name of an app. - **Mode** (String) - Required - Mode of the environment (Test, Acceptance, Production, or flexible environment name). - **Date** (String) - Required - Date of the desired log in the format YYYY-MM-DD. ### Request Example GET /api/1/apps/calc/environments/acceptance/access-logs/2021-06-12 Host: deploy.mendix.com Content-Type: application/json Mendix-Username: richard.ford51@example.com Mendix-ApiKey: 26587896-1cef-4483-accf-ad304e2673d6 ### Response #### Success Response (200) - **Environment** (String) - The unique ID of the environment. - **Date** (Number) - Timestamp of the log entry. - **DownloadUrl** (String) - The URL to download the log file. #### Response Example { "Environment": "38471410-861f-47e5-8efc-2f4b16f04005", "Date": 1536451200000, "DownloadUrl": "https://logsapi-prod-2-eu-central-1.mendix.com/v1/rtr-logs/38471410-861f-47e5-8efc-2f4b16f04005/2021-06-12?expire=20210616105139&signature=..." } #### Error Handling - **404 NOT FOUND**: An App or Environment is not found. - **403 FORBIDDEN**: You do not have access. ``` -------------------------------- ### Define ToggleButtonGroup with CSS Classes Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/design-properties Example configuration for a ToggleButtonGroup using CSS classes for styling. This setup defines three options (left, center, right) mapped to specific CSS class names. ```JSON { "name": "Text align", "type": "ToggleButtonGroup", "description": "Description of Text align Property", "options": [ { "name": "left", "class": "textAlignLeft" }, { "name": "center", "class": "textAlignCenter" }, { "name": "right", "class": "textAlignRight" } ] } ``` -------------------------------- ### Implement Constructor Injection Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/csharp-extensibility-api-10/build-todo-example-extension Apply the ImportingConstructor attribute to the class constructor to enable dependency injection. This allows the injection of services like ILogService during instantiation. ```csharp [ImportingConstructor] public ToDoListDockablePaneExtension(ILogService logService) { _logService = logService; } ``` -------------------------------- ### Define Extension Manifest Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/csharp-extensibility-api-11/get-started The manifest.json file is required for Studio Pro to recognize and load an extension. It must contain the 'mx_extensions' property, which lists the entry point DLL files for the extension. ```json { "mx_extensions": [ "MyExtension.dll" ] } ``` -------------------------------- ### Define Dockable Pane Extension with MEF Attributes Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/csharp-extensibility-api-11/build-todo-example-extension Demonstrates how to register a class as a dockable pane extension using the Export attribute and define the class structure by inheriting from DockablePaneExtension. ```csharp [Export(typeof(DockablePaneExtension))] public class ToDoListDockablePaneExtension : DockablePaneExtension { // Implementation details } ``` -------------------------------- ### Get Entity from Domain Model (TypeScript) Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/web-extensibility-api-10/model-api This example shows how to retrieve a specific entity from a loaded domain model unit using the `getEntity` helper method. This assumes the `domainModel` has already been loaded. ```typescript const entity: DomainModels.Entity = domainModel.getEntity("MyEntity"); ``` -------------------------------- ### Web Server Extension Implementation (C#) Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/csharp-extensibility-api-10/build-todo-example-extension Implements a WebServerExtension to serve web content within Mendix Studio Pro. It defines routes for index.html, main.js, and a todos endpoint, handling requests and responses. ```csharp using System.ComponentModel.Composition; using System.Net; using System.Text.Json; using Mendix.StudioPro.ExtensionsAPI.Services; using Mendix.StudioPro.ExtensionsAPI.UI.WebServer; namespace Mendix.ToDoExtension; [Export(typeof(WebServerExtension))] public class ToDoListWebServerExtension : WebServerExtension { private readonly IExtensionFileService _extensionFileService; private readonly ILogService _logService; [ImportingConstructor] public ToDoListWebServerExtension(IExtensionFileService extensionFileService, ILogService logService) { _extensionFileService = extensionFileService; _logService = logService; } public override void InitializeWebServer(IWebServer webServer) { webServer.AddRoute("index", ServeIndex); webServer.AddRoute("main.js", ServeMainJs); webServer.AddRoute("todos", ServeToDos); } private async Task ServeIndex(HttpListenerRequest request, HttpListenerResponse response, CancellationToken ct) { var indexFilePath = _extensionFileService.ResolvePath("wwwroot", "index.html"); await response.SendFileAndClose("text/html", indexFilePath, ct); } private async Task ServeMainJs(HttpListenerRequest request, HttpListenerResponse response, CancellationToken ct) { var indexFilePath = _extensionFileService.ResolvePath("wwwroot", "main.js"); await response.SendFileAndClose("text/javascript", indexFilePath, ct); } private async Task ServeToDos(HttpListenerRequest request, HttpListenerResponse response, CancellationToken ct) { if (CurrentApp == null) { response.SendNoBodyAndClose(404); return; } var toDoList = new ToDoStorage(CurrentApp, _logService).LoadToDoList(); var jsonStream = new MemoryStream(); await JsonSerializer.SerializeAsync(jsonStream, toDoList, cancellationToken: ct); response.SendJsonAndClose(jsonStream); } } ``` -------------------------------- ### Implement Widget Preview Function Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/pluggable-widgets-config-api Provides an example of the getPreview function, which returns a preview configuration object including an SVG image for rendering in Studio Pro. ```typescript export const getPreview = (_values: WidgetPreviewProps, _isDarkMode: boolean, _version: number[]) => { const mySvgImage = ` `; return { type: "Image", document: mySvgImage, width: 200 } }; ``` -------------------------------- ### Retrieve Environments for an App (HTTP Request) Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/deploy-api This example shows an HTTP GET request to fetch all environments associated with a specific Mendix app. The request includes the AppId in the URL and requires authentication headers. ```http GET /api/1/apps/calc/environments Host: deploy.mendix.com Content-Type: application/json Mendix-Username: richard.ford51@example.com Mendix-ApiKey: 26587896-1cef-4483-accf-ad304e2673d6 ``` -------------------------------- ### Retrieve App Details (HTTP Request) Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/deploy-api This example demonstrates an HTTP GET request to retrieve details of a specific Mendix app using its AppId. It requires the Host, Content-Type, Mendix-Username, and Mendix-ApiKey headers. ```http GET /api/1/apps/calc Host: deploy.mendix.com Content-Type: application/json Mendix-Username: richard.ford51@example.com Mendix-ApiKey: 26587896-1cef-4483-accf-ad304e2673d6 ``` -------------------------------- ### Define Web UI Layout with HTML and Tailwind CSS Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/csharp-extensibility-api-10/build-todo-example-extension This HTML template sets up the To-Do list interface. It includes Tailwind CSS for styling and references the main.js module for application logic. ```html To Do List

To Do

Done

``` -------------------------------- ### Define Dockable Pane Extension Class Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/csharp-extensibility-api-10/build-todo-example-extension Use the Export attribute to register the class as a DockablePaneExtension. This allows Studio Pro to identify and load the extension correctly. ```csharp [Export(typeof(DockablePaneExtension))] public class ToDoListDockablePaneExtension : DockablePaneExtension {} ``` -------------------------------- ### Invert Condition with 'not' Helper (JavaScript) Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/pluggable-widgets-client-apis-list-values-10 The 'not' helper inverts a given condition. It accepts a single argument, which is the condition to be inverted. This example demonstrates inverting a 'startsWith' condition to ensure an attribute does not start with a specific character. ```javascript const filterCondition = not( startsWith(attribute(this.props.myAttributeA.id), literal("X")), ); ``` -------------------------------- ### Retrieve Specific Environment (HTTP Request) Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/deploy-api This example illustrates an HTTP GET request to retrieve details of a specific environment within a Mendix app. The request requires both the AppId and the environment's Mode in the URL, along with authentication headers. ```http GET /api/1/apps/calc/environments/Acceptance Host: deploy.mendix.com Content-Type: application/json Mendix-Username: richard.ford51@example.com Mendix-ApiKey: 26587896-1cef-4483-accf-ad304e2673d6 ``` -------------------------------- ### Utility Class for HTTP Listener Responses (C#) Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/csharp-extensibility-api-10/build-todo-example-extension Provides utility methods for sending files, JSON, and no-body responses with default headers using HttpListenerResponse. It simplifies common HTTP response tasks for web extensions. ```csharp using System.Net; using System.Text; namespace Mendix.ToDoExtension; public static class HttpListenerResponseUtils { public static async Task SendFileAndClose(this HttpListenerResponse response, string contentType, string filePath, CancellationToken ct) { response.AddDefaultHeaders(200); var fileContents = await File.ReadAllBytesAsync(filePath, ct); response.ContentType = contentType; response.ContentLength64 = fileContents.Length; await response.OutputStream.WriteAsync(fileContents, ct); response.Close(); } public static void SendJsonAndClose(this HttpListenerResponse response, MemoryStream jsonStream) { response.AddDefaultHeaders(200); response.ContentType = "application/json"; response.ContentEncoding = Encoding.UTF8; response.ContentLength64 = jsonStream.Length; jsonStream.WriteTo(response.OutputStream); response.Close(); } public static void SendNoBodyAndClose(this HttpListenerResponse response, int statusCode) { response.AddDefaultHeaders(statusCode); response.Close(); } static void AddDefaultHeaders(this HttpListenerResponse response, int statusCode) { response.StatusCode = statusCode; // Makes sure the web-code can receive responses response.AddHeader("Access-Control-Allow-Origin", "*"); } } ``` -------------------------------- ### Migrate Command Registration to direct action Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/web-extensibility-api-11/migration-guide Shows how to migrate from the removed command registration API to the direct action property in the Menu API. This removes the need for pre-registering commands globally. ```JavaScript // Deprecated approach const commandId = "myextension.menu-command"; await studioPro.app.commands.registerCommand( commandId, async () => await studioPro.ui.messageBoxes.show("info", "My Menu was Clicked!") ); await studioPro.ui.extensionsMenu.add({ caption: "My Menu", menuId: "myextension.menu", commandId }); ``` ```JavaScript // New approach await studioPro.ui.extensionsMenu.add({ menuId: "myextension.menu", caption: "My Menu", action: async () => await studioPro.ui.messageBoxes.show("info", "My Menu was Clicked!") }); ``` -------------------------------- ### Render Widgets with ListValue Items Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/pluggable-widgets-client-apis-list-values-9 Demonstrates how to render child widgets for each item in a ListValue using the ListWidgetValue's get method. This allows dynamic rendering of UI elements based on data source items. The example maps over the items and calls the widget getter for each. ```typescript this.props.myDataSource.items.map(i => this.props.myWidgets.get(i)); ``` -------------------------------- ### Add Menu Item and Handle Activation in Mendix Studio Pro Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/web-extensibility-api-10/getting-started Registers a custom menu item in the Studio Pro interface and defines an event listener to open a specific tab when the menu item is clicked. This requires the Mendix Web Extensibility API and is implemented in TypeScript. ```TypeScript await studioPro.ui.extensionsMenu.add({ menuId: "myextension.MainMenu", caption: "MyExtension Menu", subMenus: [{ menuId: "myextension.ShowTabMenuItem", caption: "Show tab" }], }); // Open a tab when the menu item is clicked studioPro.ui.extensionsMenu.addEventListener("menuItemActivated", (args) => { if (args.menuId === "myextension.ShowTabMenuItem") { studioPro.ui.tabs.open( { title: "My Extension Tab", }, { componentName: "extension/myextension", uiEntrypoint: "tab", } ); } }); ``` -------------------------------- ### Implement To-Do Storage Handler in C# Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/csharp-extensibility-api-10/build-todo-example-extension Creates a storage handler class to manage reading and writing to-do items to a local JSON file. It integrates with Mendix Studio Pro's IModel and ILogService to handle file paths and error logging. ```csharp using System.Text; using System.Text.Json; using Mendix.StudioPro.ExtensionsAPI.Model; using Mendix.StudioPro.ExtensionsAPI.Services; namespace Mendix.ToDoExtension; public class ToDoStorage { private readonly ILogService _logService; private readonly string _toDoFilePath; public ToDoStorage(IModel currentApp, ILogService logService) { _logService = logService; _toDoFilePath = Path.Join(currentApp.Root.DirectoryPath, "to-do-list.json"); } public ToDoListModel LoadToDoList() { ToDoListModel? toDoList = null; try { toDoList = JsonSerializer.Deserialize(File.ReadAllText(_toDoFilePath, Encoding.UTF8)); } catch (Exception exception) { _logService.Error($"Error while loading To Dos from {_toDoFilePath}", exception); } return toDoList ?? new ToDoListModel(new[] { new ToDoModel("Buy milk", false), new ToDoModel("Fix house", false), new ToDoModel("Shave yak", true) }.ToList()); } public void SaveToDoList(ToDoListModel toDoList) { var jsonText = JsonSerializer.Serialize(toDoList, new JsonSerializerOptions() { WriteIndented = true }); File.WriteAllText(_toDoFilePath, jsonText, Encoding.UTF8); } } ``` -------------------------------- ### Define View Model Constructor Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/csharp-extensibility-api-10/build-todo-example-extension The constructor for the view model requires specific services to handle the web interface, application state, and logging. This class is instantiated manually by the extension, allowing for custom dependency injection. ```csharp public ToDoListDockablePaneViewModel(Uri baseUri, Func getCurrentApp, ILogService logService) { _baseUri = baseUri; _getCurrentApp = getCurrentApp; _logService = logService; } ``` -------------------------------- ### Display Version Control Info in Studio Pro Menu (TypeScript) Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/web-extensibility-api-11/version-control-api This TypeScript code snippet demonstrates how to create a menu item in Mendix Studio Pro that, when clicked, fetches and displays version control information (system type, branch, last commit details) in a message box. It utilizes the Mendix Extensibility API for UI and version control interactions. Ensure you have completed the 'Get Started with the Web Extensibility API' how-to before implementing. ```typescript import { IComponent, getStudioProApi } from "@mendix/extensions-api"; export const component: IComponent = { async loaded(componentContext) { const studioPro = getStudioProApi(componentContext); const versionControlApi = studioPro.ui.versionControl; const messageBoxApi = studioPro.ui.messageBoxes; const menuId = "version-control-menu"; await studioPro.ui.extensionsMenu.add({ menuId, caption: "Current version control system", action: async () => { const versionControlSystemInfo = await versionControlApi.getVersionControlInfo(); if (versionControlSystemInfo == null) { messageBoxApi.show("info", "This app is not version controlled"); return; } let message = `The system is ${versionControlSystemInfo.versionControlSystem}. Branch: ${versionControlSystemInfo.branch}.`; if (versionControlSystemInfo.lastCommit == null) { message += "\n\nLast Commit: No commit information available."; } else { message += "\n\nLast Commit:\n"; message += `SHA: ${versionControlSystemInfo.lastCommit.sha}\n`; message += `Author: ${versionControlSystemInfo.lastCommit.author}\n`; message += `Message: ${versionControlSystemInfo.lastCommit.message}\n`; message += `Date: ${versionControlSystemInfo.lastCommit.date}`; } await messageBoxApi.show("info", message); } }); } }; ``` -------------------------------- ### Override Pane Identification and View Initialization Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/csharp-extensibility-api-10/build-todo-example-extension Override the Id property to provide a unique identifier and the Open method to return a DockablePaneViewModelBase instance for rendering the pane content. ```csharp public override string Id => PaneId; public override DockablePaneViewModelBase Open() { return new ToDoListDockablePaneViewModel(WebServerBaseUrl, () => CurrentApp, _logService) { Title = "To Do List" }; } ``` -------------------------------- ### Configure Extension Build Directory (JavaScript) Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/web-extensibility-api-11/getting-started This snippet from `build-extension.mjs` specifies the target directory for installing the extension after it is built. The `appDir` variable should be set to the desired path on your local system. ```javascript const appDir = "C:\\TestApps\\AppTestExtensions" ``` -------------------------------- ### Implement DockablePaneExtension in C# Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/csharp-extensibility-api-10/build-todo-example-extension Defines a custom dockable pane for the Mendix Studio Pro IDE. It uses MEF (Managed Extensibility Framework) to export the extension and provides a ViewModel for the UI. ```csharp using System.ComponentModel.Composition; using Mendix.StudioPro.ExtensionsAPI.Services; using Mendix.StudioPro.ExtensionsAPI.UI.DockablePane; namespace Mendix.ToDoExtension; [Export(typeof(DockablePaneExtension))] public class ToDoListDockablePaneExtension : DockablePaneExtension { private readonly ILogService _logService; public const string PaneId = "ToDoList"; [ImportingConstructor] public ToDoListDockablePaneExtension(ILogService logService) { _logService = logService; } public override string Id => PaneId; public override DockablePaneViewModelBase Open() { return new ToDoListDockablePaneViewModel(WebServerBaseUrl, () => CurrentApp, _logService) { Title = "To Do List" }; } } ``` -------------------------------- ### Colorpicker Design Property Example (CSS Variables) Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/design-properties Shows a Mendix Colorpicker design property configured to use CSS variables. This example includes the 'property' field and 'options', where each option has a 'name' and a 'variable' for color application. ```json { "name": "Background color", "type": "ColorPicker", "property": "background-color", "description": "Description of Background Color Property", "options": [ { "name": "Red", "variable": "--color-red" }, { "name": "Green", "variable": "--color-green" }, { "name": "Blue", "variable": "--color-blue" } ] } ``` -------------------------------- ### Create Environment Snapshot Response (JSON) Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/backups-api Example JSON output when requesting the creation of an environment snapshot. It contains the snapshot ID, status message, and timestamps for creation, update, and completion. ```json { "status_message":null, "model_version":null, "expires_at":"2020-05-18T16:00:18.000Z", "finished_at":null, "updated_at":null, "snapshot_id":"51dc7872-771e-4c3e-853b-352359444db6", "created_at":"2020-02-18T16:00:18.000Z", "comment":"My snapshot", "state":"queued" } ``` -------------------------------- ### Dropdown Design Property Example (CSS Variables) Source: https://docs.mendix.com/apidocs-mxsdk/apidocs/design-properties Illustrates a Mendix Dropdown design property that utilizes CSS variables. This example shows the 'property' field along with 'options', where each option defines a 'name' and a 'variable' to be applied. ```json { "name": "Font size", "type": "Dropdown", "property": "font-size", "description": "Description of My Dropdown Design Property", "options": [ { "name": "Small", "variable": "--font-size-small" }, { "name": "Medium", "variable": "--font-size-medium" }, { "name": "Large", "variable": "--font-size-large" } ] } ```