How to use C# Web API in Dynamics 365

1.2k views Asked by At

I am using online instance of Dynamics 365. I have created C# Web API to export data from activity entity. When I am running it from visual studio it's working fine.

Now I want to call it on button click in Dynamics 365. The requirement is that when user click on the button then the Web API should be call and data will be exported. I don't have idea, how to get this task done. can anyone help me to solve this problem. kindly provide me steps to get this task. Web API code is given below

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.ServiceModel;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Services;
using Microsoft.Xrm.Sdk;
using System.Windows.Forms;

namespace Experiments
{
    class Program
    {
        private static OrganizationService _orgService;
        static void Main(string[] args)
        {
            try
            {
                CrmConnection connection = CrmConnection.Parse(ConfigurationManager.ConnectionStrings["CrmOnline"].ConnectionString);

                using (_orgService = new OrganizationService(connection))
                {

                    var exportToExcelRequest = new OrganizationRequest("ExportToExcel");
                    exportToExcelRequest.Parameters = new ParameterCollection();
                    //Has to be a savedquery aka "System View" or userquery aka "Saved View" 
                    //The view has to exist, otherwise will error out
                    exportToExcelRequest.Parameters.Add(new KeyValuePair<string, object>("View", new EntityReference("savedquery", new Guid("{00000000-0000-0000-00AA-000010001902}"))));
                    exportToExcelRequest.Parameters.Add(new KeyValuePair<string, object>("FetchXml", @"<?xml version='1.0'?>
                    <fetch distinct='false' mapping='logical' output-format='xml-platform' version='1.0'>
                       <entity name='activitypointer'>
                          <attribute name='subject'/>
                          <attribute name='ownerid'/>
                          <attribute name='prioritycode'/>
                          <attribute name='regardingobjectid'/>
                          <attribute name='activitytypecode'/>
                          <attribute name='statecode'/>
                          <attribute name='scheduledstart'/>
                          <attribute name='scheduledend'/>
                          <attribute name='activityid'/>
                          <attribute name='instancetypecode'/>
                          <attribute name='community'/>
                          <attribute name='senton'/>
                          <attribute name='statuscode'/>
                          <order descending='false' attribute='scheduledend'/>
                          <filter type='and'>
                             <condition attribute='actualdurationminutes' value='43800' operator='le'/>
                          </filter>
                          <link-entity name='systemuser' alias='activitypointerowningusersystemusersystemuserid' link-type='outer' visible='false' to='owninguser' from='systemuserid'>
                              <attribute name='internalemailaddress'/>
                          </link-entity>
                          <link-entity name='email' alias='email_engagement' link-type='outer' visible='false' to='activityid' from='activityid'><attribute name='isemailfollowed'/>
                             <attribute name='lastopenedtime'/> 
                             <attribute name='delayedemailsendtime'/>
                          </link-entity>
                       </entity>
                   </fetch>"));
                    exportToExcelRequest.Parameters.Add(new KeyValuePair<string, object>("LayoutXml", @"
                    <grid name='resultset' object='2' jump='fullname' select='1' icon='1' preview='1'>
                        <row name='result' id='activitypointerid'>
                            <cell name='activitytypecode' width='150' />
                            <cell name='statecode' width='112' />
                            <cell name='scheduledstart' width='110' />
                            <cell name='scheduledend' width='110' />
                        </row>
                    </grid>"));
                    //need these params to keep org service happy
                    exportToExcelRequest.Parameters.Add(new KeyValuePair<string, object>("QueryApi", ""));
                    exportToExcelRequest.Parameters.Add(new KeyValuePair<string, object>("QueryParameters",new InputArgumentCollection()));
                    var exportToExcelResponse = _orgService.Execute(exportToExcelRequest);
                    if (exportToExcelResponse.Results.Any())
                    {
                       File.WriteAllBytes("Activities.xlsx", exportToExcelResponse.Results["ExcelFile"] as byte[]);
                    }
                }
            }
            catch (FaultException<OrganizationServiceFault> ex)
            {
                string message = ex.Message;
                throw;
            }
        }
    }
}

Thanks.
2

There are 2 answers

1
Dave Clark On

I'd recommend you compile your C# code as an Action and include it as a step in a workflow. See here on how to invoke a custom action from a workflow.

I'd then recommend you install the Ribbon Workbench. This will let you customise your forms and navigations to add one or many buttons. You can use the workbench to customise these buttons, setting their commands to call your workflow which in turn calls your Action (your C# code).


Note there are several solutions to achieve what you're asking, I've just suggested one. Other solutions would likely include JavaScript and calling the Web API client-side.

0
Kelvin On

Since you are using Dynamics 365 online, I will recommend you to create a Microsoft FLOW App with a CDS connector. Hope this helps.