Using HTTP Status Codes to Improve Your Custom APIs

Introduction to HTTP Status Codes for Software Testers - TestLodge Blog

Introduction

Custom APIs are becoming increasingly important in Dynamics 365 development. To ensure that they meet the highest standards, it’s important to be able to send appropriate HTTP status codes in response to client requests.

Recently, a client asked me if it was possible to send specific HTTP status codes from a Custom API in Dataverse. After some research, I discovered that it is indeed possible, and it’s a good practice to implement. In this article, I will explain the different ways to send appropriate HTTP status codes in a Custom API response, which can lead to a better user experience.

Problem

A Custom API may call an external service to fetch data, but sometimes, the service may return no records. To notify the user of the custom API that no records were found, it’s important to respond with the appropriate HTTP response code. In this case, the appropriate code is 404, indicating that the requested resource could not be found. Providing an accurate and descriptive response code can lead to a more efficient and satisfying user experience.

Solution

Basic Usage

When developing workflows and plugins in Dynamics 365, InvalidPluginExecutionException is commonly used to handle errors and exceptions. While this approach is suitable for simple scenarios, it may not provide enough flexibility for more complex situations.

The most basic way to use InvalidPluginExecutionException is to pass a string containing the error message to the constructor, like this:

This will throw an exception with the specified error message.

Overloads

In addition to the basic usage, there is an important overload of InvalidPluginExecutionException that allows you to pass a specific HTTP status code that you want to return from your custom API method.

The InvalidPluginExecutionException(String, PluginHttpStatusCode) overload takes two parameters:

  • The first parameter is a String that represents the error message you want to display to the user.
  • The second parameter is a PluginHttpStatusCode enumeration that represents the HTTP status code you want to return.

By using this overload, you can return specific HTTP status codes for different scenarios in your custom API. For example, if you want to notify the user that no records were found, you can use the code below to return a 404 status code.

Example with Not Found response

Here’s an example of a custom API that fetches data from an external system. If the query returns no results, the code will throw an InvalidPluginExecutionException with the message “No records found in System X” and a status code of 404. This will cause the API to return a 404 error to the user.

HTTP Response of Custom API

When making a call to the upper API in Postman, for example, you will receive a 404 HTTP code if there is an issue with the request. In the response body, the message you sent in the string parameter will be included.

As an example, a properly formatted response could look like the following:

The user can easily identify the specific error that occurred and the associated error code. This information is critical in troubleshooting the issue and finding a resolution.

Conclusion

In conclusion, when developing custom APIs in Dynamics 365, it’s important to handle errors and exceptions properly. While the InvalidPluginExecutionException is a common approach to handling exceptions, it may not provide enough flexibility for more complex scenarios. By using the overload of InvalidPluginExecutionException that allows you to specify a specific HTTP status code, you can return appropriate HTTP response codes for different scenarios, such as when no records are found. This can improve the user experience and help with troubleshooting and debugging.

My top 3 features in 2020 Release Wave 1

Finally, the release notes are published and I’m more than happy to go through them.

You can find them on the Docs pages below:

After a quick first read, I wanted to make my favorites list and choose the top 3 features that caught my attention in this release.

Let’s start with the countdown!

3. Save is always visible in the command bar on edit forms

Customers using model-driven Power Apps will see the Save and Save & Close option on the out-of-box entity command bar when editing a record. Before this release, if the auto save option was turned on, both options were hidden and not available in the command bar. The save option was only visible in the footer.

Microsoft Docs

Really a small addition, but it makes out lives so easier. I stopped counting the requests that included adding the save button on the ribbon at all times. This is definitely one of the most requested features by the customers in the past years.

It will save us a lot of time and make us use Ribbon Workbench for more complex stuff than adding the Save button all around.

2. Modern solution import experience

In addition to supporting capabilities of classic solution import, the modern experience offers the following enhancements:

– You’re now able to create and authorize the connections required by your flows so that they’re created in a working state

– Set environment variable values required by other components in your solution

– Reduced complexity when choosing from import actions

– Accessibility

Microsoft Docs

Old solution import really needed an upgrade since nowadays we have a ton of new stuff that we can put inside and configure. Flows are a great example because at the moment our Flows are not working straight away when we import them to the environment. I hope that with the new experience we will set all the configurations and connections before publishing the final changes so we can run them straight after the import.

Setting the connections after the import to the new environment is the most annoying part for me today so this one makes me quite happy.

1. Web APIs for CRUD operations on Common Data Service entities

The liquid tags in portals today provide read-only capability. Creating, updating, and deleting operations require using UI components like entity list and entity forms. This feature adds Web APIs for portals that allow users to create, read, update, and delete operations across all Common Data Service entities.

Microsoft Docs

I’m 100% sure that all the Portal guys out there are so excited. We all know how Portals didn’t provide us an easy way to do a bit more complex operations other than simple creates and updates. With this feature, we can finally do some crazy magic like we are used to doing on classic forms on our applications. No more hacks to perform such straightforward actions anymore, but in the end, I must admit that I still love some Liquid hacks out there only because it just shows that imagination has no limits.

Nice addition to this one should be a support for PCF controls in the near future, maybe in the next release, so we can truly push the Portal forms to the next level.

Final thoughts

There is more interesting stuff in the release notes, but those 3 I mentioned up there stick to my mind on the first read. Since we can’t try any of those we can only hope that we will get the expected result as soon as they become available.

I’m also sure that there are already some hidden gems in this release and that we will find them out in the following days. Until then it’s time to study the given Docs even more!

PCF Time – Gallery Control

I’ve been playing with PCF for last few days and I finally managed to finish my first control.

I wanted to make a control that will show thumbnails of image files attached in notes. First thought was to attach it to subgrid, but I forgot that you can’t make subgrid of notes with OOB functionality. This didn’t stop me of trying to make it work so I decided to bind it to the simple text field.

Control is a really simple one. It shows all the images that are found in notes and present them as images. When you click on a thumbnail you will get a bigger preview of the image just below the thumbnails. Clicking on a big preview hides the big one.

Under each thumbnail, there is filename displayed which is also clickable and will result with download action for the clicked file.

Here is the GIF that will show the control in action.

Download the latest solution here.

I know that the Typescript coding is not my strongest side at the moment, but I keep improving in the future for sure.

You can check source code at the GitHub repository:

https://github.com/DynamicsNinja/PCF-Gallery-Control

The PCF just feels like a great tool for Dynamics developers and I think we finally have a tool that was always a dream by every Dynamics developer out there. There is also a features wish list already start at the community so you can check it out and support the ideas by others.

Can’t wait to see what will community do with this powerful tool in following months.

New CrmSdk force us to use .NET v4.6.2

It’s that time of the year when all older organizations are upgraded to the latest version of Dynamics and with that upgrade tons of new issues are produced as usual.

First of all, I have noticed that a lot of async jobs started to fail (not every time) due to 2 errors:

  • System.ServiceModel.CommunicationObjectFaultedException: The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state
  • System.TimeoutException: Couldn’t complete execution of the custom activity XYZ plug-in within the 2-minute time limit.

The main problem was that I forgot to update the SDK on the workflow activities project to the v9.x version, but when I tried to update to the latest SDK version I was stopped by an interesting error.

There is no info about required .NET framework version on the NuGet installer screen.

But when you search up for the NuGet package on the web (https://www.nuget.org/packages/Microsoft.CrmSdk.CoreAssemblies) you will find the answer very quickly.

The answer is that from now on you need to use .NET v4.6.2 on all of your projects that will use new SDK NuGet packages.

This is a smart move by Microsoft that finally confirms that .NET v4.6.2 DLL assemblies are officially supported on D365.

It’s time to update all those .NET v4.5.2 projects to the new version of the framework and take advantages of it.

Embedded canvas apps – dynamic D365 context

Introduction

Embedded canvas apps are in public preview for a few weeks now and I’ve been quite disappointed because of the context that is passed to them. The context that is passed to canvas app is a static one and it doesn’t display changes that are made on actual records so we need to use the data passed as context to make it dynamic in our app.

Canvas app control can be added to 2 elements on the form at the moment:

  • Single Line of Text
  • Subgrid

Single line of text control passes current record with all attributes as the context.

Subgrid control passes all records from the subgrid as context, but some fields are missing or just empty.

Problem

I wanted to create a canvas app that will allow us to edit contacts that are connected to the account directly from the account form.

Let’s create an app on a single line of text control.

If you ask yourself why would we use a single line of text instead of subgrid which is the more intuitive way the answer is really simple, I still didn’t find the way to do it on subgrid control because of the missing fields passed to the context (especially lookup ones). Hopefully, that issue will be fixed in near future.

Solution

First thing we need to input some test data into our D365 to validate our formulas in canvas app, othervise we will not be sure if the final result is ok.

I created 2 accounts with contacts that have email populated:

  • Constoso (Account)
    • John Doe (Contact)
    • Jane Doe (Contact)
  • Span (Account)
    • Ivan Ficko (Contact)

Just like is shown on the image below.

Next step is opening a classic Account form editor because canvas app controls are not supported on the modern designer and open properties of the one single line of text field (Ticker Symbol field in this example).

When field properties is opened click on the Controls tab and then Add control button.

After that you should have Add control dialog opened and there you need to pick Canvas app option.

You will be redirected to the field properties dialog again. Few extra fields were added here, but you should leave them as is because everything will be set automatically. The only thing you need to change here is Web radio button from Text Box to Canvas App. All you need to do here is to click Customize button to open Canvas App designer.

This screen will popup when you enter the app designer and as you can see it looks like a blank template with Gallery control.

First thing we need to do here is to make our list dynamic because in main object ModelDrivenFormIntegration.Data we have just a static list.

Since we know that we will use Contacts in our Gallery we need to find out Account ID that will be passed to our Filter function to filter up contacts.

Account ID can be found by executing following function:

You need to know that ModelDrivenFormIntegration.Data object will always be a list so you need to search for the first element of the list.

Now when we know the ID of account we can start writing filter function on Items property of the Gallery control.

We need to change Data property of Gallery from Custom to Dynamics data source by clicking on Add a data source button.

On the next screen click on the New connection button.

From the list choose Dynamics and click on the Create button.

Now you need to select which entity will be shown in the gallery control. Search for contacts and select Contacts checkbox and press Connect button.

If you done everything right you will see the list of all contacts in your gallery, but we need just contacts related to the account on our form.

Next step is to write a filter function in Items property of the gallery control.

This function filters all contacts by ‘Company Name’ field which is GUID of the account. Right side of equation is familiar from the previous step where we found a GUID of the account. After you type this function in the items field you should see the filtered contacts list.

Now we have the first part of the dynamics context done. It’s time to do the edit form for our contacts.

Press the New screen button and add the new Form screen.

Again we need to set Data property to Dynamics data source and select Contacts entity. We don’t need all the columns that are selected as default, so you can just uncheck them and include only first name, last name and email field.

Next, you need to set Item property to selected item from the gallery on the first screen. In my case, it’s called Gallery1 and the property for the selected item is called Selected, so the final formula is shown below:

When you type that in Item property of EditForm control you should see details from the first contact on the list in your app.

Every data link is now connected as it should be, but we still need to add some navigation controls.

First you need to edit next arrow on the list screen. You need to add one more action to OnSelect poperty and it’s a easy one that will just open second screen. Formula in OnSelect poprety should look like one below:

Screen2 is the name of the second screen in my example and it can be different in your app. The second parameter is transition animation and you can choose any of those.

Final step is to add Navigation function on the second screen. Again change OnSelect property, but this time on accept button that looks like a white tick symbol in the upper right corner of the screen. Function here must look like:

The only thing you need to change here is to input name of the first screen.

Now you can test your app by opening the app and selecting one of the contacts and then changing the email on the edit form. If everything is set up well you should see a changed email when you go back to the list form.

Your app is still not saved so you need to save it first by pressing the File -> Save button. When you saved your app you should see the app ID field populated on the Field properties dialog.

Finally we have our canvas app 100% complete. Now we need to test it on the Unified Interface because it’s not working on classic Web view.

Final result on the account form should look like this:

Video showing the full flow is shown below:

Conclusion

This is the trick how to add life to the context of the canvas app on the entity form. I hope that in future this will be OOB functionality, but we know that in the early days we still need to do hacks to implement something.

Probbably the same thing will be possible on the subgrid control when they fix the context fields bug.

Change to WordPress.org

Hi everyone!

Since I had some problems when trying to post code snippets on WordPress.com and for me it’s an important thing that I can post code snippets in my posts I decided to set up WordPress.org version of the blog.

From now on the blog has a new URL and it can be found on the dynamicsninja.blog.

I will keep the old blog up till I change all the links posted around to the new address, but new posts will only be posted on the new blog.

I can’t tell you how happy am I because I can finally format my code snippets the way I always wanted.

Cheers!

CRM Google Maps are available​ for previous​ Dynamics versions

gmaps+crm

Since I found out that it’s possible to revert Dynamics 365 to pre-9.0 releases I made a solution that is compatible with older releases of Dynamics 365.

Now you can install the solution on following versions:

  • Dynamics CRM 2016 (v8.0)
  • Dynamics CRM 2016 Update 1 (v.8.1)
  • Dynamics 365 (v8.2+)

You can find the solution on releases page on Github as usual.

Feel free to report the issues that you have related to this version or just post a suggestion for a new feature.