Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

CRUD operations using web api in console app

Posted on by 195

Hi Friends,

Follow the below steps to do CRUD operations in console app using web api.

Step 1: Go to https://portal.azure.com

08500.1.PNG

Click on Azure Active Directory, next Click on App registrations

Click New Application Registration

22464.2.PNG

Next fill the details and click on create

8055.3.PNG

Next click on "all Apps"

5811.4.PNG

Open "Sample App" click on settings then Click on "Required permissions"

8228.5.PNG

Click on Add button and add "Dynamics CRM Online" and give "DELEGATED PERMISSIONS" and Click "Save"

2043.6.PNG

Now Come back to "Keys" and create secret Key, when you click on save secret key will be generated then copy that key in notepad

4643.7.PNG

Go Back to App and copy application id in notepad

1104.14.PNG

Click on endpoints and copy "OAUTH 2.0 AUTHORIZATION ENDPOINT"

6710.8.PNG

Come back to Active Directory and create User in Azure and copy password in notepad

7041.9.PNG

Step 2:

Come back to CRM and go to users.

In the view Click on "Application user" and click on "+ new button".

2664.11.PNG

username and primary email should be same as that we created in Azure.

3731.10.PNG

Paste the application id which we copied to the notepad and click on save then give admin role for that user.

Configuration part is completed now coming to the coding part. Create new class(ex : webapihelper)

step 3:

=============================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Net;
using Newtonsoft.Json.Linq;

namespace CRUD_Using_Web_Api
{
class webapihelper
{
string _ClientId = "cefc4d69-0008-4841-a38f-81cf2c29a2e8";
string _ClientSecret = "15Dt6Kc31N8/D4M0zVoIZ6jyyvxwmwHJB+Kre1DIxow=";
string _Resource = "delldell.api.crm8.dynamics.com";
string _Authority = "login.microsoftonline.com/.../authorize";
string _Api = "delldell.api.crm8.dynamics.com/.../v9.1";
string accounturi = string.Empty;

public HttpClient GetHttp()
{
HttpClient httpClient = new HttpClient();
AuthenticationContext authContext = new AuthenticationContext(_Authority);
AuthenticationResult authResult;
ClientCredential credentials = new ClientCredential(_ClientId, _ClientSecret);
try
{
authResult = authContext.AcquireToken(_Resource, credentials);
httpClient.BaseAddress = new Uri(_Resource);
httpClient.Timeout = new TimeSpan(0, 2, 0);
httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;


return httpClient;
}
catch (Exception ex)
{
return null;
}
}

public async Task CreateContactOld(HttpClient httpClient)
{
string accounturi = string.Empty;

JObject account = new JObject();
account.Add("name", "delldell");
account.Add("telephone1", "9874561230");
account.Add("websiteurl", "www.delldell.com");
account.Add("address1_city", "Hyderabad");
HttpRequestMessage request1 = new HttpRequestMessage(HttpMethod.Post, "delldell.api.crm8.dynamics.com/.../accounts");
request1.Content = new StringContent(account.ToString(), System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage response1 = await httpClient.SendAsync(request1);
if (response1.StatusCode == HttpStatusCode.NoContent)
{
Console.WriteLine("Account created" + account.GetValue("name"));
// Console.Read();

HttpResponseHeaders responseheaders = response1.Headers;
accounturi = responseheaders.Location.AbsoluteUri;
}
else
{
Console.WriteLine("failed to create Account");
}
//update
JObject accountupdate = new JObject();
accountupdate.Add("name", "ABC");
accountupdate.Add("telephone1", "5588223");
accountupdate.Add("websiteurl", "www.abc.com");
accountupdate.Add("address1_city", "Banglore");
HttpRequestMessage updateRequest1 = new HttpRequestMessage(new HttpMethod("PATCH"), accounturi);
updateRequest1.Content = new StringContent(accountupdate.ToString(), System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage updateResponse1 = await httpClient.SendAsync(updateRequest1);
if (updateResponse1.StatusCode == HttpStatusCode.NoContent) //204
{
Console.WriteLine("Account updated");
HttpResponseHeaders responseheaders1 = updateResponse1.Headers;
accounturi = responseheaders1.Location.AbsoluteUri;
}
else
{
Console.WriteLine("could not update Account");
}

//Retriving account
string querystring = "?$select=name,telephone1,websiteurl,address1_city";
HttpResponseMessage retrieveresponse = await httpClient.GetAsync(accounturi + querystring);
if (retrieveresponse.StatusCode == HttpStatusCode.OK)
{
JObject retrievedaccount = JsonConvert.DeserializeObject<JObject>(await retrieveresponse.Content.ReadAsStringAsync());
Console.WriteLine("name: " + retrievedaccount.GetValue("name"));
Console.WriteLine("City: " + retrievedaccount["address1_city"]);
// Console.Read();
}
//Deleting the created account
HttpResponseMessage deleteResponse1;
//HttpContent lastBadResponseContent = null;
deleteResponse1 = await httpClient.DeleteAsync(accounturi);
Console.WriteLine("Account Deleted");
Console.Read();


}

}

}

===========

Now in main method, create instance of the created class and call the method(CreateContactOld) in the main method.

using System.Threading.Tasks;
using System.Net.Http;


namespace CRUD_Using_Web_Api
{

class Program
{

private static void Main(string[] args)
{

webapihelper web = new webapihelper();
HttpClient ht = web.GetHttp();
Task.WaitAll(Task.Run(async () => await web.CreateContactOld(ht)));

}

}
}

Debugg and do checking of the record in advanced find, because in delete operation it will delete the same record that you created.

Nuget Packages: Microsoft.IdentityModel.Clients.ActiveDirectory and install older version like 2.29.0

5807.13.PNG

I would like to thank Neeraj for helping me to achieve this.

Thanks,

Bharath

Hit like if it is useful for you.

*This post is locked for comments

  • gdas Profile Picture
    gdas 50,085 on at
    RE: CRUD operations using web api in console app

    Glad to see you have  resolved your issue. 

  • Verified answer
    bharrath Profile Picture
    bharrath 195 on at
    RE: CRUD Operations using WEBAPI in console application

    Hi gowtham, I changed my code and it is working fine. please go through my blog community.dynamics.com/.../305276

  • bharrath Profile Picture
    bharrath 195 on at
    RE: CRUD Operations using WEBAPI in console application

    In Visual Studio I have gave password in "abc@123"; but still it is throwing exception.

  • Suggested answer
    gdas Profile Picture
    gdas 50,085 on at
    RE: CRUD Operations using WEBAPI in console application

    Hi ,

    Try with this  , I fund the password you put was not in inside "" and also red highlighted text also no inside double quotation.  Please verify all are with  correct value , hopefully it will work.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using Microsoft.IdentityModel.Clients.ActiveDirectory;
    using System.Net;
    using System.Threading.Tasks;
    
    namespace Azure
    
    {
    
        class Program
    
        {
    
            // O365 User Name and Password
    
            private const string userName = "userone@user1.onmicrosoft.com";
    
            private const string password = "abc@abc";
    
            // D365 Application Url
    
            private const string serviceUrl = "https://abc.crm8.dynamics.com";
    
            // Azure APP Application Id
    
            private const string applicationId = "3d4835ec-1068-4138-94d7-a4f084d2cf48";
    
            // Redirct Uri specified during registration of application
    
            private const string RedirectUri = "https://localhost";
    
            // OAuth 2.0 Authorization Endpoint copied from Azure APP
    
            private const string authorityUri = "login.microsoftonline.com/.../authorize";
    
    
            private static AuthenticationResult authResult = null;
    
            private static void Main(string[] args)
            {
    
                // Code to connect to D365
    
                var credentials = new UserPasswordCredential(userName, password);
    
                var context = new AuthenticationContext(authorityUri);
    
                authResult = context.AcquireTokenAsync(serviceUrl, applicationId, credentials).Result;
    
                // Call CRUD operations
    
                Task.WaitAll(Task.Run(async () => await ExecuteWhoAmI()));
    
                // Task.WaitAll(Task.Run(async () => await CreateRecord()));
    
                Task.WaitAll(Task.Run(async () => await RetrieveContacts()));
    
            }
    
            private static async Task ExecuteWhoAmI()
            {
    
                var httpClient = new HttpClient
    
                {
    
                    BaseAddress = new Uri(serviceUrl),
    
                    Timeout = new TimeSpan(0, 2, 0)
    
                };
    
                httpClient.DefaultRequestHeaders.Add("OData - MaxVersion", "4.0");
    
                httpClient.DefaultRequestHeaders.Add("OData - Version", "4.0");
    
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
    
                // Add this line for TLS complaience
    
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
    
                // Call WhoAmI
    
                var retrieveResponse = await httpClient.GetAsync("api/data/v9.0/WhoAmI");
    
                if (retrieveResponse.IsSuccessStatusCode)
    
                {
    
                    var jRetrieveResponse = JObject.Parse(retrieveResponse.Content.ReadAsStringAsync().Result);
    
                    var currUserId = (Guid)jRetrieveResponse["UserId"];
    
                    var businessId = (Guid)jRetrieveResponse["BusinessUnitId"];
    
                    Console.WriteLine("My User Id – " + currUserId);
    
                    Console.WriteLine("My User Id – " + businessId);
    
                    Console.ReadLine();
    
                }
    
            }
    
            private static async Task RetrieveContacts()
            {
    
                var httpClient = new HttpClient
    
                {
    
                    BaseAddress = new Uri(serviceUrl),
    
                    Timeout = new TimeSpan(0, 2, 0)
    
                };
    
                httpClient.DefaultRequestHeaders.Add("OData - MaxVersion", "4.0");
    
                httpClient.DefaultRequestHeaders.Add("OData - Version", "4.0");
    
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
    
                // Add this line for TLS complaience
    
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
    
                // Retrieve Contacts
    
                var retrieveResponse = await httpClient.GetAsync("api/data/v9.0/contacts");
    
                if (retrieveResponse.IsSuccessStatusCode)
    
                {
    
                    var jRetrieveResponse = JObject.Parse(retrieveResponse.Content.ReadAsStringAsync().Result);
    
                    dynamic collContacts = JsonConvert.DeserializeObject(jRetrieveResponse.ToString());
    
                    foreach (var data in collContacts.value)
    
                    {
    
                        Console.WriteLine("Contact Name – " + data.fullname.Value);
    
                    }
    
                    Console.ReadLine();
    
                }
    
            }
    
        }
    
    }
  • bharrath Profile Picture
    bharrath 195 on at
    RE: CRUD Operations using WEBAPI in console application

    Hi friends,

    I am trying to do crud operations using webapi in console application. I have followed this blog(rajeevpentyala.com/.../code-snippet-authenticate-and-perform-operations-using-d365-web-api-and-c) and did changes but i got An unhandled exception of type 'System.AggregateException' occurred in mscorlib.dll.

    In this line "authResult = context.AcquireTokenAsync(serviceUrl, applicationId, credentials).Result;" I am getting error and while debugging i found username and password is null. can anyone help me.

    This is the code I have written

    =======================

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using Newtonsoft.Json;

    using Newtonsoft.Json.Linq;

    using System.Net.Http;

    using System.Net.Http.Headers;

    using Microsoft.IdentityModel.Clients.ActiveDirectory;

    using System.Net;

    using System.Threading.Tasks;

    namespace Azure

    {

    class Program

    {

    // O365 User Name and Password

    private const string userName = "userone@user1.onmicrosoft.com";

    private const string password = abc@abc;

    // D365 Application Url

    private const string serviceUrl = "https://abc.crm8.dynamics.com&quot;;

    // Azure APP Application Id

    private const string applicationId = "3d4835ec-1068-4138-94d7-a4f084d2cf48";

    // Redirct Uri specified during registration of application

    private const string RedirectUri = "https://localhost&quot;;

    // OAuth 2.0 Authorization Endpoint copied from Azure APP

    private const string authorityUri = "login.microsoftonline.com/.../authorize&quot;;

    private static AuthenticationResult authResult = null;

    private static void Main(string[] args)

    {

    // Code to connect to D365

    var credentials = new UserPasswordCredential(userName, password);

    var context = new AuthenticationContext(authorityUri);

    authResult = context.AcquireTokenAsync(serviceUrl, applicationId, credentials).Result;

    // Call CRUD operations

    Task.WaitAll(Task.Run(async () => await ExecuteWhoAmI()));

    // Task.WaitAll(Task.Run(async () => await CreateRecord()));

    Task.WaitAll(Task.Run(async () => await RetrieveContacts()));

    }

    private static async Task ExecuteWhoAmI()

    {

    var httpClient = new HttpClient

    {

    BaseAddress = new Uri(serviceUrl),

    Timeout = new TimeSpan(0, 2, 0)

    };

    httpClient.DefaultRequestHeaders.Add("OData - MaxVersion", "4.0");

    httpClient.DefaultRequestHeaders.Add("OData - Version", "4.0");

    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application / json"));

    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);

    // Add this line for TLS complaience

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

    // Call WhoAmI

    var retrieveResponse = await httpClient.GetAsync("api / data / v9.0 / WhoAmI");

    if (retrieveResponse.IsSuccessStatusCode)

    {

    var jRetrieveResponse = JObject.Parse(retrieveResponse.Content.ReadAsStringAsync().Result);

    var currUserId = (Guid)jRetrieveResponse["UserId"];

    var businessId = (Guid)jRetrieveResponse["BusinessUnitId"];

    Console.WriteLine("My User Id – " + currUserId);

    Console.WriteLine("My User Id – " + businessId);

    Console.ReadLine();

    }

    }

    private static async Task RetrieveContacts()

    {

    var httpClient = new HttpClient

    {

    BaseAddress = new Uri(serviceUrl),

    Timeout = new TimeSpan(0, 2, 0)

    };

    httpClient.DefaultRequestHeaders.Add("OData - MaxVersion", "4.0");

    httpClient.DefaultRequestHeaders.Add("OData - Version", "4.0");

    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application / json"));

    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);

    // Add this line for TLS complaience

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

    // Retrieve Contacts

    var retrieveResponse = await httpClient.GetAsync("api / data / v9.0 / contacts");

    if (retrieveResponse.IsSuccessStatusCode)

    {

    var jRetrieveResponse = JObject.Parse(retrieveResponse.Content.ReadAsStringAsync().Result);

    dynamic collContacts = JsonConvert.DeserializeObject(jRetrieveResponse.ToString());

    foreach (var data in collContacts.value)

    {

    Console.WriteLine("Contact Name – " +data.fullname.Value);

    }

    Console.ReadLine();

    }

    }

    }

    }

  • bharrath Profile Picture
    bharrath 195 on at
    RE: CRUD Operations using WEBAPI in console application

    Thanks for your reply sreevalli.

  • bharrath Profile Picture
    bharrath 195 on at
    RE: CRUD Operations using WEBAPI in console application

    Thanks for your reply Gowtham. This is what i am supposed to do.

  • Verified answer
    gdas Profile Picture
    gdas 50,085 on at
    RE: CRUD Operations using WEBAPI in console application

    Hi Bharrath,

    In addition,  please have look below reference-

    rajeevpentyala.com/.../code-snippet-authenticate-and-perform-operations-using-d365-web-api-and-c

  • Verified answer
    Sreevalli Profile Picture
    Sreevalli 3,256 on at
    RE: CRUD Operations using WEBAPI in console application
    Hi Bharrath, I found something in Microsoft docs, hope it helps you docs.microsoft.com/.../web-api-basic-operations-sample-csharp
  • bharrath Profile Picture
    bharrath 195 on at
    CRUD Operations using WEBAPI in console application

    Hi friends,

    Can anyone help me with code to do CRUD Operations using WEBAPI in console application.

    Thanks,

    Bharath

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,280 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,214 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans