Trending: Jawaan


Quick and Dirty Code to Create and Post Counting Journals in Dynamics AX


A couple of guys asked me for code to import inventory in to ax using Counting journals... so here goes..

I basically created a table, called StockLevelImport and added basic fields to it such as itemid, location, warehouse, size,colour and quantity.. Notice: other dimensions such as config, batch were not added..however you can easily do so if you like.

The following bit of code was use to import the stock file in to ax (basically import a csv file)

static int importFromFile()

{

CommaIo fileIn;

StockLevelImport stockLevelImport;

container fileInCon;

FileIOPermission perm;

int recordsInserted;

;

#stockLevelImport

// the macro holds the full file name

recordsInserted = 0;

perm = new FileIOPermission(#stockLevelImportFile,'r');

if (perm == null)

{

error("FileIoPermission error");

return 0;

}

// Grants permission to execute the CommaIo.new method.

// CommaIo.new runs under code access security.

perm.assert();

fileIn = new CommaIo(#stockLevelImportFile,'r');

delete_from stockLevelImport; // clear table before import

fileIn.inFieldDelimiter(',');

startLengthyOperation();

ttsbegin;

while(fileIn.status() == IO_Status::Ok)

{

fileInCon = connull();

fileInCon = fileIn.read();

stockLevelImport.ItemId = conpeek(fileInCon,1);

stockLevelImport.InventLocationId = conpeek(fileInCon,2);

stockLevelImport.WMSLocationId = conpeek(fileInCon,3);

stockLevelImport.InventQty = conpeek(fileInCon,4);

stockLevelImport.InventColorId = conpeek(fileInCon,6);

stockLevelImport.InventSizeId = conpeek(fileInCon,5);

if(fileIn.status() == IO_Status::Ok) // to prevent the last insert

stockLevelImport.insert();

recordsInserted++;

}

ttscommit;

endLengthyOperation();

CodeAccessPermission::revertAssert();

return recordsInserted;

}

The code below is where meat of the operations are performed..

void countIt()

{

date transDate;

StockLevelImport stockLevelImport;

inventJournalName iJournalName;

InventJournalTable iJournalTable;

InventJournalTrans iJournalTrans;

real line;

Numberseq numberseq;

InventJournalCheckPost checkPost;

SysOperationProgress prog;

int progTot;// total count for progress bar

int ss;

InventTable inventTable;

InventTableModule inventTableModule;

inventdim idimm;

;

transDate = systemdateget();

#aviFiles

line = 1.00;

select count(RecId) from stockLevelImport;

progTot = stockLevelImport.RecId;

prog = SysOperationProgress::newGeneral(#aviStopWatch,"Adding Stock...", progTot);

numberseq = Numberseq::newGetNumFromCode(InventParameters::numRefInventJournalId().NumberSequence);

iJournalName = inventJournalName::find(InventParameters::find().CountJournalNameId);

if(iJournalName.RecId == 0)

throw error("NO counting journal Name foud");

ttsbegin;

iJournalTable.initFromInventJournalName(iJournalName);

iJournalTable.JournalId = numberseq.num();

iJournalTable.Reservation = ItemReservation::Automatic;

iJournalTable.SystemBlocked = NoYes::Yes;

iJournalTable.insert();

inventTableModule.clear();

inventTableModule = null;

stockLevelImport = null;

// while select inventtable

while select stockLevelImport where stockLevelImport.InventQty

join Price from inventTableModule where inventTableModule.ItemId == stockLevelImport.ItemId && inventTableModule.ModuleType == ModuleInventPurchSales::Invent

{

ss++;

iJournalTrans.clear();

iJournalTrans.initFromInventJournalTable(iJournalTable);

iJournalTrans.LineNum = line;

iJournalTrans.CostAmount = decround((stockLevelImport.InventQty * inventTableModule.Price),2);

iJournalTrans.CostPrice = inventTableModule.Price;

iJournalTrans.Counted = stockLevelImport.InventQty;

iJournalTrans.InventDimId = this.getDim();

if(iJournalTrans.InventDimId == "")

{

info("cannot create dimension for item " + iJournalTrans.ItemId);

continue;

}

iJournalTrans.JournalType = iJournalTable.JournalType;

iJournalTrans.PriceUnit = 1.0;

iJournalTrans.ProfitSet = CostProfitSet::Standard; // Standard

iJournalTrans.ProjSalesPrice = 0.0;

iJournalTrans.Qty = stockLevelImport.InventQty;

iJournalTrans.TransDate = transDate;

iJournalTrans.ItemId = stockLevelImport.ItemId;

iJournalTrans.initFromInventTable(InventTable::find(stockLevelImport.ItemId),false,false,false);

if(!iJournalTrans.Dimension)

{

info("Dimenstions not specified for item " + iJournalTrans.ItemId);

continue;

}

if(!iJournalTrans.validateWrite())

{

info("Could not validate write");

continue;

}

iJournalTrans.insert();

line++;

// progress bar

prog.setText("Item : " + stockLevelImport.ItemId);

prog.setCount(ss);

} // end while on Lines

iJournalTable.NumOfLines = line;

iJournalTable.update();

// Posting the Journal:

prog.setText("creating inventJournal...hold on");

prog.setCount(1);

if(BOX::yesNo("Do you want to post the Journal? " ,DialogButton::Yes) == DialogButton::Yes)

{

checkPost = InventJournalCheckPost::newJournalCheckPost(JournalCheckPostType::Post,iJournalTable);

checkpost.run();

}

iJournalTable.SystemBlocked = NoYes::No;

iJournalTable.update();

ttscommit;

prog.kill();

info("Lines posted = " + int2str(ss));

}

And finally a small method to find the correct inventDimId that is to be used on the journal Line.

InventDimId getDim()

{

;

if(!stockLevelImport.InventLocationId || ! stockLevelImport.WMSLocationId)

return "";

if(!WMSLocation::exist(stockLevelImport.WMSLocationId,stockLevelImport.InventLocationId))

return "";

idimm = null;

idimm.InventLocationId = stockLevelImport.InventLocationId;

idimm.wMSLocationId = stockLevelImport.WMSLocationId;

idimm.InventColorId = stockLevelImport.InventColorId;

idimm.InventSizeId = stockLevelImport.InventSizeId;

return inventdim::findOrCreate(idimm).InventDimId;

}

- Mohammed Rasheed


View the original article here

7 Responses to “Quick and Dirty Code to Create and Post Counting Journals in Dynamics AX”

Anonymous said...
November 13, 2012 at 4:55 PM

order tramadol online without prescription tramadol 50mg street value - buy tramadol soma


Anonymous said...
November 18, 2012 at 7:34 PM

phentermine adipex buy phentermine pills online - get real phentermine online


Anonymous said...
December 27, 2012 at 8:43 AM

top [url=http://www.001casino.com/]001[/url] brake the latest [url=http://www.realcazinoz.com/]casino[/url] autonomous no consign bonus at the leading [url=http://www.baywatchcasino.com/]casino online
[/url].


Anonymous said...
January 9, 2013 at 11:09 AM

Hello. Facebook takes a [url=http://www.freecasinobonus.gd]online blackjack[/url] take a chance on 888 casino traffic: Facebook is expanding its efforts to put real-money gaming to millions of British users after announcing a train with the online gambling cast 888 Holdings.And Bye.


Anonymous said...
March 30, 2013 at 2:51 PM

казино lose [url=http://campmillterprosaftid.narod.ru/hot88.html]арт казино[/url] 21нова казино онлайн , [url=http://campmillterprosaftid.narod.ru/hot352.html]интернет казино покер рулетка игровые автоматы вулкан[/url] интернет казино на копейки , [url=http://campmillterprosaftid.narod.ru/hot748.html]казино jackpot capital group[/url] онлайн казино лимон , [url=http://campmillterprosaftid.narod.ru/hot66.html]казино джекпот спб на гражданском[/url] онлайн казино для телефонов lg


Anonymous said...
March 31, 2013 at 1:02 AM

мини игры казино [url=http://basgeodreamsterinswag.narod.ru/hit297.html]казино онлайн скачать бесплатно[/url] казино игры слот , [url=http://basgeodreamsterinswag.narod.ru/hit924.html]казино игровые автоматы без регистрации[/url] интернет казино рулетка webmoney это , [url=http://basgeodreamsterinswag.narod.ru/hit726.html]казино онлайн бесплатно играть на виртуальные деньги[/url] казино арбат в москве , [url=http://basgeodreamsterinswag.narod.ru/hit418.html]казино лазурная г сочи[/url] интернет казино в украине , [url=http://basgeodreamsterinswag.narod.ru/hit319.html]казино key games форум[/url]


Anonymous said...
June 10, 2013 at 4:07 PM

Сейчас наступило такое время, когда любого сложно удивить каким-то подарком, поэтому многим приходится изощряться, чтобы сделать сюрприз своим родным и близким, руководителям или сотрудникам. В нашем кафе есть все для того, дабы отыскать наиболее подходящее решение любой сложной ситуации с поиском подарков для родных и близких. Необходимо сказать, что для того, чтобы сделать приятно, не надо тратить много средств, самое главное – это внимание, и чувства, с которыми подбирается и дарится подарок.
[url=http://cafepodarkov.ru/]интернет магазин обуви луганск[/url]

Важным атрибутом каждого подарка является упаковка, в которой он преподносится, а также открытка, содержащая пожелания человеку, который празднает то либо иное торжество. Иногда обычная открытка, которая содержит самые искренние слова, принесёт больше радости человеку, чем дорогой, бесполезный, не несущий никакого смысла сюрприз.
[url=http://cafepodarkov.ru/]детская одежда керри интернет магазин[/url]

В нашем кафе можно подыскать сувениры и подарки со всех уголков мира, совершенно на любой вкус, из самых различных ценовых категорий. Это могут быть как необходимые вещи для дома, такие как фотообои, стильная канцелярия, так и приятные безделушки, способные дополнить имеющую в доме обстановку, гардероб эксклюзивными и красивыми вещами.
[url=http://cafepodarkov.ru/]обувь интернет магазин весна[/url]


About Me