Microsoft Dynamics CRM display error returned from plugin through javascript - dynamics-crm-2011

I am using Microsoft Dynamics CRM (off premise)
Microsoft Dynamics® CRM Online Spring '14 (6.1.0.575)
Via the javascript SDK making a call to create an entity which fires off a plugin. We do our custom validations in the plugin in pre-validation.
Javascript create call example from here -> http://msdn.microsoft.com/en-us/library/gg334427.aspx
//Create the Account
SDK.REST.createRecord(
account,
"Account",
function (account) {
writeMessage("The account named \"" + account.Name + "\" was created with the AccountId : \"" + account.AccountId + "\".");
writeMessage("Retrieving account with the AccountId: \"" + account.AccountId + "\".");
retrieveAccount(account.AccountId)
},
errorHandler
);
And then I can handle the error using that errorHandler function, like this:
function errorHandler(error) {
writeMessage(error.message);
}
However, I am trying to get the error to display in the CRM error dialog box from InvalidPluginExecutionException. It displays it when I create the entity from a form, but when I make the call through javascript I can't seem to get it to display in the CRM error dialog box. I want to keep with the CRM theme, not use alert() in javascript, and have users be able to download the full exception that we are sending back.
Is it possible to call the dlg_error.aspx page in CRM and populate it with our error message? I am grasping at straws right now, anything would help out a lot. Thanks!

If you are using CRM 2013, I would suggest you to use Workflow instead of JavaScript to create record.
Create a new workflow and un-tick the checkbox "Run this workflow in backgroung (recommended)".
Create record from newly created workflow.
Save and publish the record.
Now go the the ribbon and select 'Run Workflow'.
Select the newly created workflow and click 'Add'.
If there is an error thrown by Plugin, It will be displayed in standard CRM Error dialog box which will allow you to download the log file.

You can try to execute a synchronous jQuery ajax method, without catching error and see what happens. Creating a record from jScript you are using RESTful endpoint of CRM service, I am not sure if the error is going to be promoted in the same way. Try to use Fiddler if you would like to try opening error dialog yourself. Using new synchronous workflow feature might also do the trick.

Related

Can Custom Action Buttons run javascript in handler? Sharepoint add-in

I created a Custom Action Ribbon button for sharepoint online and i want to run a javascript code when the button is clicked.
Sharepoint documentation even provides an example of it: https://learn.microsoft.com/en-us/sharepoint/dev/schema/commanduihandler-element?redirectedfrom=MSDN#example
but when i'm trying it always returns an error Custom action urls must start with "http:", "https:", "~appWebUrl" or "~remoteAppUrl".
Another part of the documentation says that it is not possible https://learn.microsoft.com/en-us/sharepoint/dev/sp-add-ins/sharepoint-add-ins-ux-design-guidelines?redirectedfrom=MSDN#figure-4-a-custom-action-in-the-contextual-menu
So how do i make it work? is not possible anymore and only can do redirections?
or it deppends of the location? i have it defined as <CommandUIDefinition Location="Ribbon.Documents.Actions.Controls._children"> so it is displayed in the command bar.
is it possible? ... I suppose no
Unfortunately it is not possible to add a custom ribbon action with a javascript logic with a provider hosted add-in 🤔. I think the articles/links where you found it is possible refer to the Server ribbon xml custom action that could be modified using sandbox solutions (like the old school SharePoint days 😊), but now the sandbox is rather not supported in SP online.
For the Ribbon custom actions that are added with the add-in you should specify the direct link. This is already what needs to be specified when we add a Ribbon action in VS to the Add-in project (we should specify were we navigate to)
I also found this MSDN article (quite up to date - from 2020) where we may find:
CustomAction cannot contain JavaScript: Any UrlActions or CommandActions must be a URL to navigate to. (...)
So I am like 95% sure it should 😉 not be possible... but I leave the 5% as I am not like an SP PRO (I think it is hard to be one as it is like sooooo much to know 😋)
possible solution you might take
What you might do is to add the custom Ribbion xml using PowerShell and attach any javascript logic to it also using PowerShell 😋. The only drawback is that the javascript file needs to be also somehow added to the page (like it could be stored in the SiteAssets library).
So to do that we need to:
create an xml file locally with our Ribbon command button like:
<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition Location="Ribbon.Library.ViewFormat.Controls._children">
<Button Id="Ribbon.Library.ViewFormat.About"
Command="TestButton"
LabelText="Test"
Image32by32="{SiteUrl}/_layouts/15/1033/Images/formatmap32x32.png?rev=23"
Image32by32Top="-273"
Image32by32Left="-1"
Description="Test"
TemplateAlias="o1" />
</CommandUIDefinition>
</CommandUIDefinitions>
<CommandUIHandlers>
<CommandUIHandler
Command="TestButton"
CommandAction="javascript:test({SelectedItemId});"
EnabledScript="javascript:checkOneItemSelected();" />
</CommandUIHandlers>
</CommandUIExtension>
the output of the above will be a button like this
Next create a js file (also locally) with functions for the CommandAction and EnabledScript (so we need a test() function and checkOneItemSelected()). So the contents like
function test(itemId) {
alert(itemId);
}
function checkOneItemSelected() {
return (SP.ListOperation.Selection.getSelectedItems().length == 1)
}
... so locally I have two files
Now we need to connect to the site we want to add the Ribbon button using PowerShell (best would be to use PnP Powershell 👍)
connect to site using Connect-PnPOnline -Url <SiteUrl>
now lets add the JS local file to the site assets library like Add-PnPFile -Path .\customJS.js -Folder "SiteAssets"
so the output is (the file in the library)
now lets add the Ribbon button to the site (using xml) like
$ribbon = Get-Content .\CustomRibbonButton.xml
$ribbon = [string]$ribbon
Add-PnPCustomAction -Name "RibbonTester" -Title "RibbonTester" -Description "-" -Group "Tester" -Location "CommandUI.Ribbon" -CommandUIExtension $ribbon -RegistrationType ContentType -RegistrationId 0x0101
so the output of the above will be our button in the ribbon (also we need to turn on classic UI /off modern UI, to see the ribbon 😉)
now lets attach our JS to the button like Add-PnPJavaScriptLink -Name "AboutButtonScript" -Url https://tenanttocheck.sharepoint.com/sites/ClassicDeveloperSite/SiteAssets/customJS.js -Scope Web please be aware the change url to your tenant😉
and the output is like
did you consider🤔
Also did you consider to use spfx extensions and modern UI to be more up to date? In extensions you may use JS and maybe do some http request to some endpoint you want to target with the ids array (but this is only a suggestion)
hope my post will be of any help 👍
BR

Dynamics CRM Dialog hangs/freezes when called via script

when dialog process is called from a script that is embedded on a ribbon button, The dialog freezes and enter into a not responding state.
I just figured out that When calling the dialog via script check the ObjectId Guid that it passes. If the provided Guid does not exist on CRM Database the dialog will hang without giving any error. This may happen if you want to create a dialog that do not need a entity record to run against. In this type of case you just want an inactive record to appointed as ObjectId.
function CallDialog()
{
var clientId = Xrm.Page.context.getClientUrl();
var url = clientId + "/cs/dialog/rundialog.aspx?DialogId=%7b460ACCDC-701C-4947-8E72-CDE2C53807FC%7d&EntityName=EntityName&ObjectId=%7b115fbb02-b5a5-e711-8122-005056b32967%7d";
window.open(url,"", "width=700,height=600");
}

Authenticating a REST request in an Excel Add-in

I am trying to develop an add-in for Excel with the goal that it will create calendar events based on data inside a spreadsheet.
I can do almost everything that I want except use the REST API to build the events in the calendar and I can't exactly figure out where I went wrong.
I have followed the documentation suggested by #MarcLaFleur.
I can build and run the application no problem, but when I click on the 'Get my files from OneDrive' button, I get the following:
Code: 5001
Message: An internal error has occurred.
name: Internal Error
This is coming from the program.js file in the public directory somewhere in the else clause of this function.
function getDataWithoutAuthChallenge() {
Office.context.auth.getAccessTokenAsync({ forceConsent: false },
function (result) {
if (result.status === "succeeded") {
// TODO1: Use the access token to get Microsoft Graph data.
accessToken = result.value;
getData("/api/onedriveitems", accessToken);
}
else {
console.log("Code: " + result.error.code);
console.log("Message: " + result.error.message);
console.log("name: " + result.error.name);
document.getElementById("getGraphAccessTokenButton").disabled = true;
}
});
}
Here are the scopes in my manifest.xml
...
<WebApplicationInfo>
<Id>c931b396-7 ... </Id>
<Resource>api://localhost:3000/c931b396-7 ... </Resource>
<Scopes>
<Scope>files.read.all</Scope>
<Scope>profile</Scope>
</Scopes>
</WebApplicationInfo>
</VersionOverrides>
And here are the scopes on apps.dev.microsoft.com:
If you can shed any light for me, it would really help me out.
5001 can be caused by not requesting profile scope. You need to request the profile scope in addition to Calendar.ReadWrite. You do this when you register the app, as well as in the manifest. For more information, see the articles that Marc LaFleur linked to.
The 5001 error often suggests something fundamentally wrong with the add-in API in Office. For example, your Office app doesn't support the API, the manifest is incorrect, or the version of office.js doesn't work with it. Since you're using the sample, two things come to mind:
You aren't running the latest Insiders
build
The wrong manifest is getting loaded (this sometimes happens if you're
on Windows and using a version of Visual Studio 2017 that has old
schema files, so you have to do a post-build clean up of the debug
Manifest XML)
Your manifest and Azure registration look mostly good, though Rick's comment about Scopes is relevant. profile must work with openid as a pair (profile alone won't work; openid alone won't work), and as discussed you need this consented. As the developer, you can try consenting for yourself at the protocol level. You’ll want to update the client_id, redirect_uri, and scope query parameters as appropriate, and add &prompt=consent.
To answer a later question, Excel and Mail add-ins are different, and my answer only applies to Excel. For Outlook there's a different sample.
The documentation can be found at Enable single sign-on for Office Add-ins. There is also walk though for both ASP.NET and Node.js as well documentation on Troubleshooting.
There are a number of things that could be going wrong here but without knowing more about your registration it is difficult to determine. That said, here are a couple of common mistakes:
You'll need to make sure you receive Admin Consent for the tenant you're developing against. This is only a dev requirement and won't be required once your publish to the Store.
Make sure you've pre-authorized the correct applications. You'll need pre-authorizations for:
d3590ed6-52b3-4102-aeff-aad2292ab01c (Microsoft Office)
57fb890c-0dab-4253-a5e0-7188c88b2bb4 (Office Online)
bc59ab01-8403-45c6-8796-ac3ef710b3e3 (Office Online)
Make sure the scopes you're defining in your manifest.xml are reflected in the app registration at apps.dev.microsoft.com.
If you make changes to your permission scopes, you need to make sure you repeat the Admin Consent process. When you receive consent, they are consenting to the scopes that were registered at the time of consent rather than the App ID itself.

How to hide my app's calendar from built-in calendar app?

My app needs an internal calendar. I can create a new calendar like this:
var store = await AppointmentManager.RequestStoreAsync(AppointmentStoreAccessType.AppCalendarsReadWrite);
var cacheCalendar = await store.CreateAppointmentCalendarAsync("unique name here");
This succeeds and I get a new calendar. But this calendar is visible in the phone's built-in calendar app. I don't want this calendar to be visible since it's for internal bookkeeping.
So I try to hide the calendar like this:
var store = await AppointmentManager.RequestStoreAsync(AppointmentStoreAccessType.AppCalendarsReadWrite);
var cacheCalendar = await store.CreateAppointmentCalendarAsync("unique name here");
cacheCalendar.IsHidden = true; // <---- make calendar hidden
await cacheCalendar.SaveAsync(); // <---- save; error here
When calling SaveAsyncI get the following exception:
Access is denied. (Exception from HRESULT: 0x80070005
(E_ACCESSDENIED))"
Why can't I hide my calendar from the built-in phone calendar app? Is this an undocumented limitation? Are there other ways to do this?
(Note: I tested this on a Windows 10 Mobile as well as desktop Win 10 - same error.)
Edit/Addition: Since Anthony discovered the IsHidden property is documented as read-only in MSDN here is a screenshot from Visual Studio showing the public setter (which makes it compile, run and seemingly legit to call):
(The app targets Win 10 Build 10586 - maybe it's new, but unfinished?)
Honestly I am surprised this even compiles.
According to the MSDN documentation for AppointmentCalandar
IsHidden - Read-only - Gets whether the AppointmentCalendar is hidden in
the device's built-in calendar UI
This is a read only property and can't be set.
As for your actual question, after carfully reviewing the documentation it appears that this is an oversight in the API. I would raise this concern on the MSDN forums.
This was a bug in 10586 but if you’re using 14393 SDK you can use IsHidden if your app has rights to the calendar without an InvalidAccessException
https://wpdev.uservoice.com/forums/110705-universal-windows-platform/suggestions/15278775-appointmentcalendar-ishidden-setter-throws-a-inval

Sharepoint task list doesn't send email on item creation

I've created a custom workflow which creates a task item when the workflow is kicked off.
alt text http://img19.imageshack.us/img19/2862/screenshot310200942100p.png
I've also created a few custom content types for the document library and task list.
For the document library:
First, I add a document library and configure it to allow custom content types. Then I add my content type, which is based off the document content type. After, I add a workflow under workflow settings. Here, I select my custom workflow, give it a name and tell sharepoint to create a New task list to store the tasks in.
For the task list:
Now that I have a sharepoint created task list, I go there and allow custom content types and make sure "Send e-mail when ownership is assigned?" is set to Yes. Then I add my two custom content types which are both based off a workflow task content type. Thats all I should do.
When I start my workflow, it does add the approval task (I'm using a CreateTaskWithContentType activity which is named createApprovalTask), but no email is sent out for the created task.
The code I'm using in the createApprovalTask activity is:
// make a new GUID for this task
createApprovalTask_TaskId = Guid.NewGuid();
// set simple properties of task
createApprovalTask.TaskProperties.AssignedTo = "a valid domain\user";
createApprovalTask.TaskProperties.Title = "Review Contract: " + approvalWorkflowActivated_WorkflowProperties.Item.DisplayName;
createApprovalTask.TaskProperties.SendEmailNotification = true;
If I create a document library and use one of Sharepoint's built-in workflows (Approval for example), and tell it to create a task list for it, when an item is added to that list, it sends out the email correctly. So, the setting for the outgoing mail server are correct, as we're receiving other emails just fine.
I'm using a SendEmail activity right after the createApprovalTask activity to send an email back to the submitter telling them we've received their approval request. The code for that is something similar to:
sendApprovalRecievedEmail.Body = emailBody;
sendApprovalRecievedEmail.Subject = emailSubject;
sendApprovalRecievedEmail.To = emailTo;
sendApprovalRecievedEmail.From = emailFrom;
This works, so the submitter receives their custom email, but the task owner never receives the task item email.
Unfortunately, our mail servers were blocking the emails for some reason. I wasted a good 2 1/2 days searching around for this problem...and it turns out our IT department didn't have their sh*t together.
Thanks everyone.
you have to make sharepoint outgoing email settings properly.
example is shown in below link
http://sharepoint-amila.blogspot.com/2008/02/outgoin-email-settings.html
if you need to send an email through the c#.net code you can use below method to send emails in custom workflows.
SPUtility.SendEmail Method (Microsoft.SharePoint.Utilities)
example is shown in below link
http://www.sharepoint-amila.blogspot.com/
Is it possible to point out a SharePoint user by "domain\user" like you do with createApprovalTask.TaskProperties.AssignedTo? Isnt the ID required?
"id;#domain\username"

Resources