How to use XRM in C#? - c#

Hello I need to convert a JS Xrm web api function into C#
var opp = Xrm.Page.data.entity.getId();
Xrm.WebApi.retrieveMultipleRecords(
"dei_opportunityline",
"?$select=_dei_vendor_value,dei_multiplier,dei_iscommission,dei_opportunitylineid&$filter=_dei_opportunity_value eq " +
opp
).then(
function success(result) {
for (var i = 0; i < result.entities.length; i++) {
var newMulti = null;
if (result.entities[i].dei_iscommission) {
if (
result.entities[i]["_dei_vendor_value"] ==
"5fc8d03b-c41c-eb11-a813-000d3a31ed8d"
) {
if (jcimulti != null) newMulti = jcimulti;
} else {
if (commulti != null) newMulti = commulti;
}
For methods like .retrieveMultipleRecords, result.entities[i].dei_iscomission
is there a way to write this in C# plugin ?!

You cannot use Xrm in C#, this is useful inside Dynamics client scripting (JS) context only. ie web form context.
For Server side (C#), you have to use HttpClient. Sample code
HttpClient httpClient = null;
httpClient = new HttpClient();
//Default Request Headers needed to be added in the HttpClient Object
httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Set the Authorization header with the Access Token received specifying the Credentials
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
httpClient.BaseAddress = new Uri("https://yourorg.api.crmx.dynamics.com/api/data/v9.0/");
var response = httpClient.GetAsync("dei_opportunityline?$select=_dei_vendor_value,dei_multiplier,dei_iscommission,dei_opportunitylineid&$filter=_dei_opportunity_value eq <guid>").Result;
if (response.IsSuccessStatusCode)
{
var records = response.Content.ReadAsStringAsync().Result;
//you can get dei_iscomission from above records
}
This is how we use in console application, but in plugin or workflow code - you can use Org Service to get data using Query Expression or fetchxml. Methods like service.RetrieveMultiple will suffice your need. Read more

Simply include the crmsdk nuget package in C#. Then you can connect like you want.
See docs
This packages gives you access to the official c# SDK for XRM. the methods are much easier to use then directly calling the ODATA Web API. For an example to fetch multiple records, see https://community.dynamics.com/crm/f/microsoft-dynamics-crm-forum/246665/how-to-retrieve-multiple-records-from-an-entity-in-crm-using-c
For a quick start, see https://learn.microsoft.com/en-us/powerapps/developer/data-platform/webapi/get-started-dynamics-365-web-api-csharp

Related

Get Data of online API

I want to download data of this website into a json file but as I am quite new to coding with C# I cant manage to get the data. I want to get Data of https://discosweb.esoc.esa.int/api/objects the authorization via token works but I dont know how I can send a request so the server gives me a json back and I cant find a solution online. I cant give you a screenshot of the API because you have to be logged in to see it. Plz ask me for detailed information if you can help me. Thank you realy for trying.
The code I want to run is here.
class Program
{
static HttpClient client = new HttpClient();
static void Main(string[] args)
{
client.BaseAddress = new Uri("https://discosweb.esoc.esa.int");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.api+json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("my_token");
var httpRequest = (HttpWebRequest)WebRequest.Create(client.BaseAddress);
var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var streamReaderResult = streamReader.ReadToEnd();
}
Console.WriteLine("Status https://discosweb.esoc.esa.int : " + httpResponse.StatusCode);
}
}
Try this
var url = "https://discosweb.esoc.esa.int/api/objects";
var httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.Headers["Authorization"] = "Basic XXXx";
httpRequest.ContentType = "";
httpRequest.Headers["Content-Length"] = "0";
var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
Console.WriteLine(httpResponse.StatusCode);
Where XXXx is user:password in base64.
Here is a basic implementation for making that API call to get the JSON result. You will need to parse that JSON into something other than a string but I'll assume you can handle that part.
This uses System.Net.HttpClient which is the modern HTTP api provided by .NET. Its operations are async so hopefully your code is or can be written to properly await async operations.
//Someplace convenient, create a shared HttpClient to avoid
//creating and disposing for each request.
HttpClient client = new HttpClient();
string data = await GetObjects(client);
//Example implementation
public async Task<string> GetObjects(HttpClient client)
{
string url = "https://discosweb.esoc.esa.int/api/objects";
using (HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Get, url))
{
msg.Headers.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "your personal access token here");
using (var result = await client.SendAsync(msg))
{
string content = await result.Content.ReadAsStringAsync();
return content;
}
}
}
While I may be a month late, I've actually developed an SDK for this particular API.
So, if you use this SDK it's pretty simple to do what you want. You can essentially forget about handling anything HTTP related, my SDK abstracts all of that away.
For example, to fetch Sputnik's data (which has an ID of 1) you'd run.
HttpClient innerClient = new();
innerClient.BaseAddress = "https://discosweb.esoc.esa.int/api/"
innerClient.DefaultRequestHeaders.Authorization = new("bearer", yourApiKey);
DiscosClient client = new();
DiscosObject sputnik = await client.GetSingle<DiscosObject>("1");
If you're using ASP.NET, there's a set of DI extensions that can actually set it all up for you, so you can skip the first three lines.
If you do choose to use it, please let me know, as it would be nice knowing my SDK is getting some use. If you have any issues, please just reach out through the GitHub issues page and I'll try to help!

secure access to external web API .NET CORE

I have two web APIs applications developed in .Net core. I need to import Json data from the second application to the first. However,I have a security issue. I need to secure the access to the external API. How should I securely manage the connection between these two APIs.
For example, I need to secure the access to the URL in the code bellow => securely access to the covid API without another authentication.
PS: I'm using JWT token authentication in both applications
Best regards.
using (var client = new HttpClient())
{
string url = string.Format("https://covid19.mathdro.id/api");
var response = client.GetAsync(url).Result;
string responseAsString = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<CovidResult>(responseAsString);
}
If both APIs are protected by the same accessToken, then you can read the authorization header from the first request and pass it to the second request.
Something like this to read the header:
var authHeader = context.Request.Headers.Get("Authorization");
You should end up with authHeader equal to "Bearer ey...(a bunch of base64)"
Then add the auth header to the client:
var request = new HttpRequestMessage() {
RequestUri = new Uri("http://https://covid19.mathdro.id/api"),
Method = HttpMethod.Get,
};
...
request.Headers.Authorization.Add(new AuthenticationHeaderValue(authHeader));
var task = client.SendAsync(request)

How to diagnose a 401 error attempting to get an OAuth2 bearer token in c# .NET Core?

I have some limited skills in c++ and have recently moved in C# (asp.net) and azure Web services. As a PoC I'm trying to make REST calls into PayPal (which I'll need to be using professionally in 3 -6 months).
I've set up my personal PayPal account using the instructions here and I get a bearer token back using curl as described in the link. Awesome.
I'm now trying to do this from .NET Core C# and all I get is a 401 error. I've examined the request and it seems the same as the curl in terms of headers; the base64 encoded credentials I think I'm adding are the same as the ones in the verbose curl log (I examined the two base64 strings by eye) so it must be something I'm doing (or not doing) in the set up of the call. I'm looking for suggestions, pointers, or flat out laughter at the obvious mistake I've made.
I've set up what I believe to be a named client thus:
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient("PayPal", c =>
{
c.BaseAddress = new Uri("https://api.sandbox.paypal.com/v1/");
c.DefaultRequestHeaders.Add("Accept", "application/json");
c.DefaultRequestHeaders.Add("Accept-Language", "en_US");
});
(with all the other stuff that comes free with VS under it omitted for brevity).
I attempt the call thus:
string clientCredString = CLIENTID + ":" + SECRET;
var clientCreds = System.Text.Encoding.UTF8.GetBytes(clientCredString);
var client = _clientFactory.CreateClient("PayPal");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", System.Convert.ToBase64String(clientCreds));
var messageBody = new Dictionary<string,string > ();
messageBody.Add("grant_type", "client_credientials");
var request = new HttpRequestMessage(HttpMethod.Get, "oauth2/token")
{
Content = new FormUrlEncodedContent(messageBody)
};
string token;
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
token = JsonConvert.DeserializeObject<string>(json);
}
else
{
throw new ApplicationException("Well that failed");
}
and get a 401 code for my trouble.
Suggestions for troubleshooting, better methods of doing this and laughter at my foolishness all welcomed.
Update:
I read the documentation, a couple of items stand out to me:
Requires a verb of post.
Uses FormUrlEncodedContent for client credentials.
Basic auth requires username and password (Client Id & Secret)
I believe the syntax should be:
var client = new HttpClient();
using var request = new HttpRequestMessage(HttpMethod.Post, "...");
request.Content = new Dictionary<string, string>() { "grant_type", "client_credentials" };
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", $"{Encoding.UTF8.GetBytes($"{id}:{secret}")}");
HttpResponseMEssage = response = await client.PostAsync(request);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
For the benefit of future readers:
It was, as suggested, an encoding problem. The line:
var clientCreds = System.Text.Encoding.UTF8.GetBytes(clientCredString);
needed to be
var clientCreds = System.Text.Encoding.ASCII.GetBytes(clientCredString);
It should also be noted that this particular operation requires a POST not a GET as I was using, but once I started sending properly encoded requests the errors started to make a lot more sense.

Assign a manager using Microsoft Graph .NET Client Library

Can someone give me a hint how to set the User.Manager field using the Microsoft Graph .NET Client Library? I know how to do this via a direct REST call but want to avoid those calls (bypassing the wrapper) as much as possible. With the code below I was able to clear the manager property.
client = new GraphClient(...);
var builder = new DirectoryObjectWithReferenceRequestBuilder(
client.Users["<userid>"].Manager.Request().RequestUrl,client
);
builder.Request().DeleteAsync().Wait()
However, I still can't figure out which class allows me to build a PUT request for the member reference (as described here). I tried to the following code:
var mgr = new DirectoryObject();
mgr.Id = "<Id of the user that should be set as manager>";
var usrPatch = new User();
usrPatch.Manager = mgr;
client.Users["<Id of the user to be updated>"].Request().UpdateAsync(usrPatch).Wait();
This code doesn't throw an exception but it also doesn't update the manager. The request is wrong. The above code sends a PATCH instead of a PUT to the "base" object.
Request generated by the code above:
PATCH https://graph.microsoft.com/v1.0/users/[Id of the user to be updated] HTTP/1.1
SdkVersion: graph-dotnet-1.0.1
Content-Type: application/json
Host: graph.microsoft.com
Content-Length: 45 Expect: 100-continue
{"id":"[Id of the user that should be set as manager]"}
The response is a 204.
I see the following to remove a manager:
graphClient.Users[newUser.Id].Manager.Reference.Request().DeleteAsync();
But we should have something like the following to assign a manager:
graphClient.Users[newUser.Id].Manager.Reference.Request().AddAsync(manager);
I'll file a bug for this and update when fixed.
Workaround till updating the "manager" is fully supported:
var authToken = "<get your token here>";
var client = new GraphClient(...);
var usrId = "<id of the user to update>"
var mgrId = "<id of the manager>"
var url = client.Users[usrId].Manager.Reference.Request().RequestUrl;
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", authToken);
var content = new StringContent(
client.HttpProvider.Serializer.SerializeObject(
new ReferenceRequestBody
{
ODataId =
$"{client.BaseUrl}/directoryObjects/{mgrId}"
}),
Encoding.Default,
"application/json");
var resp = httpClient.PutAsync(url, content).Result;
if (!resp.IsSuccessStatusCode)
{
// throw exception/log etc
}
Two years later and this is still not working.
I'm getting the following exception when using await graphClient.Users[user.Id].Manager.Request().UpdateAsync(usrPatch);
Microsoft.Graph.ServiceException: 'Code: BadRequest
Message: Write requests are only supported on contained entities
I had to use stefboe's workaround logic to update the manager.
Microsoft.Graph DLL Version is 1.12.
Use PutAsync() to set the manager using the Graph Library:
graphClient.Users[user.Id].Manager.Reference.Request().PutAsync(manager.Id);

Call and consume Web API in winform using C#.net

I am beginner and creating winform application. In which i have to use API for Simple CRUD operation. My client had shared API with me and asked to send data in form of JSON.
API : http://blabla.com/blabla/api/login-valida
KEY : "HelloWorld"
Value : { "email": "user#gmail.com","password": "123456","time": "2015-09-22 10:15:20"}
Response : Login_id
How can i convert data to JSON, call API using POST method and get response?
EDIT
Somewhere on stackoverflow i found this solution
public static void POST(string url, string jsonContent)
{
url="blabla.com/api/blala" + url;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseURL);
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(jsonContent);
request.ContentLength = byteArray.Length;
request.ContentType = #"application/json";
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
length = response.ContentLength;
}
}
catch
{
throw;
}
}
//on my login button click
private void btnLogin_Click(object sender, EventArgs e)
{
CallAPI.POST("login-validate", "{ \"email\":" + txtUserName.Text + " ,\"password\":" + txtPassword.Text + ",\"time\": " + DateTime.Now.ToString("yyyy-MM-dd h:mm tt") + "}");
}
I got exception that says "The remote server returned an error: (404) Not Found."
You can take a look at the following docs tutorial:
Call a Web API From a .NET Client
But as an answer, here I will share a quick and short a step by step guide about how to call and consume web API in Windows forms:
Install Package - Install the Microsoft.AspNet.WebApi.Client NuGet package (Web API Client Libraries).
Open Tools menu → NuGet Package Manager → Package Manager Console → In the Package Manager Console window, type the following command:
Install-Package Microsoft.AspNet.WebApi.Client
You can install package by right click on project and choosing Manage NuGet Packages as well.
Set up HttpClient - Create an instance of HttpClient and set up its BaseAddress and DefaultRequestHeaders. For example:
// In the class
static HttpClient client = new HttpClient();
// Put the following code where you want to initialize the class
// It can be the static constructor or a one-time initializer
client.BaseAddress = new Uri("http://localhost:4354/api/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
Send Request - To send the requests, you can use the following methods of the HttpClient:
GET: GetAsync, GetStringAsync, GetByteArrayAsync, GetStreamAsync
POST: PostAsync, PostAsJsonAsync, PostAsXmlAsync
PUT: PutAsync, PutAsJsonAsync, PutAsXmlAsync
DELETE: DeleteAsync
Another HTTP method: Send
Note: To set the URL of the request for the methods, keep in mind, since you have specified the base URL when you defined the client, then here for these methods, just pass path, route values and query strings, for example:
// Assuming http://localhost:4354/api/ as BaseAddress
var response = await client.GetAsync("products");
or
// Assuming http://localhost:4354/api/ as BaseAddress
var product = new Product() { Name = "P1", Price = 100, Category = "C1" };
var response = await client.PostAsJsonAsync("products", product);
Get the Response
To get the response, if you have used methods like GetStringAsync, then you have the response as string and it's enough to parse the response. If the response is a Json content which you know, you can easily use JsonConvert class of Newtonsoft.Json package to parse it. For example:
// Assuming http://localhost:4354/api/ as BaseAddress
var response = await client.GetStringAsync("product");
var data = JsonConvert.DeserializeObject<List<Product>>(response);
this.productBindingSource.DataSource = data;
If you have used methods like GetAsync or PostAsJsonAsync and you have an HttpResponseMessage then you can use ReadAsAsync, ReadAsByteArrayAsync, ReadAsStreamAsync, `ReadAsStringAsync, for example:
// Assuming http://localhost:4354/api/ as BaseAddress
var response = await client.GetAsync("products");
var data = await response.Content.ReadAsAsync<IEnumerable<Product>>();
this.productBindingSource.DataSource = data;
Performance Tip
HttpClient is a type that is meant to be created once and then shared. So don't try to put it in a using block every time that you want to use it. Instead, create an instance of the class and share it through a static member. To read more about this, take a look at Improper Instantiation antipattern
Design Tip
Try to avoid mixing the Web API related code with your application logic. For example let's say you have a product Web API service. Then to use it, first define an IProductServieClient interface, then as an implementation put all the WEB API logic inside the ProductWebAPIClientService which you implement to contain codes to interact with WEB API. Your application should rely on IProductServieClient. (SOLID Principles, Dependency Inversion).
Just use the following library.
https://www.nuget.org/packages/RestSharp
GitHub Project: https://github.com/restsharp/RestSharp
Sample Code::
public Customer GetCustomerDetailsByCustomerId(int id)
{
var client = new RestClient("http://localhost:3000/Api/GetCustomerDetailsByCustomerId/" + id);
var request = new RestRequest(Method.GET);
request.AddHeader("X-Token-Key", "dsds-sdsdsds-swrwerfd-dfdfd");
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
dynamic json = JsonConvert.DeserializeObject(content);
JObject customerObjJson = json.CustomerObj;
var customerObj = customerObjJson.ToObject<Customer>();
return customerObj;
}
Use Json.Net to convert data into JSON
Use WebClient to POST data
Use This code:
var client = new HttpClient();
client.BaseAddress = new Uri("http://www.mywebsite.com");
var request = new HttpRequestMessage(HttpMethod.Post, "/path/to/post/to");
var keyValues = new List<KeyValuePair<string, string>>();
keyValues.Add(new KeyValuePair<string, string>("site", "http://www.google.com"));
keyValues.Add(new KeyValuePair<string, string>("content", "This is some content"));
request.Content = new FormUrlEncodedContent(keyValues);
var response = await client.SendAsync(request);
Here is another example using an online REST service (https://northwind.vercel.app) which allows interaction with Northwind API.
This example uses HttpClient and JsonConvert to get or post data. Here is a very quick example:
Install Newtonsoft.Json nuget package. And add the following using statements to your form:
using System.Net.Http;
using Newtonsoft.Json
Define an instance of the HttpClient, at class level:
private static HttpClient client = new HttpClient();
To send a GET request, for example getting list of all data:
var url = "https://northwind.vercel.app/api/categories";
var response = await client.GetAsync(url);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var content = await response.Content.ReadAsStringAsync();
var categories = JsonConvert.DeserializeObject<List<Category>>(content);
dataGridView1.DataSource = categories;
}
You can also use other overloads of Get, like GetStringAsync, GetStreamAsync, and etc. But GetAsync is a more generic method allowing you to get the status code as well.
To send a POST request, for example posting a new data:
var url = "https://northwind.vercel.app/api/categories";
var data = new Category() { Name = "Lorem", Description = "Ipsum" };
var jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(data);
var requestContent = new StringContent(jsonData, Encoding.Unicode, "application/json");
var response = await client.PostAsync(url, requestContent);
if (response.StatusCode == System.Net.HttpStatusCode.Created)
{
var content = await response.Content.ReadAsStringAsync();
var createdCategory = JsonConvert.DeserializeObject<Category>(content);
MessageBox.Show(createdCategory.Id.ToString())
}
To learn more and see some best practices or see an example without JsonConvert, see my other post.

Categories