Showing posts with label API. Show all posts
Showing posts with label API. Show all posts

Monday, February 27, 2023

Generate Token using x++

 Generate Token using x++.


using System.IO;
using System.Net;
using System.Text;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.File;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Threading.Tasks;

public class Authenticationtoken
{
    public void TokenGen()
    {
        WebException                            exception;
        System.Net.HttpWebRequest               webrequest;
        CLRObject                   		webResponse =null;
        System.Exception            		ex;
        #OCCRetryCount
		
        System.Net.HttpWebResponse response;
        str response1;
        str               	byteStr;
        System.Byte[]           byteArray;
        System.IO.Stream        stream;
        System.IO.Stream        dataStream;
		System.Text.Encoding    utf8;
		
	//Using username and password for Authentication
        byteStr = strfmt('%1:%2', "Username", "PassWord");
		
        webrequest = System.Net.WebRequest::Create("URL") as System.Net.HttpWebRequest;
        
	// Parameters
        webRequest.Method           = 'POST';// POST / Get
        webRequest.KeepAlive        = true;
        webRequest.ContentType      = "application/json";  
        webRequest.ContentLength    = 0;
        //webrequest.Host             ="";
        // webrequest.UserAgent        ="";
        //webrequest.Connection       ="";
        webRequest.Timeout          = maxInt();
		
	//Headers
        System.Net.WebHeaderCollection headers = new System.Net.WebHeaderCollection();
        headers = webRequest.Headers;
		
	// Encoding
        utf8       = System.Text.Encoding::get_UTF8();
        byteArray  = utf8.GetBytes(byteStr);
        byteStr    = System.Convert::ToBase64String(byteArray);
		
        headers.Add("Authorization", 'Basic ' + byteStr);
        //headers.Add("Username", "123");

        if (webRequest != null)
        {
            webResponse = webRequest.GetResponse();

            using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream()))
            {
               response1 = streamReader.readToEnd();
            }

            webResponse.Close();
        }
        else
        {
            throw new System.Exception("Please provide valid URL");
        }
		
        return Authenticationtoken::deserialize(response1);
    }

    public static void deserialize(str  _json)
    {
        AttendanceAuthenticationContract        attendanceAuthenticationContract;
        
        // List
        //attendanceAuthenticationContract = FormJsonSerializer::deserializeCollection(classNum(AttendanceAuthenticationContract),
        //    _json, Types::Class, classStr(AttendanceAuthenticationContract));

        attendanceAuthenticationContract = FormJsonSerializer::deserializeObject(classNum(AttendanceAuthenticationContract),
            _json);

	//Token
        info(attendanceAuthenticationContract.parmBearerToken());
		
	---------------------or--------------------------------
	Map map = RetailCommonWebAPI::getMapFromJsonString(_json);

        if (map && map.exists('access_token'))
        {
            info(map.lookup('access_token'));
        }
    }

}



Keep Daxing!!


Wednesday, February 22, 2023

Trigger URL with simple json using x++

 Trigger URL with simple json using x++.


	RetailCommonWebAPI      retailCommonWebAPI = RetailCommonWebAPI::construct();

	str requestURL = 'URL';
	str json = '{"TestField" : "123"}';

	retailCommonWebAPI.makePostRequest(requestURL, json, '', 'application/json');


Keep Daxing!!

Tuesday, February 14, 2023

Trigger the API using X++

 Trigger the API using X++.


using System.IO;
using System.Net;
using System.Text;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.File;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Threading.Tasks;

    Way 1 : With Encoding the JSON

public void callAPI()
{
    WebException                exception;
    HttpWebRequest              webRequest;
    WebResponse                 webResponse;
    CLRObject                   clrObj;
    System.Exception            ex;
    System.Byte[]               bytes;
    System.Text.Encoding        encoding;
    #OCCRetryCount
        

    webRequest                  = System.Net.WebRequest::Create('URL');
    webRequest.Method           = 'MethodName';// POST / Get
    webRequest.KeepAlive        = true;
    webRequest.ContentType      = 'ContentType';//"application/json"
    webRequest.Timeout          = maxInt();

    System.Net.WebHeaderCollection headers = new System.Net.WebHeaderCollection();

    Headers = webRequest.Headers;
    headers.Add('Authorization', 'Bearer ' + token);

	// With Encoding
    if (reqJson)
    {
        encoding    = System.Text.Encoding::get_UTF8();
        bytes       = encoding.GetBytes(reqJson);

        webRequest.ContentLength = bytes.get_Length();

        using (Stream stream = webRequest.GetRequestStream())
        {
            stream.Write(bytes,0,bytes.get_Length());
            stream.Close();
        }
    }

    if (webRequest != null)
    {
        webResponse = webRequest.GetResponse();

        using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream()))
        {
            str response = streamReader.readToEnd();
        }

        webResponse.Close();

    }
    else
    {
        throw new System.Exception("Please provide valid URL");
    }
}

    Way 2 : Without Encoding the JSON

public void callAPI()
{
    System.Net.HttpWebRequest       request;
    System.Net.HttpWebResponse      response;
    CLRObject                       clrObj;
    System.Exception                ex;
    System.Net.WebHeaderCollection  httpHeader;
    str                             requestJson, responseJson;

    try
    {
        // We can use commented code also
        //new InteropPermission(InteropKind::ClrInterop).assert();
        //clrObj = System.Net.WebRequest::Create('Url');
        //request = clrObj;

        request  = System.Net.WebRequest::Create('URL');
        request.Method      = "POST";
        request.ContentType = "application/json";
           
        // Adding header in 2 ways 
        httpHeader = new System.Net.WebHeaderCollection();

		// Way 1: Get the header from request
        httpHeader = request.Headers;
        httpHeader.Add("Authorization", 'Token');
        httpHeader.Add('key:' + 'Key');//If your API need any mandatory tags that time this is needed. 
		
		//  Way 2: assign header to request
        //request.set_Headers(httpHeader);

        //Upload Json
        //System.IO.Stream    requestStream = request.GetRequestStream();
        using (System.IO.StreamWriter   streamWriter = new System.IO.StreamWriter(request.GetRequestStream()))
        {
            streamWriter.Write(requestJson); // writing JSON
            streamWriter.Flush();
            streamWriter.Close();
        }
        if (request != null)
        {
            response = request.GetResponse();
            using (System.IO.StreamReader responseStream = new System.IO.StreamReader(response.GetResponseStream()))
            {
                responseJson = responseStream.ReadToEnd().ToString();

                info(responseJson);
            }
        }
    }
}


https://msdax.wordpress.com/2018/04/30/ax-2012-call-restful-api-using-basic-authentication-x-dynamics-ax-2012/

Keep Daxing!!

Get the environment link Using x++

 Get the environment link Using x++.


Microsoft.Dynamics.ApplicationPlatform.Environment.IApplicationEnvironment     env;
         
env = Microsoft.Dynamics.ApplicationPlatform.Environment.EnvironmentFactory::GetApplicationEnvironment();

//return env.Infrastructure.FullyQualifiedDomainName;
return env.Infrastructure.HostUrl;


Keep Daxing!!

Wednesday, July 13, 2022

Generate Bearer token using x++ in D365FO.

  Generate Bearer token using x++ in D365FO.

  • While triggering API we need to generate a token.
  • While calling their API We need to send the token, So they will validate that Token and send the response data If i.e. valid.
  • To Generate Token we need
    • Client Id
    • Client secret
    • Tenant Id
  • For the above details, we need to do the app registration in the Azure portal.
  • We need to create one record with the client id in the Azure application in the system administration module.

    AuthenticationResult        authResult; 

        
    ClientCredential        clientCrendential   = new ClientCredential('ClientId', 'ClientSecretKey');
    AuthenticationContext   authContext         = new AuthenticationContext(url);
            // https://login.microsoftonline.com/tenantId/oauth2/token
        
    authResult  = authContext.AcquireToken('Scope or Resource(URL)', clientCrendential);
        
    token =  authResult.AccessToken;

    Info(token);


Scope: ABCD/.default

--> api//:ABCD/.default 

    --> We need to remove api//: 

    --> Otherwise it will throw the error.


Keep Daxing!!

Generate token from key vault parameters using x++ in D365FO.

 Generate token from key vault parameters using x++ in D365FO.

  •  We are saving our token URL in Key vault for security. By using the below code we will get the URL form Key Vault. 
  • We have used same client ID and client secret for key vault also. So I have configured that in key vault parameters. 

    
    str                           url, token;
    KeyVaultParameters            vaultParameter;
    KeyVaultCertificateTable      vaultCertificate;

    select vaultParameter where vaultParameter.Name == 'Name';// which we have created in Key vault.

    if (vaultParameter)
    {
        select vaultCertificate where vaultCertificate.KeyVaultRef == vaultParameter.RecId;

        KeyVaultClientHelper::removeCachedKeyVaultClient(vaultCertificate.KeyVaultCertificate);

        url = KeyVaultCertificateHelper::getManualSecretValue(vaultCertificate.RecId);
        // Here KeyVault will generate the Token URL.
AuthenticationResult authResult; ClientCredential clientCrendential = new ClientCredential(                     vaultParameter.AppClientId, vaultParameter.getClientSecretKey());                     // Based on client Id and client secret key we have created Key vault. AuthenticationContext authContext = new AuthenticationContext(url); authResult = authContext.AcquireToken('Scope or Resource(URL)', clientCrendential);         token = authResult.AccessToken; Info(token); }



Keep Daxing!!