Posted in Dynamics 365

Dynamics 365: Web Service plug-in failed – Invalid name character in ‘List`1’ when using Shared Variables

Hi

Recently I had an issue with D365 plug-ins and it took me a lot of investigation and trial & error to figure out the problem.

I will start by explaining my scenario:

  • Dynamics 365 v8.2 on-premise
  • Plug-in registered on the Update message and Pre-Validation execution pipeline
  • Plug-in registered on the Update message and Pre-Operation execution pipeline
  • Also my Pre-Validation plug-in passes two Shared Variables to my Pre-Operation plug-in

If you are not familiar with Shared Variables in plug-ins, they are a great way to pass values through custom code without having to read D365 data again. It is also a great way to avoid infinite loops. Take a look at the documentation for more details: https://docs.microsoft.com/en-us/dynamics365/sales-enterprise/developer/custom-plugin-handling-shared-variable.

When triggering the plug-in via my application, it threw a very weird exception and for some reason I couldn’t debug my plug-in (a serialization error would come up and not log into the profiler). After a while troubleshooting, I found the below error in the Event Viewer in D365 Server:

The Web Service plug-in failed in OrganizationId: 466f6c23-6896-e811-a824-005056a99671; SdkMessageProcessingStepId: 4d51b0c7-d9c4-ea11-b81d-005056a75ee5; EntityName: contact; Stage: 30; MessageName: Update; AssemblyName: Microsoft.Crm.Extensibility.InternalOperationPlugin, Microsoft.Crm.ObjectModel, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35; ClassName: Microsoft.Crm.Extensibility.InternalOperationPlugin; Exception: Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Web.Services.Protocols.LogicalMethodInfo.Invoke(Object target, Object[] values)
   at Microsoft.Crm.Extensibility.InternalOperationPlugin.Execute(IServiceProvider serviceProvider)
   at Microsoft.Crm.Extensibility.V5PluginProxyStep.ExecuteInternal(PipelineExecutionContext context)
   at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
Inner Exception: System.ArgumentException: Invalid name character in 'List`1'. The '`' character, hexadecimal value 0x60, cannot be included in a name.
   at System.Xml.XmlWellFormedWriter.CheckNCName(String ncname)
   at System.Xml.XmlWellFormedWriter.WriteQualifiedName(String localName, String ns)
   at System.Runtime.Serialization.XmlWriterDelegator.WriteAttributeQualifiedName(String attrPrefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, XmlDictionaryString name, XmlDictionaryString ns)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteTypeInfo(XmlWriterDelegator writer, XmlDictionaryString dataContractName, XmlDictionaryString dataContractNamespace)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteTypeInfo(XmlWriterDelegator writer, DataContract contract, DataContract declaredContract)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiType(XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerializeReference(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at WriteKeyValuePairOfstringanyTypeToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , ClassDataContract )
   at System.Runtime.Serialization.ClassDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at WriteParameterCollectionToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , CollectionDataContract )
   at System.Runtime.Serialization.CollectionDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerializeReference(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at WriteAsyncOperationDataToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , ClassDataContract )
   at System.Runtime.Serialization.ClassDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerializeReference(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at WriteAsyncOperationDataToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , ClassDataContract )
   at System.Runtime.Serialization.ClassDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerializeReference(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at WriteAsyncOperationDataToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , ClassDataContract )
   at System.Runtime.Serialization.ClassDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerializeReference(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at WriteAsyncOperationDataToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , ClassDataContract )
   at System.Runtime.Serialization.ClassDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
   at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
   at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
   at Microsoft.Crm.Extensibility.AsynchronousStep.SerializeAsyncData(PipelineExecutionContext context)
   at Microsoft.Crm.Extensibility.AsynchronousStep.Execute(PipelineExecutionContext context)
   at Microsoft.Crm.Extensibility.PipelineInstrumentationHelper.Execute(Boolean instrumentationEnabled, String stopwatchName, ExecuteWithInstrumentation action, PipelineExecutionContext context)
   at Microsoft.Crm.Extensibility.Pipeline.Execute(PipelineExecutionContext context)
   at Microsoft.Crm.Extensibility.PipelineInstrumentationHelper.Execute(Boolean instrumentationEnabled, String stopwatchName, ExecuteWithInstrumentation action, PipelineExecutionContext context)
   at Microsoft.Crm.Extensibility.MessageProcessor.Execute(PipelineExecutionContext context)
   at Microsoft.Crm.Extensibility.InternalMessageDispatcher.Execute(PipelineExecutionContext context)
   at Microsoft.Crm.Extensibility.ExtensiblePlatformMessageDispatcher.Execute(PipelineExecutionContext pluginContext)
   at Microsoft.Crm.Extensibility.ExtensiblePlatformMessageDispatcher.UpdateWithInvocationSource(BusinessEntity entity, FilterExpression filter, Int32 invocationSource, ExecutionContext context)
   at Microsoft.Crm.Extensibility.ExtensiblePlatformMessageDispatcher.Update(BusinessEntity entity, FilterExpression filter, ExecutionContext context)
   at Microsoft.Crm.BusinessEntities.BusinessProcessObject.UpdateWithPipelineAndExtensions(IBusinessEntity entity, ExecutionContext context)
   at Microsoft.Crm.BusinessEntities.BusinessProcessObject.Update(IBusinessEntity entity, ExecutionContext context)
.

The above error message doesn’t really help much as it happens in an internal plug-in.

Also this sentence from the error message didn’t make a lot of sense (at first): Invalid name character in ‘List`1’. The ‘`’ character, hexadecimal value 0x60, cannot be included in a name.

In my code I wasn’t referencing anything that could have a “`” or any other special character that could be messing things up. My code in the pre-validation plug-in was running correctly and I was able to debug it, I just couldn’t debug the pre-operation one.

After a while troubleshooting and nearly giving up, a colleague suggested that I play around with the Shared Variables I was passing between the plugins and bang!!! That was the issue…

I had two values passing via Shared Variables:

  • GUID – created in the Pre-Validation step
  • List<Entity> – records retrieved in the Pre-Validation step

When removing the List object from my Shared Variables, my plug-in started working with no issues and I could even debug my Pre-Operation plug-in.

Why does this happen?

The issue happens due to how the C# language names a generic list object. Running the simple code below, the exception starts making sense:

            List<string> myList = new List<string>();

            myList.Add("value 01");
            myList.Add("value 02");
            myList.Add("value 03");

            foreach (var item in myList)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine(myList.ToString());

Internally, D365 is probably trying to convert the list object into a string (myList.ToString()) to be used in the next plug-in, and due to the special character created by C#, it throws an exception that Dynamics 365 can’t handle.

Conclusion

The conclusion for this is very simple, don’t pass a list of objects via Shared Variables in plug-ins. In my case, I decided to change the retrieve to the Pre-Operation plug-in. Another thing you can try is an array of GUIDs or other array types, just not a generic C# list object.

Posted in JavaScript/jQuery Plugins, Power Apps Portals

Power Apps Portals – Field Label Position

Hi,

In this post I will show you how to set the field label position within an Entity Form/Web Form in Power Apps Portals.

If you are familiar with Dynamics 365, you probably are aware that we can define which position to place a field label within a form. The positions available are:

  • Side: label and input control are positioned side-by-side
  • Top: label and input control are positioned as top-bottom

Unfortunately, Power Apps Portals ignores this definition and always renders your form as top-bottom positioning:

I will show you how to change this behavior to render your field label as side-by-side position. We can achieve this via JavaScript or CSS:

Via JavaScript/jQuery

If you need to set only for a specific form or perhaps specific section in your form, you can use the following jQuery function (just relace the sectionGeneral below for your section name):

$("table[data-name|='sectionGeneral']").find(".control").css("clear", "none");
$("table[data-name|='sectionGeneral']").find(".control").css("float", "right");

Via CSS

If you want to setup this behavior for every Entity Form/Web Form within your Portals, or perhaps for an entire Web Page, you can set it via CSS (you can place this in your .css file or the Web Page custom css field):

.section tbody tr td div.control{
    clear: none !important;
    float: right;
}

Now refresh your Portals Web Page and you will have the below rendered form (don’t forget to clear the cache):

Posted in Portal Management App, Power Apps Portals

Power Apps Portals – Script Error: One of the scripts for this record has caused an error…

Hi

This is a quick post that might help you in case you come across the below error message when using the Portal Management App within Power Apps Portals:

The first time I had this issue it took me a while to figure out what was happening. When viewing the error details, all I could see is that the Portals couldn’t run its OOB JavaScript (even though I hadn’t made any changes to it):

ReferenceError: Web resource method does not exist: adx.adx_webpage.loadResources
at Kl.execute (https://orgf67a233b.crm4.dynamics.com/uclient/scripts/app.js?v=1.4.1024-2006.4:1262:2548)
at https://orgf67a233b.crm4.dynamics.com/uclient/scripts/app.js?v=1.4.1024-2006.4:118:20532
at o (https://orgf67a233b.crm4.dynamics.com/uclient/scripts/app.js?v=1.4.1024-2006.4:289:133)
at $._executeIndividualEvent (https://orgf67a233b.crm4.dynamics.com/uclient/scripts/app.js?v=1.4.1024-2006.4:118:20508)
at $._executeEventHandler (https://orgf67a233b.crm4.dynamics.com/uclient/scripts/app.js?v=1.4.1024-2006.4:118:18113)
at Object.execute (https://orgf67a233b.crm4.dynamics.com/uclient/scripts/app.js?v=1.4.1024-2006.4:118:15469)
at O._executeSyncAction (https://orgf67a233b.crm4.dynamics.com/uclient/scripts/app.js?v=1.4.1024-2006.4:855:692)
at O._executeSync (https://orgf67a233b.crm4.dynamics.com/uclient/scripts/app.js?v=1.4.1024-2006.4:855:419)
at O.executeAction (https://orgf67a233b.crm4.dynamics.com/uclient/scripts/app.js?v=1.4.1024-2006.4:855:201)
at t.dispatch (https://orgf67a233b.crm4.dynamics.com/uclient/scripts/app.js?v=1.4.1024-2006.4:855:5545)

Fixing this problem is actually a lot easier than it looks. The root cause of this is actually an Ad Block extension that you might have installed in your browser. This issue happened to me with a few different extensions in multiple browsers.

The JavaScript used by the Portal Management App probably uses similar functions as common ads all over the internet, so it ends up blocked, causing several issues when trying to configure Portal data.

To fix this all you need is to either remove the extension, or add an exception based on the website URL. This may vary depending on the extension you have installed, in my case I have the AdBlock for Edge, so I can setup this exception using the option “Don’t run on pages on this site.”

Conclusion

If you have this problem, don’t stress, you didn’t do anything wrong – just follow the steps above and the error message will be gone!

Posted in Caching, Power Apps Portals

Power Apps Portals – Caching Tips

My record data is not up to date

My portal configuration is not showing the latest definition

I can’t see the Clear Cache button

The above are very common questions as regards Power Apps Portals Caching. In this post I will give you guys a few tips on how to identify/solve some of these issues.

A few things are very important to know about how Power Apps Portals uses CDS Dataflex Pro data:

  • Power Apps Portals shares the same database as your Model-Driven App, it doesn’t have a database copy and there is no data sync involved
  • A Server-Side Caching is part of the Portals capabilities to improve performance, a message is transferred asynchronously between your Dataflex Pro and the Portals to notify (invalidate) the data once it’s changed
  • The SLA for message transfer is 15 minutes
  • Cache is automatically invalidated when sync transactions are triggered via Portals
  • When a D365 org is reset or restored, cache invalidation can stop working. To enable it, go to Portal Admin Center > Portal details tab > Press Update
  • Clear Cache function is available on <Portal URL>/_services/about (must be logged in as Administrator)
  • No web notification invalidation plugin is required to invalidate cache (this was legacy on ADX Portals)

The above should give you a better understanding of how it works. Let me share a few more tips with you:

Clear Cache function in Bookmark

Add the below JavaScript code into a bookmark in your browser, this will open a separate tab with the Clear Cache page, regardless of which Portals/Page you have opened.

javascript:((function(){window.open(window.location.origin+"/_services/about", "_blank");})())

Clear Cache page

The Clear Cache page shows information about your current Power Apps Portals, like version, Organization ID, etc. Three buttons are available for caching actions:

  • Clear cache: clear cache for both transaction and configuration entities
  • Rebuild search index: rebuild full search index, to be used when Global Search configurations are changed
  • Clear config: clear cache for adx_* entities

Administrator Web Role

If you see a blank page when opening the clear cache page, it means you are not logged in as an Administrator user.

Go to https://make.powerapps.com > Apps > Portal Management App > Contact > find your Contact record and under related entities go to Web Roles. Make sure you have the Administrators Web Roles associated to your Contact.

Clear Cache using Portal Studio – Sync Configuration

Another way to clear the cache is using Portal Studio capabilities, to use this option, go to https://make.powerapps.com > Apps > Select your Portal app and click Edit:

Click on the Sync Configuration button to clear the cache:

Clear Cache using Portal Admin Center

Also, another way to clear the cache is by using Portal Admin Center actions. To use this option, go to https://make.powerapps.com > Apps > Select your Portal app click Settings and click Administration:

On the left menu click on Portal Actions and click the Restart option:

This will restart the website app service and clear the server-side cache.

This option might take your Portal offline for a few minutes, so be aware of that when performing this action.

Can I Clear Cache Programmatically?

No. Currently there is no supported way to clear cache programmatically, so it is not possible to automate or trigger it programmatically.

Retrieving data via FetchXML/Liquid or oData

If you are retrieving data programmatically in the Portals, it’s possible to bypass the cache by making sure your query is always unique. A simple way of achieving this is by adding a filter with a timestamp, for example:

  • oData – JavaScript
var oDataURL = "/_odata/myoDataSet";
var filter = "?$filter=new_name ne '" + new Date().getMilliseconds() + "'";
  • FetchXML – Liquid

In my example, I first create a variable and then add it as a condition in my FetchXML. The only reason I do this is to make it easy to reuse the code in different places, you can even create a Web Template just returning that filter condition and reuse it by using the include tag (maybe this is a topic for another post):

{% assign currentDate = now | date: "yyyyMMddHHmmss" %}
{% assign conditionCache = ' <condition attribute="new_name" operator="ne" value="' | append: currentDate | append: '" />' %}

Then you just add the condition in your FetchXML:

{% fetchxml myFetch %}
      <fetch>
        <entity name="new_entityname">
          <filter type="and">
            {{ conditionCache }}
          </filter>
        </entity>
      </fetch>
{% endfetchxml %}

CSS changes

When making changes related to styling/CSS, your local browser cache might be influencing here as well. You might consider trying an in-private/incognito session or clearing the local browser’s cache.

Thanks Nikita Polyakov for this tip. 

Conclusion

Microsoft is constantly making improvements related to Portal caching. But for now, we still have to live with some of the above issues.

I hope this post has been useful for you to get a better understanding of how Caching works, and how to overcome potential obstacles you might run into along the way.

Posted in JavaScript/jQuery Plugins, Power Apps Portals

Power Apps Portals – JavaScript Tip #01 – Hide & Show Elements

Power Apps Portals allows us to add custom JavaScript/jQuery code to manipulate behaviour within the Portals website.

I am starting a series of quick posts with snippets of JavaScript/jQuery code to help you with your Power Apps Portals implementation.

When talking about client-side customization, there is no single way of interacting with the page elements, there are several ways to achieve same results, in this post I will give an example on how to hide & show elements in your page, so here we go:

Hide & Show Fields

$("#<field name>").closest("td").find("div.control, div.info").hide(); // show();

Hide & Show Section

$("table[data-name='<section name>']").parent().hide(); // show();

Hide & Show Tab

$("div[data-name='<tab name>']").prev("h2.tab-title").hide();  // show();
$("div[data-name='<tab name>']").hide();  // show();

Hide & Show Entity List/Sub-grid column

var list = $(".entity-grid")
list.on("loaded", function () {
	list.find("th:contains('<column display name>')").hide(); // show();
	list.find("td[data-th='<column display name>']").hide(); // show();
}); 

Hide & Show Option Set value

$("#<field name> option[value='< option set value>']").hide(); // show();

Do you have any suggestions or requests for another JavaScript tip? Let me know in the comments below.

Posted in Menu / Navigation, Power Apps Portals

Power Apps Portals – Navigation Menu showing every Web Page

Have you recently come across a situation where after defining the links for your main navigation menu, it suddenly resets on its own showing every custom Web Page you’ve created? Well, in this post I am going to show you how to stop that from happening.

Behind the scenes

First, we need to understand how the menu is structured. A menu is represented by two entities in your CDS environment:

  • Web Link Set: represents a group of links, the main menu for example is represented by the Default Web Link Set
  • Web Link: represents the link to a certain page in your Portal, or an external URL, you can also define an image to be displayed and the order to be shown in your Web Link Set

For more information on managing Web Link Set/Web Link, please refer to the official documentation: https://docs.microsoft.com/en-us/powerapps/maker/portals/configure/manage-web-links.

Finally these entities are represented as custom Liquid objects, being rendered in the Header or Footer Web Template.

What is causing this menu reset?

Now let’s understand exactly what is happening with the Portals.

Microsoft is making a lot of investment in Portals Studio app (https://docs.microsoft.com/en-us/powerapps/maker/portals/portal-designer-anatomy) adding lots of new features on a regular basis. Personally, I am not a big fan of the Portals Studio and I still go to the classic Portal Management app. If you are new to the Portals or just want to quickly update certain content, I completely agree that the Portals Studio interface is much easier and intuitive to make simple changes.

One important (and hidden) feature of the Portals Studio app, is that it automatically refreshes the Default Web Link Set with any custom Web Page you may have created. It doesn’t matter if you’ve created the Web Page via Portal Studio or Portal Management, this seems to happen on the onload event of the Portals Studio, but at the same time it doesn’t show you straight away, only after refreshing the Portals Studio page.

A bit confusing? Let’s try to replicate the issue step-by-step:

  • Open two tabs in your browser, one with your Portals website and the other the Portal Studio App, at this moment the navigation menu should be identical in both tabs
  • Create a new Web Page (can be a blank page), sync and refresh first just the Portals website
  • Now your new Web Page is present in the menu

Now let’s go to the Portal Management App, navigate to the Web Link Set and open the Default Web Link Set. In the Web Links tab, you will see the recently created Web Page there as a new Web Link, even though you didn’t want it to be shown there.

Got it, now what’s the solution?

I know the above text was a bit long, but I think it is important to understand what’s happening in the background. There are a few ways to fix this.

Within the Portals Studio, you can hide the page from showing in the menu, what this will do is deactivate the Web Link record in the CDS, so it won’t show in the menu anymore. Just go to Pages, select the ellipses (…) on your page and click Hide in default menu:

But the problem is still there, if you create new pages it will keep adding to the menu. To get rid of this behavior, we need to change the reference to the Web Link Set. Let’s just forget about the Default Web Link Set and leave the Portals manage it the way it wants, we will be using the Primary Navigation Web Link Set for our menu. In the Portal Management App add/remove any links you want in your menu.

Once the menu has been defined in the Portal Management App, we need to set the Portals to use that Web Link Set, there are two ways of doing this. Please read the entire post before actually making any change in your environment:

Set Navigation Menu via Portals Studio

Open the Portals Studio and click on the main menu, and on the right-hand pane, change the navigation menu dropdown:

Click sync configuration and you’re done!

Set Navigation Menu via Portal Management App / Header Web Template

Go to the Web Templates, open the Header record. Simply change the reference to the Web Link Set, locate the line below, and replace Default for Primary Navigation:

Now clear the cache and don’t worry about this issue again.

Which method should I use?

One thing I noticed is that when changing the navigation menu via Portals Studio, the Portals automatically resets the Header Web Template with the OOB code, changing only the line mentioned above. If you haven’t made any customization in your Web Template, this won’t be an issue, and it is probably easier to change, but if you have made any changes in the Liquid code, you definitely don’t want to lose them, so you’re better off making the change manually in the Web Template.

Apparently this was a bug and it is now fixed in the version 9.2.5.x, although I currently find anywhere in the release notes, when testing this was now updating only the weblinkset assignment, instead of the entire Web Template

Update on 20th July 2020

I see a lot of people having issues with the menu navigation where the pages keep being added, I hope this post clarifies why this is happening and how to solve it.

Posted in Power Apps Portals

Power Apps Portals – Adding Head Meta Tag

Hi, in this post I will talk a bit about HTML Meta Tag and how we can setup custom tags in Power Apps Portals <head> element.

For the purpose of this post, I will create a custom Open Graph Meta Tag to be used in Facebook/Twitter.

What are Meta Tags?

The <meta> tag is used to define metadata about the HTML document. This is commonly used by search engines, browser and other web services.

This tag is never displayed on the page and is an empty element, so there is never a closing tag like </meta>.

Open Graph protocol

Open Graph protocol was introduced by Facebook to enable any page becoming a rich object in a social graph – in simpler words, to display your website in a prettier way when sharing via social media. Today several other social medias and web services use this protocol, such as Twitter/Google+ etc.

By opening Facebook and add the Bing URL, this is the structure we can see on the post:

If we open bing.com and inspect the page, we can actually see the og meta tags defined on the page:

If we simply try to share an OOB Power Apps Portals via Facebook, this is how it would be presented:

Adding Meta Tag to Power Apps Portals

At first it might look tricky to make this change in Power Apps Portals, but it is actually easier than it looks. Power Apps Portals are full of hidden content snippets, not all are documented. One of them is called Head/Bottom and we can use it exactly to perform changes in the <head> element of the Portals website.

If you can’t find this content snippet in your CDS environment, all you have to do is create the record, set it to HTML type and define the tags in the HTML tab of your snippet.

In my example I am adding an image (created via Web File), description and title:

For my image, I tried initially leaving only the relative path (/og-image.png), but it didn’t work, so I had to change to the full image path (https://<portalurl>/og-image.png).

If we now try to share on Facebook, for example, this is how it looks:

By inspecting the Portals website, we can see the tags at the end of the <head> element:

Caching issues

While testing this, one thing I noticed is that Facebook might cache some data on their side, so you are changing the tags on the Portals, just note that it might take a while to replicate on Facebook.

Conclusion

Meta tags are a simple but effective way to give an insight into what your website is about. Give it a try and see what you think!

Posted in Menu / Navigation, Power Apps Portals

Power Apps Portals – Navigation Menu: Setting up a tree structure menu

Hi

In Power Apps Portals, the main navigation menu is represented by the Web Link Set and Web Link objects (entities). A Web Link contains a reference to a Web Page from the Portal or an external URL. The Web Link Set contains a group of Web Links, and can be placed via Liquid template in the Portal.

When setting up Power Apps Portals, by default, it comes with with a few Web Link Sets pre-defined. The Default Web Link Set is used as the primary menu in your Portal. For a better understanding of all the properties of Web Links and Web Link Sets, please refer to the following documentation: https://docs.microsoft.com/en-us/powerapps/maker/portals/configure/manage-web-links.

The way the menu is rendered by default, we cannot have sub-menus or a title to split Web Links. In this post, I will show you a quick tip on how to setup a tree structure for your Portal menu/primary navigation, something like this:

MENU
– – – – – – – – – – – –
 TITLE 01
LINK A
LINK B
 TITLE 02
LINK A
LINK B

Implementation

To achieve this, I am going to make customizations in the Web Link entity. There is no problem modifying the OOB Portal entities, just make sure you add any changed objects to an unmanaged solution when moving to other environments, you can’t export the Portals solution as it is a managed solution.

The code that renders the menu is in Liquid Template, and it’s placed in the Header Web Template, we will also make a few changes there.

By default, if you add a custom field to your Portal entities, it will be reflected in the Liquid objects, so you can easily access the value without writing additional code.

If for some reason you prefer not to change the entity, that's fine, another approach would be when creating your Web Link record, add some tag in the name (for example *menu-title*)

Now let’s jump into the customization:

  • Create a new field in the Web Link entity (I am calling “Display as Title”)
  • Add the new field to the Web Link form
  • I am leaving Page / URL blank, additionally if you want you could add a business rule to hide/show those fields according to the Display as Title value
  • Now open your “Header” Web Template, I am changing the code with the following logic:
    • If my custom field “ollie_displayastitle” is true, display the link as a title instead of an <a> element
    • In my example, I am using a <strong> element, but you could use anything here, preferably you should also add a class from your CSS to get a better look & feel
    • If you didn’t create the custom field and are using the tag like I mentioned *menu-title*, your if condition will be {% if sublink.name contains “*menu-title*” %} and then you also need to remove that using liquid filter {{ sublink.name | remove: “*menu-title* “}}
  • This snippet of code can be found on the line 62 for the Header Web Template (OOB Portals):
 {% for sublink in sublinks %}
  <li role="none">
    {% if sublink.ollie_displayastitle %}
      <strong>{{ sublink.name | default:sublink.title | escape }}</strong> 
      <!-- this can be any element type -->
    {% else %}
      <a 
        role="menuitem" 
        aria-label="{{ sublink.name | default:sublink.title | escape }}" 
        href="{{ sublink.url }}" 
        {% if sublink.Open_In_New_Window %} 
          target="_blank" 
        {% endif %} 
        {% if sublink.nofollow %}
          rel="nofollow" 
        {% endif %} 
        {% if sublink.tooltip %}
          title="{{ sublink.tooltip | escape }}"
        {% endif %}>
        {{ sublink.name | default:sublink.title | escape }}
      </a> 
    {% endif %}
  </li>
{% endfor %}
  • This is the final result:

Conclusion

By customizing Portal entities and existing Web Templates, we are not only making customization to the Portals but also extending its original functionality.

This post idea came after seeing a few questions on the communities about changing the way the menu is rendered. I hope this post encourages you to make changes to the way the menu is rendered OOB.

Posted in Entity List, Export Content, Power Apps Portals

Power Apps Portals – Generate and Download Word Document from an Entity List

Hi

I recently came across an interesting requirement that I thought would be worth sharing here. Yet again I will be working with Entity Lists, and some implementations will be used from previous posts.

Business Requirement:

  • Display list of records in the Portal
  • Allow users to download a document with record details (including child entities)
  • Document should be (preferably) Word format
  • The document should also be available in D365

Before we dive into the details, here is a sneak peek of what will be achieved by the end of this post:

To achieve this, I will use the following components:

  • Web File with the Word icon
  • Web Page and Entity List for the Contact entity
  • Entity List actions
    • View record details
    • Run Workflow (to generate the Word Document)
  • Entity Permissions
  • Custom entity (Application) with the following relationship:
    • Contact 1:N Application
  • Word Template against the Contact record, displaying contact details and a list of Applications
  • Workflow to set generate Word Template against the Contact record
  • CSS customizations to display my workflow actions as icons
  • JavaScript code to dynamically create the download button

Implementation

My overall approach for this will be using as much as possible existing D365 features, I won’t write any custom code in D365, only client-side code in the Portals will be necessary.

  • Web File:

As I want my Entity List to display a Word Icon, I am creating a Web File and uploading the icon from IconFinder.com

  • Web Page/CSS:

The only customization I am doing around my Web Page is the CSS to display the entity list actions as icons, you can view more details on how to achieve this in the following post: https://oliverrodrigues365.com/2020/05/10/power-apps-portals-adding-icons-to-entity-list-action-buttons-via-css/.

I want to use a Word icon for my “Generate Document” workflow action in my entity list, so I am adding one more class to my CSS, this is to set the height and position of my image (you wouldn’t need this if you were using icons within the bootstrap/glyphicon):

.view-grid .dropdown.action .dropdown-menu .workflow-link .entitylist-icon>img {
    max-height: 18px;
    margin-top: -9px;
}
  • Entity List:

My Entity List is simply pointing to the Active Contacts view, and I am assigning the following Actions against it:

  • Details action redirecting to a new Web Page to display record details
  • Workflow action triggering my custom workflow to generate the document, on the Button Label I am adding my custom CSS class and image:
<span class="fa fa-fw entitylist-icon" aria-hidden="true">
    <img src="icon-word.png"/>
</span>
  • Entity Permissions:

The Word document will be generated as a Note attached to my Contact record in D365, for this reason we need to have an entity permission for the Note entity, this is a child entity permission against my Contact entity permission, for more details on parent/child entity permissions please refer to the following documentation: https://docs.microsoft.com/en-us/powerapps/maker/portals/configure/assign-entity-permissions

  • D365 Application Entity / Contact Entity

I have a custom entity called Application, with some very simple fields for this demo such as ID, Status, Type and Created On.

Another customization I am making is adding a custom field (Text/URL) in my OOB Contact entity to store the URL of my document, I am calling this “Generated Document URL”.

Finally make sure this URL field is available in your view being displayed on the Portal, in my case the Active Contacts view. Don’t worry, we will hide the column via JavaScript, but this will be important on a later stage.

  • Word Template

I am using the OOB Word Template feature to generate my document. What I like about this is that we can generate the document manually via D365 or through a workflow, which is perfect for my scenario. For more details on how to create the Word Template please refer to the following: https://docs.microsoft.com/en-us/power-platform/admin/using-word-templates-dynamics-365.

My template will display a logo image, the Contact name and e-mail and a list of the existing Applications.

  • Workflows

We need two sync workflows to achieve our need. Here I will describe each of the workflow steps:

Generate Word Document
Sync Workflow
Trigger: On-Demand
Entity: Contact
Scope: Organization
Steps: 
 - Perform Action: SetWordTemplate (pass the contact record and set the Word Template created as actions parameters)

The SetWordTemplate is an OOB action that creates a note against the record with the generated Word Document.

A note record in your Portal can be accessed via the following URL pattern: <portalurl>/_entity/annotation/<note guid>, so now we need to generate the URL against the Contact record. For this I am creating the below workflow:

Set Contact Generated Document URL
Sync Workflow
Trigger: Record is created
Entity: Note
Scope: Organization
Steps: 
 - Validate if the Regarding field of the note is a Contact
 - Validate if the File Name is <your word template name> (you can make better validations, I am going for simple ones for this demo)
 - Now we need the note GUID, to avoid code I am using the D365 Workflow Tools solution: https://github.com/demianrasko/Dynamics-365-Workflow-Tools/blob/master/docs/GetRecordID.md but you could also write your own custom code to retrieve the record GUID
 - The next step is to update the related Contact record with the URL pattern + Note GUID. All we need here is the relative path, no need for the Portal root URL (as this might change between environments or other reasons)
  • Entity List JavaScript:

At this point we have the core of our development done. If you navigate to your Web Page you should have the Word icon to generate your document, and once triggered, the URL column from your view, once empty, should get populated with the document URL, if you click that URL you should be able to download your document.

Now we need to add a JavaScript logic, attached to the Entity List Load event, that will perform the following actions:

  • Hide URL column
  • For each row:
    • Get the URL from the “Generated Document URL” attribute
    • If this contains data, create dynamically an element in the same structure as the other elements
    • Append new element to the workflow links so it will be the last action

The following JavaScript code can be placed in the Entity List custom JavaScript section:

$(document).ready(function() {
    SetDownloadButton();
});

SetDownloadButton = function() {

    var entityList = $(".entitylist.entity-grid").eq(0);

    entityList.on("loaded", function() {

        // hide url column 
        entityList.find("table thead th").eq(4).hide();
        entityList.find("table tbody tr").each(function() { $(this).find("td").eq(4).hide(); });

        entityList.find("table tbody > tr").each(function(index, value) {
            var tr = $(this);

            var documentUrlAttribute = tr.find('td[data-attribute="ollie_generateddocumenturl"]');

            if (documentUrlAttribute.length > 0) {
                
                var documentUrl = $(documentUrlAttribute).attr("data-value");

                var downloadElement = "";
                downloadElement += "<li>";
                downloadElement += "    <a href='" + documentUrl + "' target='_blank'>"
                downloadElement += "        <span class='fa fa-download fa-fw' aria-hidden='true'/>";
                downloadElement += "    </a>";
                downloadElement += "</li>";

                var generateWord = tr.find(".dropdown-menu");
                generateWord.append(downloadElement);
            }
        });
    });
};

Now after refreshing the cache and your Web Page you should see the below behavior:

  • Caching Issues?

We all know the Portals have some caching issues, but this shouldn’t be an issue with the above implementation. For any actions triggered by the Portals, the cache is automatically refreshed for that record, as in our scenario we are using sync workflows, the cache gets refreshed within the same transaction.

Conclusion

My example was specific to generate a Word document using a Word Template in D365, but this approach could be used for several other requirements where you have a workflow updating the main record in real-time, and appending a dynamic link to anything on your entity list.

Have you ever had a similar requirement? Please comment below with how you implemented it.

If you find this post useful feel free to like and share it.

Posted in Entity List, Power Apps Portals

Power Apps Portals – Adding Icons to Entity List Action buttons via JavaScript

Hi

In my last post, I showed how to change the Action buttons from an Entity List to be displayed as icons instead of the usual dropdown using only CSS, you can check the details here: Power Apps Portals – Adding Icons to Entity List Action buttons via CSS.

But if we have too many Actions setup in our Entity List, the page gets very busy, so it may not be ideal. In this post I am going to show another way to achieve a similar result using JavaScript/jQuery, but this time we will leave the main actions (Details/Edit/Delete) as icons, and the remaining in the dropdown.

So I am going to remove the CSS from my Web Page, and my Entity List is going back to this state:

icon_css_01

If you didn’t see my previous post, what I have here is a simple Entity List pointing to my Active Accounts view from my CDS environment, and I have a few actions setup as part of my Entity List (Edit/View Details/Delete/Run Workflow to send an e-mail).

Now it’s time to write the JavaScript, there are tons of ways to approach this, I will describe the actions I am performing in my JavaScript:

  • Validate that my list contains actions associated
  • Create an object with the rows from the list
  • Start looping the list rows
    • Create an object with the actions for that row (only actions for Edit/Details/Delete)
      • Start looping the actions
        • Create an object to store the span class of the action, which contains the icon
        • Create dynamically a new <span> with the previous class and add that to the main action element
        • Via JS I am adding some styling, but you can also set a class from your CSS and reference it here, you can also change those properties if you prefer the icons bigger/smaller
        • Remove the old action element
      •  Create an object with the actions for that row (Workflow)
      • Start looping the actions
        • Here I will replace the current <div> element for a new <a> element
        • Again I am manually applying some styling that could be in the CSS
        • Move the <a> element to the far right by appending to the previous object
      • Finally we can remove the old dropdown button completely
$(document).ready(function () {
    ChangeGridButtons();
});
ChangeGridButtons = function () {
    $(“.entity-grid”).on(“loaded”, function () {
        if ($(this).find(“.view-grid .table tbody tr td:last-child ul.dropdown-menu > li > a.details-link, .view-grid .table tbody tr td:last-child ul.dropdown-menu > li > a.edit-link, .view-grid .table tbody tr td:last-child ul.dropdown-menu > li > a.deactivate-link, .view-grid .table tbody tr td:last-child ul.dropdown-menu > li > a.delete-link, .view-grid .table tbody tr td:last-child ul.dropdown-menu > li > a.disassociate-link”).length > 0) {
            var rows = $(this).find(“.view-grid .table tbody tr td:last-child”);
            $.each(rows, function (index, row) {
                var actions = $(row).find(“ul.dropdown-menu > li > a.details-link, ul.dropdown-menu > li > a.edit-link, ul.dropdown-menu > li > a.deactivate-link, ul.dropdown-menu > li > a.delete-link, ul.dropdown-menu > li > a.disassociate-link”);
                $.each(actions, function (index, action) {
                    var li = $(action).parent();
                    var iconClass = $(action).find(“span”).attr(“class”);
                    $(action).append(“<span class='” + iconClass + “‘></span>”);
                    $(action).append($(action).find(“span”));
                    $(action).css(“font-size”, “18px”);
                    $(action).css(“text-decoration”, “none”);
                    $(action).css(“padding-right”, “4px”);
                    $(row).append($(action));
                    li.remove();
                });
                var actions = $(row).find(“ul.dropdown-menu > li > a.workflow-link”);
                if (actions.length > 0) {
                    var divDropDown = $(row).find(“div.dropdown”);
                    $(divDropDown).css(“display”, “unset”);
                    $(divDropDown).append(“<a class=’dropdown-link’></a>”);
                    var aDropDown = $(divDropDown).find(“a.dropdown-link”);
                    $(aDropDown).attr(“aria-expanded”, “false”);
                    $(aDropDown).attr(“data-toggle”, “dropdown”);
                    $(aDropDown).css(“text-decoration”, “none”);
                    $(aDropDown).css(“cursor”, “pointer”);
                    $(aDropDown).append($(divDropDown).find(“span”));
                    // move dropdown to the far right
                    $(divDropDown).appendTo(row);
                }
                $(row).find(“div.dropdown”).find(“button”).remove();
            });
        }
    });
};

You can place the above code in the Entity List or Web Page custom JavaScript section, and now this is how our Entity List looks:

icon_js_cover_01

JavaScript VS CSS – Which one is better?

Well, there is no right or wrong, it really depends on your scenario/requirement.

Performance wise we can expect the CSS method would be better, but usually you won’t have an Entity List displaying a large number of records per page, by default an Entity List displays 10 records per page, so the JavaScript should run quick enough. It also depends on what you are most comfortable with, performing style changes or code changes.

I hope you find this post useful for your Portals project.