Thursday, January 22, 2026

Call API using x++ D365FO

 System.Net.HttpWebRequest    request;

System.Net.HttpWebResponse   response;

System.IO.Stream             dataStream;

System.IO.StreamReader       reader;

System.Text.Encoding         encoding = System.Text.Encoding::UTF8;

System.Text.StringBuilder    responseBuilder = new System.Text.StringBuilder();

System.Byte[]                byteArray;


str url = "API URL";

str body = "{"Sample json"}";

str accessToken = "TokenValue";

 try

 {

    

     request = System.Net.WebRequest::Create(url) as System.Net.HttpWebRequest;

     request.set_Method('POST');

     request.set_ContentType('application/json');

     System.Net.WebHeaderCollection headers = request.get_Headers();

     headers.Add('X-Access-Token', accessToken); // header changes with API access level


     byteArray = encoding.GetBytes(body);

     request.set_ContentLength(byteArray.get_Length());

     dataStream = request.GetRequestStream();

     dataStream.Write(byteArray, 0, byteArray.get_Length());

     dataStream.Close();


     response = request.GetResponse() as System.Net.HttpWebResponse;

     dataStream = response.GetResponseStream();

     reader = new System.IO.StreamReader(dataStream, encoding);

     

     str line = reader.ReadLine();

     while (!CLRInterop::isNull(line))

     {

         responseBuilder.Append(line);

         line = reader.ReadLine();

     }

     reader.Close();

     dataStream.Close();

     response.Close();


     str responseString = responseBuilder.ToString();


Newtonsoft.Json.Linq.JObject  contractData    = Newtonsoft.Json.JsonConvert::DeserializeObject(responseString );


Newtonsoft.Json.Linq.JObject  dataObject = contractData.GetValue('data');

Newtonsoft.Json.Linq.JObject  locationAddObject = dataObject.GetValue('Create');

if (locationAddObject)

{

    Newtonsoft.Json.Linq.JObject  locationObject = locationAddObject.GetValue('lineDetails');

    if (productAttributeMapping.RecId)

    {

         Str value1 =  locationObject.GetValue('id').ToString();

    }

}

}

catch

{

   error("error occurred while calling an API " );

}

-----------------------------------------

Json response:

{
    "data": {
        "Create": {
            "lineDetails": {
                "id": "gid://shopify/MetafieldDefinition/144792846553",
                "qty": "Custom",
                "name": "122361",
                "description": "Warranty"
            },
            "userErrors": []
        }
    },
    "extensions": {
        "cost": {
            "requestedQueryCost": 10,
            "actualQueryCost": 10,
            "throttleStatus": {
                "maximumAvailable": 2000.0,
                "currentlyAvailable": 1990,
                "restoreRate": 100.0
            }
        }
    }
}



Sunday, January 4, 2026

How to create json foramt using MAP class x++ D365FO




   Map myMap;
   myMap.insert("Invoice account", "INV001");
   myMap.insert("SalesId", "SO-100-001");
     Str json = JSONSerializerExtension::serializeClass(myMap);
OutPut json:
{
  "Invoice account": "INV001",
  "SalesId" :"SO-100-001"
}


Saturday, December 27, 2025

Convert string into ENUM str2enum in x++

str salesStatusValue = ‘Open order’;

salesStatus = str2Enum(salesStatus,salesStatusValue);

Tuesday, December 23, 2025

find or create legal entity postal address x++ d365fo

 public void findOrcreatePostalAddress(

    LogisticsAddressStreet _street,

    str _countryRegionCode,

    str _city,

    str _state,

    str _postalCode,

    LogisticsDescription _locationName,

    PurchTable _purchTable)

{

    LogisticsPostalAddress      postalAddress;

    DirPartyLocation            partyLocation;

    DirPartyPostalAddressView   dirPartyPostalAddressView;

    DirParty                    dirParty;

    CompanyInfo                 companyInfo = CompanyInfo::findDataArea("USMF"); // Get company info for legal entity


    // Try to find an existing postal address for this company with given parameters

    select firstonly dirPartyPostalAddressView

        where dirPartyPostalAddressView.Party               == companyInfo.RecId

           && dirPartyPostalAddressView.LocationName       == _locationName

           && dirPartyPostalAddressView.Street             == _street

           && dirPartyPostalAddressView.City               == _city

           && dirPartyPostalAddressView.State              == _state

           && dirPartyPostalAddressView.CountryRegionId    == _countryRegionCode;


    // If no existing postal address found, create a new one

    if (!dirPartyPostalAddressView)

    {

        // Construct DirParty from the company

        dirParty = DirParty::constructFromCommon(companyInfo);


        // Define location role container (e.g., Delivery)

        container roleContainer = [LogisticsLocationRole::findByType(LogisticsLocationRoleType::Delivery).RecId];


        // Set postal address details

        dirPartyPostalAddressView.Street             = _street;

        dirPartyPostalAddressView.City               = _city;

        dirPartyPostalAddressView.CountryRegionId    = _countryRegionCode;

        dirPartyPostalAddressView.State              = _state;

        dirPartyPostalAddressView.ZipCode            = _postalCode;

        dirPartyPostalAddressView.IsPrimary          = NoYes::No;

        dirPartyPostalAddressView.LocationName       = _locationName;


        // Create or update the postal address in D365FO

        dirPartyPostalAddressView = dirParty.createOrUpdatePostalAddress(dirPartyPostalAddressView, roleContainer);


    }

}


How to change the To Email in Print Management when printing a report using X++ in Dynamics 365 Finance and Operations

[ExtensionOf(classStr(SrsReportRunPrinter))]

final class TestSrsReportRunPrinter_Extension

{

    public void printReport()

    {

        if (reportContract.parmRdpName() == "SalesInvoiceDP")

        {

            SalesInvoiceContract salesInvoicecontract = reportContract.parmRdpContract() as SalesInvoiceContract;

            printSettings.reportTitle("SalesInvoice");

            printSettings.custInvoiceRecid(salesInvoicecontract.parmRecordId());

        }

        next printReport();

    }

}


[ExtensionOf(classStr(SRSPrintDestinationSettings))]

final class TestSRSPrintDestinationSettings_Extension

{

    internal str reportTitle, clreportTitle;

    internal RecId custJourRecId;


    [DataMemberAttribute]

    public str reportTitle(str _reportTitle = reportTitle)

    {

        reportTitle = _reportTitle;

        return reportTitle;

    }


    [DataMemberAttribute]

    public RecId custInvoiceRecid(RecId _custJourRecId = custJourRecId)

    {

        custJourRecId = _custJourRecId;

        return custJourRecId;

    }


    public SrsReportEMailDataContract parmEMailContract(SrsReportEMailDataContract _emailContract)

    {

        contract = next parmEMailContract(_emailContract);


        if (this.reportTitle() == "SalesInvoice")

        {

            CustInvoiceJour custinvoicejour;

            select firstonly custinvoicejour where custinvoicejour.RecId == this.custInvoiceRecid();


            contract.parmTo(custinvoicejour.TestExternalRequesterEmail);


            emailSubject = contract.parmSubject();

            emailSubject = strReplace(emailSubject, "%PurchaseOrder%", purchTable.PurchId);

            contract.parmSubject(emailSubject);

        }

        return contract;

    }

}


Sunday, December 21, 2025

Attach a file with base 64 string x++ D365fo

 str base64String = "JVBERi0xLjQKJeLjz9MKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZwovUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzCi9LaWRzIFsgMyAwIFIgXQovQ291bnQgMSA+PgplbmRvYmoKMyAwIG9iago8PCAvVHlwZSAvUGFnZQovUGFyZW50IDIgMCBSCi9NZWRpYUJveCBbMCAwIDYxMiA3OTJdCi9Db250ZW50cyA0IDAgUgovUmVzb3VyY2VzIDw8IC9Gb250IDw8IC9GMSA1IDAgUiA+PiA+PiA+PgplbmRvYmoKNCAwIG9iago8PCAvTGVuZ3RoIDQ0ID4+CnN0cmVhbQpCVAovRjEgMjQgVGYKMTAwIDcwMCBUZAooSGVsbG8gV29ybGQpIFRqCkVUCmVuZHN0cmVhbQplbmRvYmoKNSAwIG9iago8PCAvVHlwZSAvRm9udAovU3VidHlwZSAvVHlwZTEKL0Jhc2VGb250IC9IZWx2ZXRpY2EgPj4KZW5kb2JqCnhyZWYKMCA2CjAwMDAwMDAwMDAgNjU1MzUgZgowMDAwMDAwMDEwIDAwMDAwIG4KMDAwMDAwMDA3OSAwMDAwMCBuCjAwMDAwMDAxNzggMDAwMDAgbgowMDAwMDAwMzAxIDAwMDAwIG4KMDAwMDAwMDM5MCAwMDAwMCBuCnRyYWlsZXIKPDwgL1NpemUgNgovUm9vdCAxIDAgUiA+PgpzdGFydHhyZWYKNTAyCiUlRU9G";

str fileName = "MyAttachment.pdf";

str fileType = "PDF"; 

PurchTable purchTable; 

select firstOnly purchTable where purchTable.PurchId == 'PO00003075'; 

if (purchTable)

{

    System.IO.MemoryStream      memoryStream;

    DocuRef                     docuRef;

    #define.File('File')

    try

    {

        if(purchTable.RecId  && fileName)

        {

            docuRef.clear();

            docuRef.RefTableId   = purchTable.TableId;

            docuRef.RefRecId     = purchTable.RecId;

            docuRef.RefCompanyId = curExt();

            docuRef.TypeId       = #File;

            docuRef.Name         = System.IO.Path::GetFileNameWithoutExtension(fileName);

            docuRef.DocumentId   = newGuid();

            if(docuRef.validateWrite())

            {

                docuRef.insert();

                memoryStream = new System.IO.MemoryStream(System.Convert::FromBase64String(base64String));

                if(memoryStream != null)

                {

                    using(System.IO.MemoryStream fileStream = memoryStream)

                    {

                        DocuAction action = docuRef.docuAction();

                        action.attachFile(docuRef,fileName,'',fileStream);

                        info(strFmt('File is uploaded to Sales ID:%1 successfully',salesTable.SalesId));

                    }

                }

            }

        }

    }

    catch(Exception::CLRError)

    {

        System.Exception e = CLRInterop::getLastException();

        if(e != null)

        {

            e = e.InnerException;

            throw error(e.ToString());

        }

    }

}

else

{

    warning("Purchase Order not found.");

}

Thursday, October 23, 2025

call API using x++ D365fo

public void callAPI

{  

System.Net.HttpWebRequest    request;

 System.Net.HttpWebResponse   response;

 System.IO.Stream             dataStream;

 System.IO.StreamReader       reader;

 System.Text.Encoding         encoding = System.Text.Encoding::UTF8;

 System.Text.StringBuilder    responseBuilder = new System.Text.StringBuilder();

 System.Byte[]                byteArray;

 str url ="https://sample.com";

 str body = your request body;

 str accessToken = "euwqyeiuqwiyiuwq";

 try

 {

     request = System.Net.WebRequest::Create(url) as System.Net.HttpWebRequest;

     request.set_Method("POST");

     request.set_ContentType("application/json");

     System.Net.WebHeaderCollection headers = request.get_Headers();

     headers.Add("Access-Token", accessToken);


     byteArray = encoding.GetBytes(body);

     request.set_ContentLength(byteArray.get_Length());


     // This line may throw if headers/content-length/content-type are not set properly

     dataStream = request.GetRequestStream();

     dataStream.Write(byteArray, 0, byteArray.get_Length());

     dataStream.Close();


     response = request.GetResponse() as System.Net.HttpWebResponse;

     dataStream = response.GetResponseStream();

     reader = new System.IO.StreamReader(dataStream, encoding);


     str line = reader.ReadLine();

     while (!CLRInterop::isNull(line))

     {

         responseBuilder.Append(line);

         line = reader.ReadLine();

     }

     reader.Close();

     dataStream.Close();

     response.Close();


     str responseString = responseBuilder.ToString();

    readJsonRequest(responseString );

}

public static void readJsonRequest(str _response)

{

    System.IO.StreamReader   reader;

    System.Text.Json.JsonDocument doc;

    System.Text.Json.JsonElement  root, message, transactionSet, hlLoop, item;

    Newtonsoft.Json.Linq.JObject  contractData    = Newtonsoft.Json.JsonConvert::DeserializeObject(_response);


    Newtonsoft.Json.Linq.JObject  dataObject = contractData.GetValue('data');

    Newtonsoft.Json.Linq.JObject  taxonomyObject = dataObject.GetValue('details');

    Newtonsoft.Json.Linq.JObject  categoriesArray = taxonomyObject.GetValue('categories');

    Newtonsoft.Json.Linq.JArray  edgesArray = categoriesArray.GetValue('item');

    for (int i = 0; i < edgesArray.Count; i++)

    {

        Newtonsoft.Json.Linq.JObject    currentObject = edgesArray.get_item(i);

        Newtonsoft.Json.Linq.JObject    nodeObject =   currentObject.GetValue('node');

        str id =  nodeObject.GetValue('id').ToString();

        str name =  nodeObject.GetValue('name').ToString();

        str fillName =  nodeObject.GetValue('unitPrice').ToString();

    }


}

Call API using x++ D365FO

 System.Net.HttpWebRequest    request; System.Net.HttpWebResponse   response; System.IO.Stream             dataStream; System.IO.StreamReade...