Custom API for the document attachement on the Line level

 Today We have a requirement to create a custom APi so that power apps team can consume you. They will send the URL of the share point and we need to save it on the work order line level for that we need to create 

  1. Create data contracts for input and output and build a needed tree.

  2. Create a custom service.

  3. Add service to a service group.

  4. Build module.

  5. Run a request with a RESTful services tool (Postman.)

Contract :-

[DataContractAttribute]
class IHSWOLineAttachmentContract
{   
    DataAreaId              dataAreaId;
    EntAssetWorkOrderID     workOrderId;
    TradeLineNumber         lineNo;
    URL                     url;

    [DataMember('Company')]
    public str parmDataAreaId(str _value = dataAreaId)
    {
        if (!prmIsDefault(_value))
        {
            dataAreaId = _value;
        }
        return dataAreaId;
    }

    [DataMember('WorkOrderNo')]
    public str parmworkOrderId(EntAssetWorkOrderID _workOrderId = workOrderId)
    {
        if (!prmIsDefault(_workOrderId))
        {
            workOrderId = _workOrderId;
        }
        return workOrderId;
    }

    [DataMember('LineNo')]
    public int64 parmLineNo(TradeLineNumber _lineNo = lineNo)
    {
        if (!prmIsDefault(_lineNo))
        {
            lineNo = _lineNo;
        }
        return lineNo;
    }

    [DataMember('URL')]
    public str parmURL(str _url = url)
    {
        if (!prmIsDefault(_url))
        {
            url = _url;
        }
        return url;
    }

}

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

Service Class :-

class IHSWOLineAttachmentService extends SysOperationServiceBase { System.IO.StringWriter stringWriter; Newtonsoft.Json.JsonTextWriter jsonWriter; [AifCollectionType('_workorderLineList', Types::Class, classStr(IHSWOLineAttachmentContract))] public Notes attachFiles(List _workorderLineList) { ListEnumerator workorderLineListEnum; IHSWOLineAttachmentContract contract; Notes ret; stringWriter = new System.IO.StringWriter(); jsonWriter = new Newtonsoft.Json.JsonTextWriter(stringWriter); jsonWriter.WriteStartArray(); workorderLineListEnum = _workorderLineList.getEnumerator(); while (workorderLineListEnum.moveNext()) { contract = workorderLineListEnum.current(); this.attachFile(contract); } jsonWriter.WriteEndArray(); return stringWriter.ToString(); } /// <summary> /// this is used to attach document to a record /// </summary> public str attachFile(IHSWOLineAttachmentContract _WOLineAttachContract) { DocuRef docuRef; Notes returnMsg; EntAssetWorkOrderLine workOrderLine; EntAssetParameters parameters; if (!CompanyInfo::findDataArea(_WOLineAttachContract.parmDataAreaId()).RecId) { return this.outputMessage(_WOLineAttachContract.parmworkOrderId(),_WOLineAttachContract.parmLineNo(),false,"Company could not be found"); } try { changecompany(_WOLineAttachContract.parmDataAreaId()) { EntAssetWorkOrderTable workOrderTable; parameters = EntAssetParameters::find(); workOrderTable = EntAssetWorkOrderTable::find(_WOLineAttachContract.parmworkOrderId()); select firstonly RecId from workOrderLine where workOrderLine.LineNumber == _WOLineAttachContract.parmLineNo() && workOrderLine.WorkOrder == workOrderTable.RecId; if (workOrderLine.RecId > 0) { ttsbegin; docuRef.clear(); docuRef.RefRecId = workOrderLine.RecId; docuRef.RefTableId = tableNum(EntAssetWorkOrderLine); docuRef.RefCompanyId = _WOLineAttachContract.parmDataAreaId(); docuRef.Notes = _WOLineAttachContract.parmURL(); docuRef.TypeId = parameters.IHSWOLineAttachDocTypeURL; docuRef.Name = DocuType::find(docuRef.TypeId).Name; docuRef.Restriction = DocuRestriction::External; docuRef.insert(); returnMsg = this.outputMessage(_WOLineAttachContract.parmworkOrderId(),_WOLineAttachContract.parmLineNo(),true,"Uploaded successfully"); ttscommit; } else { returnMsg = this.outputMessage(_WOLineAttachContract.parmworkOrderId(),_WOLineAttachContract.parmLineNo(),false,"Work order line could not be found"); } } } catch(Exception::CLRError) { System.Exception ex = CLRInterop::getLastException(); if (ex != null) { ex = ex.get_InnerException(); this.outputMessage(_WOLineAttachContract.parmworkOrderId(),_WOLineAttachContract.parmLineNo(),false,ex.ToString()); } ttsabort; } catch { this.outputMessage(_WOLineAttachContract.parmworkOrderId(),false,_WOLineAttachContract.parmLineNo(),IHSReserveEAAssetsService::GetInfoLogMessages()); ttsabort; } return returnMsg; } private Notes outputMessage(EntAssetWorkOrderID _workId,TradeLineNumber _lineNo,NoYesId _success,Notes _message) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("Status"); jsonWriter.WriteValue(_success ? "Success" : "Failed"); jsonWriter.WritePropertyName("WorkID"); jsonWriter.WriteValue(_workId); jsonWriter.WritePropertyName("LineNumber"); jsonWriter.WriteValue(_lineNo); jsonWriter.WritePropertyName(_success ? "Message" : "ErrorMessage"); jsonWriter.WriteValue(_message); jsonWriter.WriteEndObject(); return stringWriter.ToString(); } }
=====================================================================

Job to test the APi :-

Final class IHSWOLineAttachmentTestJob { /// <summary> /// Class entry point. The system will call this method when a designated menu /// is selected or when execution starts and this class is set as the startup class. /// </summary> /// <param name = "_args">The specified arguments.</param> public static void main(Args _args) { str output; List li = new List(Types::Class); System.Byte[] pdfDocBuffer; System.IO.FileInfo fi_pdfDoc; System.IO.FileStream fs; str Content; // Grant clrinterop permission. new InteropPermission(InteropKind::ClrInterop).assert(); //Load the file fi_pdfDoc = new System.IO.FileInfo(@'C:\Users\Admin3dd47904f2\Desktop\IHS_MaintenanceRequestEntity.axpp'); //Initiallize the byte array by setting the length of the file pdfDocBuffer= new System.Byte[int642int(fi_pdfDoc.get_Length())](); // Stream the file fs= new System.IO.FileStream(fi_pdfDoc.get_FullName(), System.IO.FileMode::Open, System.IO.FileAccess::Read); fs.Read(pdfDocBuffer, 0, pdfDocBuffer.get_Length()); // Convert the file into a base64 string Content = System.Convert::ToBase64String(pdfDocBuffer, 0, pdfDocBuffer.get_Length()); //Revert the access // CodeAccessPermission::revertAssert(); IHSWOLineAttachmentContract contract = new IHSWOLineAttachmentContract(); contract.parmDataAreaId("NG04"); contract.parmworkOrderId('NG04-00000468'); contract.parmLineNo(1); contract.parmURL(@"https://nagarro.com"); li.addEnd(contract); contract = new IHSWOLineAttachmentContract(); contract.parmDataAreaId("NG04"); contract.parmworkOrderId('NG04-00000468'); contract.parmLineNo(1); contract.parmURL(@"https://google.com"); li.addEnd(contract); contract = new IHSWOLineAttachmentContract(); contract.parmDataAreaId("NG04"); contract.parmworkOrderId('NG04-00000477'); contract.parmLineNo(1); contract.parmURL(@"https://google.com"); li.addEnd(contract); contract = new IHSWOLineAttachmentContract(); contract.parmDataAreaId("NG04"); contract.parmworkOrderId('NG04-00000468'); contract.parmLineNo(1); contract.parmURL(@"https://bing.com"); li.addEnd(contract); IHSWOLineAttachmentService service = new IHSWOLineAttachmentService(); output = service.attachFiles(li); //output = service.attachFile(contract); info(output); CodeAccessPermission::revertAssert(); } }

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

Create Service Group and service and run it

 

Comments

Popular posts from this blog

Customization on Sales invoice Report in D365 F&O

75) COC - Create a coc of the table modified method

46) D365 FO: SHAREPOINT FILE UPLOAD USING X++