Code Carriers
while (it.more()) { container errorRow = it.value(); // Get the current element from the iterator // Check if errorRow is valid and has enough elements if (conLen(errorRow) < 4) { error(strFmt("Insufficient columns in errorRow at index %1. Skipping.", rowIdx)); it.next(); // Skip to the next iteration continue; } // Debug: Log the container values to check structure Debug::writeTrace(strFmt("Row: %1, Brand: %2, ItemGroup: %3, Warehouse: %4, Error: %5", rowIdx, conPeek(errorRow, 1), conPeek(errorRow, 2), conPeek(errorRow, 3), conPeek(errorRow, 4))); // Try accessing the cells safely try { // Ensure we're within range if (rowIdx <= worksheet.Dimension.End.Row) { // Write values to Excel worksheet.Cells[rowIdx, 1].Value = conPeek(errorRow, 1); // Brand worksheet.Cells[rowIdx, 2].Value = conPeek(errorRow, 2); // Item Group worksheet.Cells[rowIdx, 3].Value = conPeek(errorRow, 3); // Warehouse ID worksheet.Cells[rowIdx, 4].Value = conPeek(errorRow, 4); // Error Message } else { error(strFmt("Row index %1 exceeds the worksheet row count %2. Skipping.", rowIdx, worksheet.Dimension.End.Row)); } } catch (Exception::Error) { error(strFmt("Error processing row %1: %2", rowIdx, con2str(errorRow))); } it.next(); // Move to the next element rowIdx++; // Move to the next row in Excel }
void generateErrorFile(List errors) { // Create a memory stream to store the Excel file System.IO.MemoryStream memStream = new System.IO.MemoryStream(); // Use OfficeOpenXml to create an Excel file using (OfficeOpenXml.ExcelPackage errorPackage = new OfficeOpenXml.ExcelPackage(memStream)) { // Create a worksheet named "Errors" OfficeOpenXml.ExcelWorksheet errorSheet = errorPackage.get_Workbook().get_Worksheets().Add("Errors"); // Add column headers to the Excel file OfficeOpenXml.ExcelRange cells = errorSheet.get_Cells(); cells.get_Item(1, 1).set_Value("Brand"); cells.get_Item(1, 2).set_Value("Item Group"); cells.get_Item(1, 3).set_Value("Warehouse ID"); cells.get_Item(1, 4).set_Value("Error Message"); // Add rows with error details int rowIdx = 2; // Start adding data from the second row ListIterator it = new ListIterator(errors); while (it.more()) { container errorRow = it.next(); // Assign values to cells from the error container cells.get_Item(rowIdx, 1).set_Value(conPeek(errorRow, 1)); // Brand cells.get_Item(rowIdx, 2).set_Value(conPeek(errorRow, 2)); // Item Group cells.get_Item(rowIdx, 3).set_Value(conPeek(errorRow, 3)); // Warehouse ID cells.get_Item(rowIdx, 4).set_Value(conPeek(errorRow, 4)); // Error Message rowIdx++; // Move to the next row } // Save the generated Excel file into the memory stream errorPackage.Save(); } // Send the file to the user for download str fileName = "ImportErrors.xlsx"; File::SendFileToBrowser(fileName, memStream.ToArray()); }
using Microsoft.Dynamics.ApplicationFoundation.DIXF.Instrumentation; using OfficeOpenXml; class USVPrductInclustionByWHSImportService extends SysOperationServiceBase { USVPrductInclustionByWHSImportContract importContract; void processImport(USVPrductInclustionByWHSImportContract _contract) { #File int excelRowCount, i; OfficeOpenXml.ExcelWorksheet worksheet; OfficeOpenXml.ExcelRange range; List errors = new List(Types::Record); container errorRow; str errorMessage; importContract = _contract; FileUploadTemporaryStorageResult fileUploadResult = importContract.parmFileUploadResult(); if (fileUploadResult && fileUploadResult.getUploadStatus()) { System.IO.Stream stream = fileUploadResult.openResult(); if (stream) { using (OfficeOpenXml.ExcelPackage package = new OfficeOpenXml.ExcelPackage(stream)) { package.Load(stream); worksheet = package.get_Workbook().get_Worksheets().get_Item(1); range = worksheet.Cells; excelRowCount = worksheet.Dimension.End.Row; for (i = 2; i <= excelRowCount; i++) // Start from the second row to skip headers { boolean hasError = false; errorMessage = ""; str brand = range.get_Item(i, 1).Text; str itemGroup = range.get_Item(i, 2).Text; str warehouseIds = range.get_Item(i, 3).Text; // Validation logic if (brand == "") { hasError = true; errorMessage += "Brand is missing; "; } if (itemGroup == "") { hasError = true; errorMessage += "Item Group is missing; "; } if (warehouseIds == "") { hasError = true; errorMessage += "Warehouse ID is missing; "; } if (hasError) { // Add row with error message to the error list errorRow = [brand, itemGroup, warehouseIds, errorMessage]; errors.addEnd(errorRow); } else { // Insert into staging if no errors ttsbegin; USVPrductInclustionByWHSStaging staging; staging.Brand = brand; staging.ItemGroup = itemGroup; staging.WareHouseIds = warehouseIds; staging.insert(); ttscommit; } } // If there are errors, generate error Excel file if (!errors.isEmpty()) { this.generateErrorFile(errors); } } } } } void generateErrorFile(List errors) { // Create new Excel file for errors System.IO.MemoryStream memStream = new System.IO.MemoryStream(); using (OfficeOpenXml.ExcelPackage errorPackage = new OfficeOpenXml.ExcelPackage(memStream)) { OfficeOpenXml.ExcelWorksheet errorSheet = errorPackage.Workbook.Worksheets.Add("Errors"); // Add headers errorSheet.Cells[1, 1].Value = "Brand"; errorSheet.Cells[1, 2].Value = "Item Group"; errorSheet.Cells[1, 3].Value = "Warehouse ID"; errorSheet.Cells[1, 4].Value = "Error Message"; // Add rows with errors int rowIdx = 2; ListIterator it = new ListIterator(errors); while (it.more()) { container errorRow = it.next(); errorSheet.Cells[rowIdx, 1].Value = conPeek(errorRow, 1); errorSheet.Cells[rowIdx, 2].Value = conPeek(errorRow, 2); errorSheet.Cells[rowIdx, 3].Value = conPeek(errorRow, 3); errorSheet.Cells[rowIdx, 4].Value = conPeek(errorRow, 4); rowIdx++; } // Save file to memory stream errorPackage.Save(); } // Send the file for download str fileName = "ImportErrors.xlsx"; File::SendFileToBrowser(fileName, memStream.ToArray()); } }
[Form] public class USVPrductInclustionByWHS extends FormRun { [Control("String")] class USVPrductInclustionByWHS_Brand { /// <summary> /// Provides a custom lookup for the control. /// </summary> public void lookup() { // Initialize SysTableLookup for the lookup functionality SysTableLookup sysTableLookup = SysTableLookup::newParameters(tableNum(EcoResTextValue), this); // Retrieve the specific attribute type using RecId RecId recidAttributetype = 5637155087; EcoResAttributeType localEcoResAttributeType = EcoResAttributeType::find(recidAttributetype); // Define a query for the lookup Query query = new Query(); QueryBuildDataSource qbdsEnumValue = query.addDataSource(tableNum(EcoResTextValue)); QueryBuildDataSource qbdsEnumAttrTypeValue = qbdsEnumValue.addJoin(tableNum(EcoResEnumerationAttributeTypeValue)); QueryBuildDataSource qbdsEnumDomain = qbdsEnumAttrTypeValue.addJoin(tableNum(EcoResAttributeType)); QueryBuildDataSource qbdsEcoResText = qbdsEnumValue.addJoin(tableNum(EcoResTextValueTranslation), JoinMode::OuterJoin); // Set relationships between tables qbdsEnumAttrTypeValue.addLink(fieldNum(EcoResTextValue, RecId), fieldNum(EcoResEnumerationAttributeTypeValue, Value)); qbdsEnumDomain.addLink(fieldNum(EcoResAttributeType, RecId), fieldNum(EcoResEnumerationAttributeTypeValue, AttributeType)); qbdsEcoResText.addLink(fieldNum(EcoResTextValueTranslation, TextValueTable), fieldNum(EcoResTextValue, RecId)); // Apply filters qbdsEnumAttrTypeValue.addRange(fieldNum(EcoResEnumerationAttributeTypeValue, AttributeType)) .value(queryValue(localEcoResAttributeType.RecId)); qbdsEcoResText.addRange(fieldNum(EcoResTextValueTranslation, Language)) .value(queryValue(SystemParameters::getSystemLanguageId())); // Apply sorting qbdsEnumAttrTypeValue.addSortField(fieldNum(EcoResEnumerationAttributeTypeValue, OrdinalNumber), SortOrder::Ascending); // Set the query for the lookup sysTableLookup.parmQuery(query); // Add fields to display in the lookup sysTableLookup.addLookupfield(fieldNum(EcoResTextValue, TextValue)); // Main display field sysTableLookup.addLookupfield(fieldNum(EcoResTextValue, RecId)); // Optionally include additional fields // Execute the lookup sysTableLookup.performFormLookup(); } } }
Congratulations on passing the MB-500 exam! Here's a draft email you can send to your manager:
Subject: Successfully Passed MB-500: Microsoft Certified: Dynamics 365: Finance and Operations Apps Developer Associate
Dear [Manager's Name],
I am pleased to inform you that I have successfully completed and passed the MB-500: Microsoft Certified: Dynamics 365: Finance and Operations Apps Developer Associate exam. This certification has further enhanced my skills and knowledge in Dynamics 365 Finance and Operations, particularly in areas such as solution design, AOT development, code testing, data integration, and security optimization.
I look forward to applying these skills to our ongoing and future projects, and I am confident that this achievement will contribute positively to our team's objectives.
Thank you for your continued support.
Best regards,
[Your Name]
SELECT TOP 1 WorkId, WorkStatus, OrderNum, ShipmentId FROM workTableSO WHERE OrderNum = @SalesId AND WorkTransType = 'Sales' AND EXISTS ( SELECT 1 FROM workLineSOLine WHERE workTableSO.WorkId = workLineSOLine.WorkId AND workLineSOLine.ItemId = @ItemId AND workLineSOLine.InventTransId = @InventTransId );
/// <summary> /// Creates load based on Excel file /// </summary> /// <remarks> /// Jan 30, 2019 - ansari. - Mod 018 Load creation import /// </remarks> using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; class ANSARILoadCreationService { /// <summary> /// Creates load based on Excel file /// </summary> /// <param name = "_fileUrl">Location of Excel file</param> /// <param name = "_siteId">Site to create load for</param> /// <param name = "_locationId">Location to create load for</param> /// <param name = "_loadTemplateId">Template for load</param> /// <remarks> /// Jan 30, 2019 - ANSARI. /// - Search for item based on ItemId or NameAlias /// </remarks> public void process( str _fileUrl, InventSiteId _siteId, InventLocationId _locationId, WHSLoadTemplateId _loadTemplateId, ANSARIWHSASNLicensePlateId _licensePlateId) //03/14/2024 - - BUG 255602 - CR 303 - Add license plate field for manual load creation import { container con, errorList; int i, curLine, purchLineNum; boolean hasError = false; Set purchRecIdSet = new Set(Types::AnyType); PurchId purchId, nextPurchId; ItemId itemId; WHSLoadTable whsLoadTable; WHSLoadLine whsLoadLine; PurchLine purchLine, validatePurchLine; PurchTable purchTable; WHSShipmentTable whsShipmentTable; WHSParameters whsParameters = WHSParameters::find(); WHSUOMStructure whsUOMStructure; //03/14/2024 - - BUG 255602 - CR 303 - Add license plate field for manual load creation import ttsbegin; // Build Header whsLoadTable.LoadId = NumberSeq::newGetNum(NumberSeqReference::findReference(extendedTypeNum(WHSLoadId))).num(); whsLoadTable.InventSiteId = _siteId; whsLoadTable.InventLocationId = _locationId; whsLoadTable.initFromloadTemplateId(_loadTemplateId); whsLoadTable.LoadDirection = WHSLoadDirection::Inbound; whsLoadTable.LoadStatus = WHSLoadStatus::Open; whsLoadTable.loadTemplateId = _loadTemplateId; whsLoadTable.CarrierCode = whsParameters.ANSARILoadCreationShippingCarrier; whsLoadTable.CarrierServiceCode = whsParameters.ANSARILoadCreationCarrierService; whsLoadTable.ModeCode = whsParameters.ANSARILoadCreationMode; whsLoadTable.ANSARIEDIASNLicensePlateId = _licensePlateId; //04/12/2024 - - BUG 255602 - CR 303 - Add license plate field for manual load creation import whsLoadTable.insert(); // Read excel file System.Byte[] byteArray; System.IO.Stream stream; stream = File::UseFileFromURL(_fileUrl); con = this.readExcelData(stream); curLine = 1; purchLineNum = 1; for (i=1; i <= conLen(con); i++) { purchId = conPeek(conPeek(con, curLine), 1); nextPurchId = conPeek(conPeek(con, curLine - 1), 1); itemId = conPeek(conPeek(con, curLine), 2); purchTable = PurchTable::find(purchId); if (PurchTable::exist(purchId)) { if (purchId != nextPurchId) { // Create ShipmentId whsShipmentTable.clear(); whsShipmentTable.ShipmentId = whsShipmentTable.getShipmentId(); whsShipmentTable.LoadId = whsLoadTable.LoadId; whsShipmentTable.WorkTransType = WHSWorkTransType::Purch; whsShipmentTable.OrderNum = purchTable.PurchId; whsShipmentTable.AccountNum = purchTable.OrderAccount; whsShipmentTable.DeliveryName = purchTable.DeliveryName; whsShipmentTable.DeliveryPostalAddress = purchTable.DeliveryPostalAddress; whsShipmentTable.CountryRegionISOCode = purchTable.CountyOrigDest; whsShipmentTable.DlvTermId = purchTable.DlvTerm; whsShipmentTable.InventSiteId = _siteId; whsShipmentTable.InventLocationId = _locationId; whsShipmentTable.CarrierCode = whsLoadTable.CarrierCode; whsShipmentTable.CarrierServiceCode = whsLoadTable.CarrierServiceCode; whsShipmentTable.CarrierGroupCode = whsLoadTable.CarrierGroupCode; whsShipmentTable.LoadDirection = WHSLoadDirection::Inbound; whsShipmentTable.CustomerRef = purchTable.VendorRef; whsShipmentTable.insert(); //03/14/2024 - - BUG 255602 - CR 303 - Add license plate field for manual load creation import - START whsUOMStructure.clear(); whsUOMStructure.LoadId = whsShipmentTable.LoadId; whsUOMStructure.ShipmentId = whsShipmentTable.ShipmentId; whsUOMStructure.Module = WHSModule::Purch; whsUOMStructure.LicensePlateId = _licensePlateId; whsUOMStructure.insert(); //03/14/2024 - - BUG 255602 - CR 303 - Add license plate field for manual load creation import - END } InventTable inventTable; // Search for item based on ItemId or Search Name select firstonly ItemId from inventTable where inventTable.ItemId == itemId exists join validatePurchLine where validatePurchLine.PurchId == purchTable.PurchId && validatePurchLine.ItemId == inventTable.ItemId; if (!inventTable.ItemId) { select firstonly ItemId from inventTable where inventTable.NameAlias == itemId exists join validatePurchLine where validatePurchLine.PurchId == purchTable.PurchId && validatePurchLine.ItemId == inventTable.ItemId; if (inventTable.ItemId) { itemId = inventTable.ItemId; } else { errorList += strFmt("@ANSARI:LoadPOError" + '\n', purchId, itemId); curLine++; hasError = true; continue; } } select firstonly purchLine where purchLine.PurchId == purchId && purchLine.ItemId == itemId; if (!purchRecIdSet.in(purchLine.RecId)) { // Build load lines whsLoadLine.clear(); whsLoadLine.initFromPurchLine(purchLine); whsLoadLine.LoadId = whsLoadTable.LoadId; whsLoadLine.InventTransType = InventTransType::Purch; whsLoadLine.LoadDirection = WHSLoadDirection::Inbound; whsLoadLine.OrderNum = purchLine.PurchId; whsLoadLine.ItemId = purchLine.ItemId; whsLoadLine.Qty = conPeek(conPeek(con, curLine), 3); whsLoadLine.UOM = conPeek(conPeek(con, curLine), 4); whsLoadLine.PackingQty = WHSInventTable::getDefaultPackingQty(whsLoadLine.ItemId, purchLine.InventDimId); whsLoadLine.ShipmentId = whsShipmentTable.ShipmentId; whsLoadLine.insert(); } else { // added by ext-ransari ttsbegin; select forupdate whsLoadLine where whsLoadLine.OrderNum == purchLine.PurchId && whsLoadLine.ItemId == purchLine.ItemId;; whsLoadLine.Qty += conPeek(conPeek(con, curLine), 3); whsLoadLine.update(); ttscommit; // added by ext-ransari } if (curLine == i) { curLine++; } purchRecIdSet.add(purchLine.RecId); } else { throw error(strFmt("@ANSARI:LoadPOError", purchId, itemId)); } } if (hasError == true) { container shipments = whsLoadTable.getShipmentIds(); if (shipments != conNull()) { info(con2Str(errorList, '\n')); } else { throw error(con2Str(errorList, '\n')); } } info(strFmt("@ANSARI:LoadCreated", whsLoadTable.LoadId)); ttscommit; } /// <summary> /// Reads data from Excel sheet /// </summary> /// <param name = "_stream">Stream of Excel file</param> /// <returns>Two dimensional container hold Excel data</returns> /// <remarks> /// Jan 30, 2019 - ANSARI - Mod 018 Load creation import /// </remarks> public container readExcelData(System.IO.Stream _stream) { OfficeOpenXml.ExcelWorksheet worksheet; OfficeOpenXml.ExcelPackage package = new OfficeOpenXml.ExcelPackage(_stream); int iRowCount,iCellCount; anytype anyData; container conRow,ret; WHSParameters whsParameters = WHSParameters::find(); try { if (package) { worksheet = package.get_Workbook().get_Worksheets().Copy(whsParameters.ANSARILoadExcelSheet, whsParameters.ANSARILoadExcelJournal); var cells = worksheet.get_Cells(); iRowCount = worksheet.get_Dimension().get_End().get_Row(); iCellCount = worksheet.get_Dimension().get_End().get_Column(); // Start at row 2 to allow for headers in Excel for (int i=2;i<=iRowCount;i++) { conRow = conNull(); for (int j=1;j<=iCellCount;j++) { anyData= cells.get_Item(i, j).get_Value(); if (!anyData && j ==1) { break; } if (anyData) { conRow += anyData; } else { conRow += ""; } } if (conRow) { conRow += iRowCount; ret = conIns(ret,i,conRow); } } } } catch (Exception::CLRError) { throw error("@SYS135884"); } return ret; } }
[Form] public class ANSARILoadCreationImport extends FormRun { WorkflowImportDialog workflowImportDialog; FilePath configurationFilePath; System.IO.Stream fileOpen; public void init() { FileUpload uploadControl; WHSParameters whsParameters = WHSParameters::find(); super(); ANSARILoadTemplateId.text(whsParameters.ANSARIWHSLoadTemplateId); uploadControl = fileuploadControl; uploadControl.notifyUploadCompleted += eventhandler(this.UploadCompleted); } /// <summary> /// /// </summary> public void UploadCompleted() { FileUploadTemporaryStorageResult fileUploadResult = FileUploadControl.getFileUploadResult(); if (fileUploadResult != null && fileUploadResult.getUploadStatus()) { configurationFilePath = fileUploadResult.getDownloadUrl(); fileOpen = fileUploadResult.openResult(); } } public WorkflowImportDialog parmWorkflowImportDialog(WorkflowImportDialog _workflowImportDialog = workflowImportDialog) { workflowImportDialog = _workflowImportDialog; return workflowImportDialog; } [Control("String")] class ANSARIWHSASNLicensePlateId { /// <summary> /// /// </summary> /// <returns></returns> /// //04/12/2024 - - BUG 255602 - CR 303 - Add license plate field for manual load creation import public boolean validate() { var pattern = @"[A-Za-z]"; boolean ret; var result1 = new System.Text.RegularExpressions.Regex(pattern).Match(this.valueStr()).Success; ret = super(); if(result1 == false) { ret = checkFailed("Invalid format"); } return ret; } //04/12/2024 - - BUG 255602 - CR 303 - Add license plate field for manual load creation import } [Control("CommandButton")] class OK { public void clicked() { ANSARILoadCreationService service = new ANSARILoadCreationService(); if(ANSARIWHSASNLicensePlateId.valueStr() == "") //04/12/2024 - BUG 255602 - CR 303 - Add license plate field for manual load creation import { throw Error("BOL/Container must be filled in"); } else { service.process(configurationFilePath, ANSARIInventSiteId.valueStr(), ANSARIInventLocationId.valueStr(), ANSARILoadTemplateId.valueStr(), ANSARIWHSASNLicensePlateId.valueStr()); //03/14/2024 - - BUG 255602 - CR 303 - Add license plate field for manual load creation import super(); } } } }
python3 -m pip install -r requirements.txt python3 manage.py makemigrations python3 manage.py migrate --run-syncdb python3 manage.py runserver ctrl +c sh run.sh ctrl +c sh install.sh sh test.sh
Admin
from django.contrib import admin from .models import Item # Register your models here. admin.site.register(Item)
urls
from django.urls import include, path from django.contrib import admin from inventoryapp.views import InventoryItemView, SortItemsView, QueryItemsView # Add your URLS in respective place. urlpatterns = [ path('admin/', admin.site.urls), path('inventory/items/', InventoryItemView.as_view(), name='inventory-item'), path('inventory/items/<int:pk>/', InventoryItemView.as_view(), name='inventory-detail'), path('items/sort/', SortItemsView.as_view(), name='sort-items'), path('items/query/<str:category>/', QueryItemsView.as_view(), name='query-items'), ]
View
from rest_framework import viewsets from rest_framework.views import APIView from rest_framework.response import Response from inventoryapp.serializers import ItemSerializer from .models import Item from rest_framework import status # Create your views here class SortItemsView(APIView): def get(self, request): items = Item.objects.all().order_by('price') serializer = ItemSerializer(items, many=True) return Response(serializer.data) class QueryItemsView(APIView): def get(self, request, category): items = Item.objects.filter(category=category) serializer = ItemSerializer(items, many=True) return Response(serializer.data) class InventoryItemView(APIView): def get(self, request): items = Item.objects.all() serializer = ItemSerializer(items, many=True) return Response(serializer.data) def post(self, request): serializer = ItemSerializer(data=request.data) if serializer.is_valid(): barcode = serializer.validated_data['barcode'] if Item.objects.filter(barcode=barcode).exists(): return Response({'barcode': ['item with this barcode already exists']}, status=status.HTTP_400_BAD_REQUEST) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk): try: item = Item.objects.get(pk=pk) except Item.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) item.delete() return Response(status=status.HTTP_204_NO_CONTENT)
from django.contrib import admin from .models import Item # Register your models here. admin.site.register(Item)
from rest_framework import serializers from .models import Item #Create your serializers here. class ItemSerializer(serializers.ModelSerializer): class Meta: model=Item fields= '__all__'
from django.db import models # Create your models here. class Item(models.Model): id =models.AutoField() name=models.CharField(max_length=250) category=models.CharField(max_length=250) price=models.IntegerField() quantity=models.IntegerField() barcode=models. IntegerField (unique=True)
// salestable_extension // Add a tax exempt flag to customer account and Sales orders - Start [SysClientCacheDataMethodAttribute(true)] display NoYesId atnylaTaxExempt() { CustTable custTable; select firstonly ATNYLATaxExempt from custTable where custTable.AccountNum == this.CustAccount; return custTable.ATNYLATaxExempt; } // Add a tax exempt flag to customer account and Sales orders - Start
/// <summary> /// This method will sent email to sales invoice /// </summary> public void sentEmailToInvoicePrint(RecId _jourRecId) { SalesInvoiceHeaderFooterTmp salesInvoiceHeaderTmpLoc; SalesInvoiceTmp salesInvoiceTmpLoc; CustInvoiceJour custInvoiceJourLoc1; SalesLine salesLineLoc; SalesId salesIdloc; int countSalesId,countInvoiceSalesId; CustInvoiceTrans custInvoiceTransLoc; SalesId salesIDMap; int countPrintInvoiceMap; CustParameters custParameters; select firstonly custParameters; if (custParameters.ATNYLAInvoicePrintingNoYes == NoYes::Yes && custParameters.ATNYLAPrintEmail) { //retrieve from map mapEnumerator = map.getEnumerator(); while (mapEnumerator.moveNext()) { salesIDMap = mapEnumerator.currentKey(); countPrintInvoiceMap = mapEnumerator.currentValue(); if (countPrintInvoiceMap > 0 && salesIDMap) { select count(RecId) from custInvoiceTransLoc join custInvoiceJourLoc1 where custInvoiceJourLoc1.salesid == salesIDMap && custInvoiceJourLoc1.InvoiceId == custInvoiceTransLoc.InvoiceId && custInvoiceJourLoc1.InvoiceDate == custInvoiceTransLoc.InvoiceDate; countSalesId = custInvoiceTransLoc.RecId; select firstonly custInvoiceTransLoc join custInvoiceJourLoc1 where custInvoiceJourLoc1.salesid == salesIDMap && custInvoiceJourLoc1.InvoiceId == custInvoiceTransLoc.InvoiceId && custInvoiceJourLoc1.InvoiceDate == custInvoiceTransLoc.InvoiceDate; salesIdloc = custInvoiceTransLoc.SalesId; if (countSalesId != countPrintInvoiceMap && salesIdloc) { ATNYLAEmailer::sendSMTPEmail(custParameters.ATNYLAPrintEmail,strFmt('@ATNYLA:MissInvLine',salesIdloc),strFmt('@ATNYLA:SOMissingPrint',salesIdloc)); } } } } }
class ATNYLAProgramProductsTableImport extends RunBaseBatch { DialogRunbase dialog; DialogField dialogDefinitionGroupUpdate; DMFDefinitionGroupName definitionGroupUpdate; Filename filename; System.IO.Stream fileStream; SharedServiceUnitFileID fileID; DMFDefinitionGroupName definitionGroupName; #define.definitionGroupName("Program products import") #define.CurrentVersion(3) #localmacro.CurrentList definitionGroupUpdate, filename, fileID #endmacro private const str OkButtonName = 'OkButton'; private const str FileUploadName = 'FileUpload'; /// <summary> /// /// </summary> public boolean canGoBatch() { return true; } /// <summary> /// /// </summary> protected boolean canGoBatchJournal() { return true; } /// <summary> /// Returns a class that contains the methods that are described by the <c>RunBaseDialogable</c> /// interface. /// </summary> /// <returns> /// A class that contains the methods that are described by the <c>RunBaseDialogable</c> interface. /// </returns> /// <remarks> /// A dialog can be either built by using the <c>Dialog</c> class or by using a class that is created /// in the Application Object Tree (AOT). /// </remarks> public Object dialog() { DialogGroup dialogGroup; FormBuildControl formBuildControl; FileUploadBuild dialogFileUpload; dialog = new DialogRunbase(ATNYLAProgramProductsTableImport::description(), this); dialogDefinitionGroupUpdate = dialog.addFieldValue(extendedTypeStr(DMFDefinitionGroupName), definitionGroupUpdate); dialogDefinitionGroupUpdate.registerOverrideMethod(methodStr(FormStringControl, lookup), methodStr(ATNYLAProgramProductsTableImport, lookUpDefinitionGroup), this); dialogDefinitionGroupUpdate.value(#definitionGroupName); dialogGroup = dialog.addGroup(ATNYLAProgramProductsTableImport::description()); formBuildControl = dialog.formBuildDesign().control(dialogGroup.name()); dialogFileUpload = formBuildControl.addControlEx(classstr(FileUpload), FileUploadName); dialogFileUpload.style(FileUploadStyle::MinimalWithFilename); dialogFileUpload.fileTypesAccepted('.xlsx,.xls,.xlsm'); dialogFileUpload.baseFileUploadStrategyClassName(classstr(FileUploadTemporaryStorageStrategy)); dialogFileUpload.fileNameLabel("@SYS308842"); return dialog; } /// <summary> /// Looks up the definition group name. /// </summary> /// <param name="_control"> /// The look up control. /// </param> public void lookUpDefinitionGroup(FormStringControl _control) { Query query; QueryBuildDataSource qbds; SysTableLookup lookup; container con; str rangeValue; DMFDefinitionGroupEntity definitionGroupEntity; #define.Import('Program products') while select DefinitionGroup from definitionGroupEntity where definitionGroupEntity.Entity == #Import && definitionGroupEntity.DefinitionGroup == #definitionGroupName { con += definitionGroupEntity.DefinitionGroup; } rangeValue = con2Str(con, ','); query = new Query(); qbds = query.addDataSource(tableNum(DMFDefinitionGroup)); qbds.addRange(fieldNum(DMFDefinitionGroup, DefinitionGroupName)).value(rangeValue); lookup = SysTableLookup::newParameters(tableNum(DMFDefinitionGroup), _control, true); lookup.parmQuery(query); lookup.addLookupField(fieldNum(DMFDefinitionGroup, DefinitionGroupName), true); lookup.addLookupField(fieldNum(DMFDefinitionGroup, Description)); lookup.performFormLookup(); } /// <summary> /// Disables the dialog Ok button until the file upload is complete. /// </summary> /// <param name="_dialog">The <c>Runbase</c> dialog object.</param> public void dialogPostRun(DialogRunbase _dialog) { FileUpload fileUpload = this.getFormControl(_dialog, FileUploadName); fileUpload.notifyUploadCompleted += eventhandler(this.uploadCompleted); this.setDialogOkButtonEnabled(_dialog, false); } /// <summary> /// Displays the summary of the execution /// </summary> public void executionStatus() { DMFDefinitionGroupExecution definitionGroupExecution; DMFExecutionSummaryStatus summaryStatus; DMFExecution execution; select firstonly ExecutionId, NoOfRecords, NumOfTargetNew, NumOfTargetUpdated from definitionGroupExecution order by CreatedDateTime desc where definitionGroupExecution.DefinitionGroup == #definitionGroupName; execution = DMFExecution::find(definitionGroupExecution.ExecutionId); summaryStatus = execution.GetExecutionSummaryStatus(); info(strFmt("@SYS90632",DateTimeUtil::applyTimeZoneOffset(DateTimeUtil::utcNow(), DateTimeUtil::getUserPreferredTimeZone()))); info(strfmt("@ATNYLA:FileReadFrom", filename)); info(strfmt("@ATNYLA:RowsInserted", definitionGroupExecution.NumOfTargetNew)); info(strfmt("@ATNYLA:RecordsUpdated", definitionGroupExecution.NumOfTargetUpdated)); info(strFmt("@ATNYLA:ImportStatus", DMFExecutionStatusHelper::GetExecutionSummaryStatusText(summaryStatus))); info(strFmt("@ATNYLA:ExecutionId", definitionGroupExecution.ExecutionId)); info("@ATNYLA:Importcompleted"); } /// <summary> /// After the file has been uploaded, the Ok button is enabled. /// </summary> protected void uploadCompleted() { FileUpload fileUpload = this.getFormControl(dialog, FileUploadName); fileUpload.notifyUploadCompleted -= eventhandler(this.UploadCompleted); filename = fileUpload.fileName(); this.setDialogOkButtonEnabled(dialog, true); } /// <summary> /// Enables or disables the dialog Ok button. /// </summary> /// <param name = "_dialog">The <c>Runbase</c> dialog object.</param> /// <param name = "_isEnabled">Indicates to enable or disable the Ok button.</param> protected void setDialogOkButtonEnabled(DialogRunbase _dialog, boolean _isEnabled) { FormControl okButtonControl = this.getFormControl(_dialog, OkButtonName); if (okButtonControl) { okButtonControl.enabled(_isEnabled); } } /// <summary> /// Gets the form control /// </summary> /// <Returns> Returns the form control </Returns> protected FormControl getFormControl(DialogRunbase _dialog, str _controlName) { return _dialog.formRun().control(_dialog.formRun().controlId( _controlName)); } /// <summary> /// Gets the user input values from dialog /// </summary> /// /// <Returns> Returns True/False </Returns> public boolean getFromDialog() { boolean ret; ret = super(); definitionGroupUpdate = dialogDefinitionGroupUpdate.value(); FileUpload fileUploadControl = this.getFormControl(dialog, FileUploadName); FileUploadTemporaryStorageResult fileUploadResult = fileUploadControl.getFileUploadResult(); if (fileUploadResult != null && fileUploadResult.getUploadStatus()) { fileID = fileUploadResult.getFileId(); } return ret; } /// <summary> /// Contains the code that does the actual job of the class. /// </summary> public void run() { DMFExecutionId executionId; DMFDefinitionGroup definitionGroup; DMFDefinitionGroupEntity definitionGroupEntity; boolean executeTargetDuringInitialImport; DMFDefinitionGroupExecution definitionGroupExecution; DMFExecutionSummaryStatus summaryStatus; DMFExecution execution; try { definitionGroup = ATNYLAProgramProductsTableImport::findDMFDefinitionGroup(definitionGroupUpdate); ATNYLAProgramProductsTableImport::applyTransforms(fileID, definitionGroup); definitionGroupEntity = ATNYLAProgramProductsTableImport::findDMFDefinitionGroupEntity(definitionGroup); executionId = DMFUtil::setupNewExecution(definitionGroup.DefinitionGroupName); // Determine if source to target should happen on initial import based on if we are in batch or not. executeTargetDuringInitialImport = !this.parmInBatch(); // Find execution definitionGroupExecution = DMFDefinitionGroupExecution::find(definitionGroup.DefinitionGroupName, definitionGroupEntity.Entity, executionId, true); summaryStatus = definitionGroupExecution.GetExecutionSummaryStatus(); execution = DMFExecution::find(definitionGroupExecution.ExecutionId); //To showing info related to count definitionGroupExecution.FilePath = fileID; definitionGroupExecution.IsTransformed = NoYes::Yes; definitionGroupExecution.ExecuteTargetStep = executeTargetDuringInitialImport; definitionGroupExecution.update(); DMFQuickImportExport::doPGImport(definitionGroup.DefinitionGroupName, executionId, executeTargetDuringInitialImport); // If we still need to move from source to target, kick off that process now. if (!executeTargetDuringInitialImport) { DMFDefinitionGroupExecution executionSourceToTarget; update_recordset executionSourceToTarget setting IsSelected = NoYes::Yes where executionSourceToTarget.ExecutionId == executionId; DMFWriteExecutionParameters executionParameters = DMFWriteExecutionParameters::construct(); executionParameters.parmDefinitionGroup(definitionGroup.DefinitionGroupName); executionParameters.parmsourceTarget(DMFSourceTarget::Source); executionParameters.parmSelectedData(NoYes::No); executionParameters.parmErrorStatus(NoYes::No); executionParameters.parmSkipFormNavigation(NoYes::Yes); DMFExecution dmfExecution = DMFExecution::find(executionId, true); Args args = new Args(); args.record(dmfExecution); args.parmObject(executionParameters); args.parmEnum(NoYes::No); new MenuFunction(menuItemActionStr(DMFEntityWriterBatch), MenuItemType::Action).run(args); } this.executionStatus(); } catch(Exception::Error) { info(strFmt("%1",Exception::Error)); } } /// <summary> /// /// </summary> public boolean runsImpersonated() { return true; } /// <summary> /// Packs the state of the object /// </summary> /// <returns> /// Returns the packed container /// </returns> public container pack() { return [#CurrentVersion, #CurrentList]; } /// <summary> /// Unpacks the received contaienr object /// </summary> /// <parameter> Container with the packed status</parameter> /// <returns> /// Returns the packed container /// </returns> public boolean unpack(container _packedClass) { Integer version = conPeek(_packedClass, 1); switch (version) { case #CurrentVersion: [version, #CurrentList] = _packedClass; break; default: return false; } return true; } /// <summary> /// Validates the user input information /// </summary> /// <parm = _calledFrom>The caller object</parm> /// <returns> /// Returns True/False /// </returns> public boolean validate(Object _calledFrom = null) { boolean ret = true; if (!definitionGroupUpdate) { ret = checkFailed("@DMF1432"); } if (!filename) { ret = checkFailed("@SYS18624"); } return ret; } /// <summary> /// Constructs the ATNYLAProductUOMConversionsImport object /// </summary> /// <returns>Returns the ATNYLAProductUOMConversionsImport object</returns> public static ATNYLAProgramProductsTableImport construct() { return new ATNYLAProgramProductsTableImport(); } /// <summary> /// Provides caption for the dialog /// </summary> /// <returns>Reutrns the caption of the dialog</returns> public static ClassDescription description() { return ("Program products import"); } /// <summary> /// Provides the entry point for the ATNYLAPurchaseOrdersImportInsertDialog dialog class /// </summary> /// <param name = "args"></param> public static void main(Args args) { ATNYLAProgramProductsTableImport programProductsTableImport; programProductsTableImport = ATNYLAProgramProductsTableImport::construct(); if (programProductsTableImport.prompt()) { programProductsTableImport.runOperation(); } } /// <summary> /// /// </summary> protected boolean canRunInNewSession() { return false; } /// <summary> /// /// </summary> private static DMFLocalFilePath applyTransforms(SharedServiceUnitFileID _uploadedStatement, DMFDefinitionGroup definitionGroup) { DMFDefinitionGroupEntity definitionGroupEntity = ATNYLAProgramProductsTableImport::findDMFDefinitionGroupEntity(definitionGroup); DMFExecutionId executionId = DMFUtil::setupNewExecution(definitionGroup.DefinitionGroupName); DMFDefinitionGroupExecution execution = DMFDefinitionGroupExecution::find( definitionGroup.DefinitionGroupName, definitionGroupEntity.Entity, executionId, true); execution.IsTransformed = NoYes::No; DMFLocalFilePath filePath = execution.applyTransforms(_uploadedStatement); DMFExecution e = DMFExecution::find(executionId, true); e.delete(); return filePath; } /// <summary> /// /// </summary> private static DMFDefinitionGroupEntity findDMFDefinitionGroupEntity(DMFDefinitionGroup _definitionGroup) { DMFDefinitionGroupEntity definitionGroupEntity; DMFEntity dmfEntity; select firstonly RecId, Entity from definitionGroupEntity exists join dmfEntity where definitionGroupEntity.DefinitionGroup == _definitionGroup.DefinitionGroupName && dmfEntity.EntityName == definitionGroupEntity.Entity && dmfEntity.TargetEntity == dataentityviewstr(ATNYLAProgramProductsTableEntity); if (!definitionGroupEntity) { throw error(strFmt("@DMF:DMFNoEntityExists", _definitionGroup.DefinitionGroupName)); } return definitionGroupEntity; } /// <summary> /// /// </summary> private static DMFDefinitionGroup findDMFDefinitionGroup(DMFDefinitionGroupName definitionGroupName) { DMFDefinitionGroup definitionGroup; select firstonly definitionGroup where definitionGroup.DefinitionGroupName == definitionGroupName; //PurchParameters::find().ATNYLAProcessingGroupDisplayUpdate;//DMF import data project return definitionGroup; } }