Our blog contains the activity stream of Orchard Dojo: general news, new resources or tutorials are announced here.

Add Recipe Roles permission behavior, how to add media management to an ASP.NET Core app? - This week in Orchard (24/01/2025)

This week's topics are migrating the OpenID module to OpenIddict 6, adding Recipe Roles permission behavior, and we will mention our latest Orchard Nuggets post, where you can learn how to add media management to an ASP.NET Core app. Without further ado, let's dive in!

Featured tags

IIS
API
SMS
SEO
All tags >

How to add media management to an ASP.NET Core app? - Orchard Core Nuggets

Using media files, such as images, videos, and documents (like PDF files), is a common requirement for a modern website. Media can enhance user experience by making content more engaging, visually appealing, and/or easier to understand. Fortunately, Orchard Core has a built-in solution: the Orchard Core Media feature. As the description says in the official documentation:The Media module provides a UI to upload and organize binary files that can be used while creating content.Are you new to Orchard Core? It's a great open-source framework, and CMS built on ASP.NET Core. Check out the official getting started docs.Let's see Orchard Dojo and its blog for a real-life example of why you would use the media feature. At Orchard Dojo, we mainly use images for two things:Image of trainers: As you can see on the About page.Images for blog posts: For example, in this blog post.We have flexibility, and we can organize the media files using the media feature.Flexibility: Let's say a trainer got a new haircut and wants to update their image. Then, we can overwrite the old image with the same name in the media library, and that's it.Organization: We can have a “Trainers” media folder with the trainers' images, a “Blog Posts” folder with the images for blog posts broken down to years, and a folder for each individual blog post's images.Now, to turn on the feature, go to Configuration → Features and make sure the Media feature is enabled. You can additionally enable these media features: Media Cache: The feature caches remote media files locally, improving performance and reducing bandwidth usage for sites using external storage like Azure Blob or S3. For example, an online store with product images hosted on cloud storage can deliver images faster to users.Media Slugify: The feature ensures SEO-friendly URLs by automatically renaming new media folders and files to use slugs (e.g., “The team (2020).jpg” becomes “the-team-2020.jpg”). This is useful for improving search visibility, such as when uploading product images for an e-commerce site. The URLs are also just nicer.Secure Media: This feature allows administrators to control access to media folders based on user roles, ensuring only authorized users can view or manage specific files. For example, a company could restrict marketing files to the marketing team while allowing all staff to access shared resources, enhancing security and organization. If you are new to Orchard Core, you can check out user management (including adding permissions to roles) in one of our Dojo Course videos (to learn more about Dojo Course, click here).After enabling the Media feature, go to the Content menu, and you will see the Media Library menu item. Inside the Media Library, you will see one already existing folder named “_Users”. You can read about this here in detail. But in a nutshell, Orchard Core's Media Library includes a “_Users” folder with subfolders for each user, allowing them to manage their own media. New permissions like Manage All Media Folders and Manage Own Media let admins control access while restricting editors to their folders.A few buttons are not self-explanatory in the media library; we will go through them. With the plus button, you can add new folders to the media library. Just click on the folder and type its name. If you click on an existing folder, follow the same process; the new folder will be created as a subfolder of the current one.The invert button inverts the selection, so if you have image-1.jpg, image-2.jpg, and image-3.jpg, and you selected images 1 and 2, if you click on it, images 1 and 2 will be unselected, and 3 will be selected.With these buttons, you can change between list and grid view: This is the button for uploading files. You can select them from your computer, but you can also just drag them into the empty space in your folder in the media library.The delete button is also available, which is mainly for mass deleting files. If you want to do something with only one file, you can click on it, and three options will appear: rename, delete, and download. You can also filter by file name, that option is left to the upload button (4).Turning on different media features will also add new menu items to the Media menu under the Configuration menu. Media Cache: This menu item appears only if you turn on the Media Cache feature, which we discussed earlier. It contains options related to that feature, such as purging all the assets from the cache.Media Options: Here, you can see the configured media options. One option, for example, is Allowed file extensions, which tell you files with which extensions may be uploaded. You can configure these options from the appsettings.json file or other ASP.NET Core configuration providers. You can read more about it here. For example, if you want to allow only image uploads, you can specify extensions like .jpg, .png, or .gif. This ensures users can upload only images, preventing unauthorized file types like .exe or .zip.Media Profiles: In this menu item, you can define custom image transformations, such as resizing or cropping, to ensure consistent formatting across your site. For example, you can create a thumbnail profile that automatically resizes all product images to 200x200 pixels for a uniform storefront display.When you turn on the Media feature, you will also have a new content field, the media field. Returning to our example, we have trainers on the About page on Orchard Dojo. We already have a widget dedicated to trainers. A media field called image was added to the content type. You can see the media field's settings here: For example, when using the “Multiple” option, we can display multiple images in one media field. With the media field added, when we are creating a Trainer Widget, we can select an image: The plus button opens the media library, where you can select your image. After selecting the image, you will get a small preview of it: But let's see the blog post example. In our Blog Post content type, we have an HTML body (with the Trumbowyg editor). This supports adding an image with the image shortcode. Clicking on the “Insert Media” button, you can select the file from the media library. The result will be something like this: [], and the image will appear in the blog post after publishing it.In this blog post, we’ve seen Orchard Dojo's media library and how we use it, but let's look at another example: You have an e-commerce page where you sell tech products. With the Media feature, you can create product content items with media fields to display images of the products (even multiple with one media field). Let's say on the same site, you are also reviewing tech products in a blog-like format. When you are writing a review, you can use the image shortcode in the HTML body to display your photos of the product.To conclude, Orchard Core’s Media feature makes it easy and effective to manage media files across your site. With features like customizable media profiles, caching, and role-based access, it helps keep your media organized.Did you like this post? It's part of our Orchard Core Nuggets series where we answer common Orchard questions, be it about user-facing features or developer-level issues. Check out the other posts for more such bite-sized Orchard Core tips and let us know if you have another question!

How to add import/export to an ASP.NET Core app? - Orchard Core Nuggets

When working with an ASP.NET Core application, it’s often necessary to move various content or configurations between different environments or back up critical information. Whether you’re setting up a new site, migrating content, or synchronizing data across multiple instances, the Orchard Core Deployment feature can simplify the process. This feature provides an easy solution for importing and exporting data.Are you new to Orchard Core? It's a great open-source framework and CMS built on ASP.NET Core. Check out the official getting started docs.Let’s say you manage multiple sites for clients. You might have a standard set of content (like sample blog posts, landing pages, or settings) to help clients get started. With Orchard Core Deployment, you can create these once, export them, and import them into each new Orchard Core instance to streamline the onboarding process. A similar example would be to move content or configuration between a staging and production app.To get started, go to Configuration → Features and search for “Deployment”. Some features will also enable others explicitly. We will go through each feature and explain what they do. Deployment: Offers a framework for importing and exporting recipes, JSON files containing configuration and content. This feature is the foundation of deployment (how we call export-import) in Orchard Core, allowing for the structured export and import of content, technical configuration, and user-editable settings for entire sites or specific components.Remote Deployment: Extends the deployment feature by allowing content export and import to and from a remote server. This feature is useful when managing Orchard Core installations across multiple environments, enabling direct deployment to remote instances, without downloading and uploading JSON files.Add Content To Deployment Plan: This feature adds an action in the content item action list to include specific content items in a deployment plan. This is useful when you want to select specific items to deploy without including the entire site’s content.Export Content To Deployment Target: Adds an option to the content item action list that allows you to directly export content items to a specified deployment target (including downloading the recipe, thus basically the content item inside a JSON file locally).View Or Download Content As JSON: Provides an action in the content item action list to view or download content as JSON files. This feature is helpful for reviewing content item details or troubleshooting.Here is an example of all the content item list actions that are added by these features:These actions focus on single content items and they are really simple. “View as JSON” and “Download as JSON” options are self-explanatory. If you select “Add to Deployment Plan” you will get a list of your current deployment plans and a default one will be created (“Export content to deployment plan target”):“Export to Deployment Target” will list the deployment targets. The default one is “File Download”:But what is a deployment plan? It’s a collection of steps that together produce a recipe JSON file. You can have multiple deployment plans. Let’s create one! Go to Configuration → Import/Export → Deployment Plans. Here you can see your deployment plans, rename them (with “Edit”), delete them, and modify them (“Manage Steps”).image alt="Deployment plans inside menu"]BlogPost/orchard-nuggets/2024/how-to-add-import-export-to-an-asp-net-core-app/deployment-plans-inside-menu.png[/image]Click on the “Add Deployment Plan” button. Here you can name your new deployment plan.After that, you can create the plan, and then you will see it in the list. Now click on the “Manage Steps” button for your deployment plan. You will see this screen, but it’s empty since you need to click on the “Add Step” button to add steps:Here you will see all the available steps:They have descriptions, but just to name a few important ones:All Content: Exports all the content items of the system.Content: Exports all content items for specified content types.Content Item: Exports a specified content item.All Features: Exports the state of all features, ensuring the same features are enabled or disabled across sites.We have two Page content items in our case, so let’s export those with the “My second deployment plan”.Add the “Content” step. Then select the Page content type. Additionally, you can check the “Export As Setup Recipe” option if the data should be exported as a Setup recipe. A setup recipe in Orchard Core is a JSON file that contains instructions for setting up content, configuration, and features on a new or existing Orchard Core instance, structured to automate the setup of a site. It’s almost the same as a recipe that you can export with the Deployment feature, just it needs to contain everything to set up a site, not just e.g. a couple of pages.After that, you can add the step by clicking on “Create” and execute the plan with “Execute”:When executing you can again select the target. The default option here is the previously mentioned “File Download” to download the deployment plan locally. This will download a ZIP file that has the “Recipe.json” file inside. This will contain in our case all the page content items.Okay, but how do you import? Go to Configuration → Import/Export. You will have multiple options:JSON Import: Here you can directly insert your Recipe.json file. You can copy the file's content, or you can also just drag the file there. The content will be visible as JSON and you can edit it before importing. In this example, we used the recipe which was inside the ZIP that we downloaded from “My second deployment plan”.Package Import: Imports a complete package (ZIP file) containing multiple JSON files, media files (yes you can export media files, by adding the Media step), and other resources. So this is best for large-scale site migrations or complete environment setups. You just need to select the ZIP file, then click on “Import”:In our case, this will throw an error but this is because we already have the two pages (thus the two permalinks of the pages are already in use), but if you import this package in another application that has the Page content type, it will work. But if it doesn’t have the Page content type, you can just add the “Replace Content Definitions” step in your plan, which will also export the content type after you choose it.But what if you want to import to a remote instance? If you have the Orchard Core Deployment Remote enabled you will see two more options under Import/Export: “Remote Clients” and “Remote Instances”.Under “Remote Clients” you can add your remote clients:You will need to set a “Client Name” and an “Api Key”. This will come from the client app. So for example, if you want to import from staging to production, you will need to go to production and create the client.After that, you can enter your staging site, and under “Remote Instances” you can add the instance.You will need to set a name (it’s just for display and can be anything) and a URL (which can be copied from under “Remote Clients” for example in your production app if you are importing to production).Then you will need to set the client name and the API key. These are the ones that you set first in “Remote Clients” in the other app.After that, the instance will be available as a target when exporting something (so it would be imported right into the target).Returning to the example at the beginning:Let’s say you manage multiple sites for clients. You might have a standard set of content (like sample blog posts, landing pages, or settings) to help clients get started.With Orchard Core Deployment, you can create the “template” of these sites, with the necessary items and settings, then export them into a recipe. After that, you can send that to your clients. Or Orchard Core Remote Deployment you can even export the recipe right to your clients' app.Orchard Core’s Deployment features make it easy to move content and configuration across environments or different sites. Whether you're migrating data or synchronizing settings, these tools simplify the process. Want to see these features in action? Check out our tutorial video to learn how to set up and use Orchard Core Deployment features!Did you like this post? It's part of our Orchard Core Nuggets series where we answer common Orchard questions, be it about user-facing features or developer-level issues. Check out the other posts for more such bite-sized Orchard Core tips and let us know if you have another question!

How to add an audit trail to an ASP.NET Core app - Orchard Core Nuggets

When you have an ASP.NET Core application, that publishes content often and has different users, it’s a good idea to keep track of what is happening in the app: What changes? What content gets deleted or published by who? Who logged in, and when, did somebody fail to log in repeatedly using a wrong password? Who changed the settings?For example: Imagine you're managing a news portal where multiple articles are being written and published daily. One day, an article titled "Breaking News: Major Policy Change Announced" was accidentally deleted. It was a high-traffic piece, and its sudden disappearance created confusion among readers and the team. As an administrator or perhaps an owner, you want to restore the article, then find out what happened and who made this change. The answer is: Orchard Core and its Audit Trail module.Are you new to Orchard Core? It's a great open-source framework and CMS built on ASP.NET Core. Check out the official getting started docs.The Audit Trail module logs key changes and events in the system, such as content creation, deletion, and login failures. It also allows tracking changes to content, restoring previous versions, and recovering deleted items. It’s all extensible too, so you can add more features with some coding. Let’s see how to use it!First, go to Configuration → Features and make sure the Audit Trail feature is enabled. Optionally, if you also want to track user events (like somebody logging in etc.) you can enable the Users Audit Trail feature too. Please note that enabling the Users Audit Trail feature will automatically enable the base Audit Trail feature, as it is a dependency of the Users Audit Trail. After this, you can access the audit trail settings under Configuration → Settings → Audit Trail. You can see three tabs on the top: Events, Trimming, and Content. Let’s start with Events. Here you can see the events that will trigger an audit trail record, and by default, all of them are enabled. The first set of events is tied to content, so content item creation, removal, etc. You can disable any of those if you want. The second set of events is for the user. This set of events only appears if you enable the Users Audit Trail feature too. These are for user activities, so login, failed login, etc. You can also select to record the client's IP address. We recommend erring on side of caution, and starting with everything enabled, and only disable certain events if it turns out that they’re just noise for your site.Now take a look at the other tab, Trimming. If a site has a lot of activity, perhaps it’s good to delete audit trail logs after a year or so, since the records can eat up a lot of space in the database (it won’t really get slower, but depending on your hosting provider, you may need to pay more). The trimming setting allows you to do that. The default trimming option is 90 days. So any audit trail event that is logged and older than 90 days will be deleted from the database. To avoid trimming you can select the Disable trimming task option. In the Last run field, you can see the most recent time the trimming task was executed.Now, check the content tab. Here you can see the types of content for which events are logged. You can freely disable or enable any of them. In our example, some are enabled, but some are disabled. This is because we configured the audit trail settings in the startup recipe. For example, see this startup recipe in our open-source Lombiq Walkthroughs module. Of course, if you have different content types than our example site, you will see them on this screen. But remember, if a content type is disabled here, its events won’t be recorded (like deletion). Not all content types may be important for you to track. For example, if you're not actively using a particular content type, you might want to disable the logging of it to reduce unnecessary noise. Only track what’s necessary to balance performance and insight. For instance, in the image, just to name one, the tracking of the Layout Injection content type is disabled. This is because it’s a widget that is only used in one place, and it won’t be updated ever likely.Additionally turning on the Audit Trail feature will add a content part called Audit Trail part. This part as the description says: “Allows editors to enter a comment to be saved into the Audit Trail event when saving a content item.” If you add this part to the content type, you will see a new field for a comment, what you can use to add some explanation about the current content change. Staying with the news portal example, each time an editor revises, they can leave a comment in the audit trail explaining what was changed and why. For example, "I reworked the intro paragraph for clarity." This is all good, but how one can see the actual logs? Well, it’s pretty simple, now there is a new tab in the admin menu called Audit Trail. In this example, we had a page content type and audit trail turned on from the beginning. When I set up the site I created an admin user and I logged in. After that, I created a page content item, published it, and deleted it. You can restore deleted content items from the audit trail, so that’s what I did next. Then I renamed the title of the page. You can see all that from the logs: Returning to the example at the beginning:One day, an article titled "Breaking News: Major Policy Change Announced" was accidentally deleted.If the audit trail was turned on for that content type, now there is a solution! Go to the audit trail logs, you will see who deleted it and you can also restore it, correcting all the mistakes.For more audit trail features check out our open-source Orchard Core extension for the Audit Trail module: Lombiq Audit Trail Extensions. Did you like this post? It's part of our Orchard Core Nuggets series where we answer common Orchard questions, be it about user-facing features or developer-level issues. Check out the other posts for more such bite-sized Orchard Core tips and let us know if you have another question!

How to add workflows to an ASP.NET Core app - Orchard Core Nuggets

Do you want to send an email, when a form is submitted? Perhaps delete a content item after a certain amount of time? You don't want to write complex codes? Look no further with the Orchard Core Workflows feature you can achieve these, without writing any code. This way people who are not familiar with coding can also easily modify these processes.Are you new to Orchard Core? It's a great open-source framework and CMS built on ASP.NET Core. Check out the official getting started docs.Workflows in Orchard Core can be a powerful tool. A workflow is basically a visual script, that consists of two types of activities: Tasks and Events. A Task activity performs an action, for example sends an email, or creates a notification. An Event activity is like a trigger point, it listens for an event and it can activate Tasks. But why are workflows so useful? Here are some examples of what you can do with workflows:Automatically assigning a role to a user based on their input from a registration form.Moving content to an "Archived" state after a specified number of days since publication.Sending users a weekly email digest summarizing newly published content on the site.Sending a reminder to users who have incomplete profile information after a certain period.This is to name a couple.Let's see how you can create your own workflow! In this example we will create a workflow that displays a notification, but only for users in the Administrator role.First, go to Configuration → Features and make sure the Workflows feature is enabled. Now you can access the workflows in the Workflows menu point. Click on the Create Workflow button. Name the workflows for example "Display Notification for Administrators". You can leave the other settings as they are and click on Save. Now you will see the dashboard of our workflow. Here click on the Add Event button, so our workflow will have a starting point. Select the User LoggedIn activity, you can give it a title but it's not necessary. To make this your startup event, you will need to click on the event and then on the Startup task button. After that, the event card will turn green. Now let's add a task. Click on the Add Task button and select Validate User, as the description says it checks if the user exists for the current request and has the specified role(s)". When adding the task select the Administrator role in roles. Also select Set the 'UserName' workflow property if the user is authenticated. Okay, there is a starting event and a task, but how do we connect them? It's pretty simple: grab the green dot from the top of the starting activity and drag it to the task. We only need one more activity a task that displays notifications. So click on the Add Task button once more and select Notify. For the notification type let's go with Success, the message could be anything, but since we have the username from the previous activity, we can personally welcome the user. You can use Liquid syntax, just like this "Welcome, {{ Workflow.Properties.UserName }}!". After saving it, the only thing left to do is to connect the InRole dot from the top of the Validate User activity to the Sucsess Notification activity. In the end, your workflow should look something like this: Save it, then you can log off and log in with an admin user and see the results: That's it! You can modify this workflow how you want, add more events or tasks and based on this tutorial create your own!Did you like this post? It's part of our Orchard Core Nuggets series where we answer common Orchard questions, be it about user-facing features or developer-level issues. Check out the other posts for more such bite-sized Orchard Core tips and let us know if you have another question!

How to change the idle logout time in Orchard Core - Orchard Core Nuggets

Keeping user accounts secure is important. One aspect of this is to constrain how long people can remain logged in: If they share a device, especially a public one, then it's better to be on the safe side and automatically log them out after some time of inactivity. Here is how you can do it in Orchard Core! Since an Orchard Core-using app is in the end just an ASP.NET Core app, you can use the standard Identity options to configure how user sessions work. What governs how long users remain logged in is mostly the cookie settings. This is how you can set it from the Program file of your web app: builder.Services .AddOrchardCms() .ConfigureServices(services => services.ConfigureApplicationCookie(options => options.ExpireTimeSpan = TimeSpan.FromMinutes(30))); This logs users out after 30 minutes of inactivity. You can also set options.SlidingExpiration = false if you'd like this to be counted from the time they logged in, as opposed to the last time they did something in the app. While the above example shows how to do this in the root web app, you can similarly set this from the Startup class of a module or theme. That's it! It's worth checking out the official Orchard Core docs on configuring other Identity options too. Did you like this post? It's part of our Orchard Core Nuggets series where we answer common Orchard questions, be it about user-facing features or developer-level issues. Check out the other posts for more such bite-sized Orchard Core tips and let us know if you have another question!

How to do a security scan of an Orchard Core app - Orchard Core Nuggets

You don't want malicious people to crack your web apps to use them for spamming, cryptocurrency mining, and spreading malware, nor do you want them to get access to your users' personal data (if you actually do want to cooperate with criminals, you don't need to read further). Thus, you want your app to be secure. One aspect of achieving this is to do penetration testing on your app. Thankfully, much of this can be automated, and with the help of Lombiq UI Testing Toolbox for Orchard Core and Zed Attack Proxy (ZAP) you can conveniently do this for your Orchard Core app. Let's see how! First, install v8.2.1-alpha.6.osoe-351 or greater of the UI Testing Toolbox from NuGet because that's the one that added security scanning. There are a couple of minor breaking changes that should affect nobody, really, in this, so it'll be part of the upcoming v.9.0.0 (but for that, we're waiting for Orchard Core 1.8). Set up UI testing as explained in the UI Testing Toolbox's documentation. While we're focusing on security scanning here, the UI Testing Toolbox can do a lot, and I really mean a lot more, including one-liners to test if the basic Orchard Core features still work in your app, or unleashing automated monkey testing to try to break your app. We never work on an Orchard Core app without its safety net! Add one or more test cases to run ZAP's security scan. Since all the configuration of ZAP is available to you, customization is unlimited, but to give you a glimpse, this is how a basic security scan that's already a good start would look like: [Fact] public Task BasicSecurityScanShouldPass() => ExecuteTestAfterSetupAsync(context => context.RunAndAssertBaselineSecurityScanAsync()); And that's it! OK, I might have omitted the last step here: 4. Fix all the security issues ZAP finds, because it'll definitely find at least a couple of them! This was just a short teaser, but be sure to check out the UI Testing Toolbox's security scanning documentation, because we tried to summarize everything necessary to get you going there, including samples that you can just copy-paste. Do you want to see security scanning in action? Check out the demo video too! Also, security starts with quality code. Check out our Lombiq .NET Analyzers project to get automated checks for your code too, including pointing out potential security issues even before running the app. Did you like this post? It's part of our Orchard Core Nuggets series where we answer common Orchard questions, be it about user-facing features or developer-level issues. Check out the other posts for more such bite-sized Orchard Core tips and let us know if you have another question!

How to debug a NuGet-based Orchard Core solution - Orchard Core Nuggets

How can you debug Orchard Core code when you’re working with a solution that loads Orchard packages from NuGet? Orchard’s packages are built with symbols so you can actually use them as source too! First, in Visual Studio be sure to uncheck “Enable Just My Code” under Tools → Options → Debugging → General. Then you can debug almost as usual: If you want to step into Orchard’s code from your own code then just put a breakpoint into your code as usual and hit Step Into (F11). It’ll open the Orchard source and debugging will work as usual. If you want to place a breakpoint anywhere in the Orchard Code that you can’t step into from yours (like a controller action) then do the following: Add a reference to the type anywhere in your own code. E.g. just write ItemController somewhere and import the namespace for OrchardCore.Contents.Controllers.ItemController. Hit Go To Definition (F12) on the type. Now you’re at the decompiled source of the type. This won’t be perfect but at least you’ll be able to place a breakpoint at the beginning of the method or other member you want to debug. Be sure to tick “Allow the source code to be different from the original” under the breakpoint’s settings. Run the app with the debugger attached. Your breakpoint will be hit and then the nice symbol sources will be used, just as when you step into Orchard’s code. Note that with “Enable Just My Code” you’ll also potentially see exceptions from the libraries you use or from .NET, even if they’re swallowed down the line. Depending on your work it might be better to keep the option ticked most of the time. Alternatively, you can also try opening a full Orchard source solution (with the Orchard version closest to what you’re using) and attach it to your own app. This sometimes works too but you can only debug Orchard’s own code in that case, not yours. Did you like this post? It's part of our Orchard Core Nuggets series where we answer common Orchard questions, be it about user-facing features or developer-level issues. Check out the other posts for more such bite-sized Orchard Core tips and let us know if you have another question!

How to access services from another tenant in Orchard Core - Orchard Core Nuggets

The multi-tenancy feature of Orchard Core is great: A tenant is basically a subsite with its own independent content and configuration, under its own domain or URL prefix. You can use tenants to e.g. host websites for multiple customers of yours from a single Orchard Core app. The sites won't know anything about each other but they'll run from the same app built from the same codebase, and have access to the same modules and themes. This makes maintaining such sites very efficient, both for hosting and for development. What if you want tenants to be not that isolated though? What if there is certain content or configuration that you actually want to share among tenants or some functionality that you want to centralize on one tenant? You can use the APIs we show below to cross tenant boundaries and use any service from another tenant! Back in the day, this was also possible with Orchard 1. What we'll see here is a simple controller (just for the sake of easy demonstration, you can do the same thing anywhere). In the Index action, we'll fetch content items from another tenant with the IContentManager service that you already know. This is just an example though, really you can access any other service as well. public class CrossTenantServicesController : Controller { private readonly IShellHost _shellHost; // We'll need IShellHost to access services from a currently running shell's dependency injection container // (Service Provider). public CrossTenantServicesController(IShellHost shellHost) => _shellHost = shellHost; // A simple route for convenience. You can access this from under /CrossTenantServices?contentItemId=ID. Here // ID needs to be a content item ID that you can get e.g. from the URL when you open an item to edit from the // admin (it looks something like "4da2sme18cc2k2rpdgwx3d4cwj" which is NOT made by a cat walking across the // keyboard!). [Route("CrossTenantServices")] public async Task<string> Index(string contentItemId) { // Even if you don't create tenants, there will still be a single tenant in an Orchard app, the Default // tenant. For all other tenants you create you can provide the technical name. // In this example, we'll access content items from the Default tenant but this works for any tenant of // course. Create a tenant in your app (enable the Tenants feature and then create it from under // Configuration / Tenants), enable the Training Demo on it too and check out how this works there! // First you have to retrieve the tenant's shell scope that contains the shell's Service Provider. Note // that there is also an IShellSettingsManager service that you can use to access the just shell settings // for all tenants (shell settings are a tenant's basic settings, like its technical name and its URL). var shellScope = await _shellHost.GetScopeAsync("Default"); // We'll just return the title of the content item from this action but you can do anything else with the // item too, like displaying it. string title = null; // With UsingAsync() we'll create a block where everything is executed within the context of that other // tenant. It's a bit similar to being inside a controller action, but remember that all of this is running // on the Default tenant, even if you're looking at it from another tenant you've created. await shellScope.UsingAsync(async scope => { // You can resolve any service from the shell's Service Provider. This serves instead of injecting // services in the constructor. var contentManager = scope.ServiceProvider.GetRequiredService<IContentManager>(); // We can use IContentManager as usual, it'll just work. // Note that for the sake of simplicity there is no error handling for missing content items here, or // any authorization. It's up to you to add those :). var contentItem = await contentManager.GetAsync(contentItemId); // DisplayText is what you've already learned about in PersonPartHandler. title = contentItem.DisplayText; }); return title; } } Pretty neat, right? If you'd like to play with the code and see it in action check it out in our Training Demo module! Note that a shortcut to achieving this is now part of our Helpful Libraries too! Did you like this post? It's part of our Orchard Core Nuggets series where we answer common Orchard questions, be it about user-facing features or developer-level issues. Check out the other posts for more such bite-sized Orchard Core tips and let us know if you have another question!

How can I call an external API from a workflow task? - Orchard Core Nuggets

You have several options to send an HTTP request to an external API in Orchard Core, but maybe you haven't tried the Http Request Task. Let's see quickly how you can hook up a workflow! The HTTP Request Task comes from the HTTP Workflows Activities feature, so before doing anything, don't forget the enable that module. Now navigate to the Workflows option from the menu and hit Create Workflow Type to add your workflow. JSONPlaceholder is a nice fake online REST API that you can use whenever you need some fake data. It comes with a set of 6 common resources and we are going to use the first one and making a GET HTTP request to get 100 user posts in a JSON format. Choose the Add Task button in the Workflow editor and select the HTTP Request one from the HTTP category. Here you can see a nice editor where you can provide the details of your request. We added a custom title to our activity as Get 100 posts. The URL will be the URL provided by the JSONPlaceholder API. To get the posts we have to make a GET request. If you would like to add a new post, make a POST request to the same endpoint, and provide the body to send. Don't forget to handle the 201 HTTP response code, because this will be the number that will show you that you are good to go and the server faked that your content was created. You may notice that you can type Liquid code everywhere in this editor. Let's say that the title of our new post will be the name of our site. To do that, we can pass the {{ Site.SiteName }} Liquid expression. As we mentioned, we get 201 if everything goes well. If the server returned with anything else, then something bad happened and we should handle that in our workflow of course. To handle the failed requests, we can use the Unhandled HTTP Status branch of the HTTP Request Task (we named in Create a new post) and notice the user somehow. OK, it's not a useful workflow, because we are only dealing with the response codes, but not with the response body. But how can we use the response details? To find the answer we have to check the source code of the HTTP Request Task activity and take a look at the ExecutyAsync method. Here you can see that the code uses the LastResult of the workflowContext and the LastResult has a Body property where you can find the response body itself. The LastResult property of the WorkflowExecutionContext is an object, that means you can easily put everything into the LastResult, but it could be a little bit harder to get the content from it. public override async Task<ActivityExecutionResult> ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { using (var httpClient = new HttpClient()) { var headersText = await _expressionEvaluator.EvaluateAsync(Headers, workflowContext); var headers = ParseHeaders(headersText); foreach (var header in headers) { httpClient.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value); } var httpMethod = HttpMethod; var url = await _expressionEvaluator.EvaluateAsync(Url, workflowContext); var request = new HttpRequestMessage(new HttpMethod(httpMethod), url); var postMethods = new[] { HttpMethods.Patch, HttpMethods.Post, HttpMethods.Put }; if (postMethods.Any(x => string.Equals(x, httpMethod, StringComparison.OrdinalIgnoreCase))) { var body = await _expressionEvaluator.EvaluateAsync(Body, workflowContext); var contentType = await _expressionEvaluator.EvaluateAsync(ContentType, workflowContext); request.Content = new StringContent(body, Encoding.UTF8, contentType); } var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead); var responseCodes = ParseResponseCodes(HttpResponseCodes); var outcome = responseCodes.FirstOrDefault(x => x == (int)response.StatusCode); workflowContext.LastResult = new { Body = await response.Content.ReadAsStringAsync(), Headers = response.Headers.ToDictionary(x => x.Key), StatusCode = response.StatusCode, ReasonPhrase = response.ReasonPhrase, IsSuccessStatusCode = response.IsSuccessStatusCode }; return Outcomes(outcome != 0 ? outcome.ToString() : "UnhandledHttpStatus"); } } Imagine you are implementing a custom activity that creates content items based on the response body. For that, you need to get the JSON then serialize it to a typed class. That makes the data easier to work with. In the ExecutyAsync method of your custom activity you can get the JSON like: var responseBody = workflowContext.LastResult.GetType().GetProperty("Body").GetValue(workflowContext.LastResult).ToString(); Here the responseBody variable will contain a JSON in a string. You may notice that the value of the title here is Orchard Core, which comes from the {{ Site.SiteName }} Liquid value. To deserialize the response to typed classes you can use the built-in Json.NET package in Orchard Core and for instance, use the JsonConvert.DeserializeObject method of it. And that's it, now do what you want with the data. Did you like this post? It's part of our Orchard Core Nuggets series where we answer common Orchard questions, be it about user-facing features or developer-level issues. Check out the other posts for more such bite-sized Orchard Core tips and let us know if you have another question!

How to fix "InvalidDataException: Form value count limit 1024 exceeded." in Orchard Core - Orchard Core Nuggets

Let's suppose you're building your shiny new Orchard Core website. In there you're also building a shiny new page, with Flow Part obviously. You throw together a lot of widgets to get all the bells and whistles on the page, then you save it and BAM! Internal Server Error: "InvalidDataException: Form value count limit 1024 exceeded." What's this, did I break Orchard? Is Orchard trying to break me? Let's fix this! The exception happens because the structure you've built with Flow Part is simply too large for the default ASP.NET Core limits. This is not something that would be too extreme to achieve, actually: If you have more complex widgets (with a lot of fields each) and you put several of them into a complex nested structure you can quite possibly build something by hand that would fail like this. Ask how I know! You can increase the limits restricting posted form value sizes, and in this particular case you'd need to change the ValueCountLimit value of FormOptions. Put this into the Startup class of your Orchard-based web app project (it won't work in a module or theme!): services.Configure This increased the limit to 4096, plenty more than the default. However, keep in mind that these limits have their uses: Malicious users could try to post large pieces of data to your server, trying to overwhelm it for example. So only increase this as much you only need! Note BTW that we're using the ASP.NET Core configuration API here, something which is also demonstrated in detail in our Training Demo Module, so follow up learning there! Did you like this post? It's part of our Orchard Core Nuggets series where we answer common Orchard questions, be it about user-facing features or developer-level issues. Check out the other posts for more such bite-sized Orchard Core tips and let us know if you have another question!