Create a inventory movement journal in Dynamics AX 2012 - axapta

This problem is driving me nuts... I don't know how to fix it. I'm trying to create an inventory movement journal entry using the ProfitLossJournalService.
The code below runs, but it shows the transaction in the "inventory adjustment" journal. I want it in the inventory movement jounal.
public void UpdateInventoryForConsumableItem(InventoryUpdate update)
{
var svc = new ProfitLossJournalServiceClient();
var cc = new CallContext {Company = "SS"};
var journal = new AxdProfitLossJournal();
var table = new AxdEntity_InventJournalTable
{
InventDimFixedSpecified = false,
InventSiteId = "MC",
InventLocationId = "MAIN WH",
JournalType = AxdEnum_InventJournalType.Movement,
JournalNameId = "InvMovJour",
Description = Constants.InventoryMovementJournalDescription,
NumOfLines = 1,
NumOfLinesSpecified = true,
JournalTypeSpecified = true,
JournalId = "InvMovJour",
JournalIdOrignal = "InvMovJour",
action = AxdEnum_AxdEntityAction.update
};
var inventoryDims = new AxdEntity_InventDim
{
InventLocationId = "MAIN WH",
InventDimId = update.InventoryDimId,
InventColorId = update.Color,
InventSiteId = "MC",
InventSizeId = update.Size,
InventStyleId = update.Style,
action = AxdEnum_AxdEntityAction.create
};
var entry = new AxdEntity_InventJournalTrans
{
InventDimId = update.InventoryDimId,
TransDate = DateTime.Now,
ItemId = update.ItemId,
CostMarkupSpecified = false,
InventRefTypeSpecified = false,
LineNumSpecified = false,
JournalType = AxdEnum_InventJournalType.Movement,
JournalTypeSpecified = true,
Qty = update.Quantity,
QtySpecified = true,
InventDim = new AxdEntity_InventDim[1] {inventoryDims}
};
table.InventJournalTrans = new[] {entry};
journal.InventJournalTable = new[] {table};
try
{
var result = svc.create(cc, journal);
Logger.LogTrace(string.Format("sending InventoryTransferJournal {0}", result.GetValue(0)));
Logger.LogEvent(Logger.SentConsumableInventoryUpdateToDynamics);
}
catch (Exception e)
{
Logger.LogException(e);
throw;
}
}

When you use the ProfitLossJournalService that is essentially what you are creating, an Inventory adjustment.
If you want to create an inventory movement journal, unfortunately there is no standard AIF service that does that. You would need to implement that yourself and expose it to AIF.

Related

Mocking of Where method in Data Repository is returning null at its actual implementation in repository

I have written a test for edit model of a class in EF core.
public async Task<Expense> EditExpense(Expense model)
{
var expense = _dataRepository.Where<Expense>(x => x.Id == model.Id).ToList();
if(expense != null)
{
expense.ForEach(x =>
{
x.Name = model.Name;
x.AddedOn = model.AddedOn;
x.Amount = model.Amount;
x.Type = model.Type;
x.SplitOption = model.SplitOption;
x.Notes = model.Notes;
x.IsGroupExpense = model.IsGroupExpense;
});
return expense.FirstOrDefault();
}
else
{
return null;
}
}
I want to test this method using xUnit and Moq and I have also written a method for it as below.
[Fact]
public async void UnitTest_IsExpenseEdited_ReturnsTrue()
{
var expenseCurrent = new Expense()
{
Id = 5,
Name = "Test Expense",
Amount = 1500,
AddedBy = "44db32c3-ad6a-4d68-a683-862be363f59c",
AddedOn = DateTime.Now,
Notes = "",
IsDeleted = false,
IsGroupExpense = false,
SplitOption = 1,
Type = 0
};
var expenseList = (new List<Expense>{ expenseCurrent });
var expenseAfterEdit = new Expense()
{
Id = 5,
Name = "Test Expense Edited",
Amount = 2000,
AddedBy = "44db32c3-ad6a-4d68-a683-862be363f59c",
AddedOn = DateTime.Now,
Notes = "Edited !!!",
IsDeleted = false,
IsGroupExpense = true,
SplitOption = 2,
Type = 0
};
_dataRepositoryMock.Setup(x => x.Where<Expense>(a => a.Id == expenseCurrent.Id)).Returns(expenseList as IQueryable<Expense>);
var expenseEdited = await _exepenseRepository.EditExpense(expenseAfterEdit);
Assert.Equal(expenseEdited, expenseAfterEdit);
}
But here, the Where method is returning null
public async Task<Expense> EditExpense(Expense model)
{
var expense = _dataRepository.Where<Expense>(x => x.Id == model.Id).ToList(); in repository
}
I am getting var expense null in above code.
Please suggest what should I include in the code to get the value in above var expense?
To test this method, I want to create a fake data which is going to be updated. Please suggest how this thing needs to be written properly?

how to send a post request?

How to consume web post service in C#? I did tests with POSTMAN and I got a response data, but in .net my response is empty. It works great in PostMan. The problem is how to format the Body Content and send it.
string idop = "";
List<ProductJSON> listProductsJSON = new List<ProductJSON>();
List<List<string>> productJSON = new List<List<string>>();
List<string> products = new List<string>();
products.Add("4");
products.Add("5");
products.Add("30.2");
products.Add("1");
products.Add("0");
products.Add("4");
productJSON.Add(products);
using (var client = new HttpClient())
{
var res = client.PostAsync("http://xyz.cti.lat/sant2/webservices/edd.php",
new StringContent(JsonConvert.SerializeObject(
new {
a = "pCatlog",
cnal = "RED",
tpo = "2",
fpago = "DETO",
pgdo = "0",
rc = "13123",
local = "BACK",
localorg = "BACK",
raz = "PPPPPP",
dir_ruc = "name",
log = "CREAVIR",
not = "DETO2",
del = "0",
dir = "",
ubi = "",
refe = "",
prod = productJSON
}),
Encoding.UTF8, "application/json")));
try
{
res.Result.EnsureSuccessStatusCode();
var x = res;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Can you try this code inside of the try block?
if (res.IsCompleted)
{
var result = res.Result;
var response = result.Content.ReadAsStringAsync();
var data = response.Result;
}
The ideal would be to declare this as an async method and use the await operations to get the result as follows.
var res = await client.PostAsync(<url>, <string_content>);
var result = await res.Content.ReadAsStringAsync();

PayPal Plus stay on own page

I have implemented a small PayPal PLUS Demo in ASP.NET:
protected void Page_Load(object sender, EventArgs e)
{
var config = ConfigManager.Instance.GetProperties();
config.Add("clientId", "XXXXXXXXXXXXXXXXXXXXXXXXX");
config.Add("clientSecret", "XXXXXXXXXXXXXXXXXXXXXXXXX");
config.Add("mode", "sandbox");
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
var apiContext = new APIContext(accessToken);
var itemList = new ItemList() { items = new List<Item>() { new Item() { name = "Item Name", currency = "USD", price = "15", quantity = "5", sku = "sku" } } };
var payer = new Payer() { payment_method = "paypal" };
var baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPal.aspx?";
var guid = Convert.ToString((new Random()).Next(100000));
var redirectUrl = baseURI + "guid=" + guid;
var redirUrls = new RedirectUrls() { cancel_url = redirectUrl + "&cancel=true", return_url = redirectUrl };
var details = new Details() { tax = "15", shipping = "10", subtotal = "75" };
var amount = new Amount() { currency = "USD", total = "100.00", details = details };
var transactionList = new List<Transaction> { new Transaction() { description = "Transaction description.", invoice_number = new Random().Next(999999).ToString(), amount = amount, item_list = itemList } };
var payment = new Payment() { intent = "sale", payer = payer, transactions = transactionList, redirect_urls = redirUrls };
var createdPayment = payment.Create(apiContext);
var approval_url = createdPayment.links.FirstOrDefault(x => x.rel == "approval_url").href;
hfApprovalUrl.Value = approval_url;
}
<asp:HiddenField runat="server" id="hfApprovalUrl"/>
<script src="https://www.paypalobjects.com/webstatic/ppplus/ppplus.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="ppplus"></div>
<script type="application/javascript">
var approval_url = $('#hfApprovalUrl').val();
var ppp = PAYPAL.apps.PPP({
"approvalUrl": approval_url,
"placeholder": "ppplus",
"mode": "sandbox",
"country": "DE"
});
</script>
Its works so far but if a choose a pay option (e.g. credit card) I will be redirected to PayPal.I want that the user stys on my own page. How can I do this?
Thanks!
Jan

MvcxGridview with datatype System.Byte[]

I'm using MvcxGridView to bind a DataTable model and I have a problem with a DataColumn with datatype System.Byte[].
When I view data, gridview does not show a value and only displays System.Byte[]. I want the GridView to display a picture in that column.
When I save data, I get this message:
Invalid cast from 'System.String' to 'System.Byte[]'
How can I solve these problems?
Here is my code in view:
#using System.Data;
#model TestPA6MVC.Models.EntityModelForViewDataSettingGrid
#functions{
MVCxGridViewCommandColumn CreateCommandColumn(string AllowEdit,string AllowAdd)
{
MVCxGridViewCommandColumn column = new MVCxGridViewCommandColumn();
column.Visible = true;
column.NewButton.Visible = (AllowAdd.ToLower()=="true")?true:false;
column.DeleteButton.Visible = (AllowEdit.ToLower() == "true") ? true : false; ;
//column.EditButton.Visible = true;
return column;
}
}
#{
var grid = Html.DevExpress().GridView(
settings => {
settings.Name = "gvEditing";
settings.CallbackRouteValues = new {
Controller = "Home", Action = "GridViewPartial",
ViewName = Model.ViewName,
PrimaryKeyCollection = Model.PrimaryKeyCollection,
TableEditorList = Model.TableEditorList,
ColumnComboBoxCollection = Model.ColumnComboBoxCollection,
ColumnReadOnlyCollection = Model.ColumnReadOnlyCollection,
ColumnHideCollection = Model.ColumnHideCollection,
ParamNameCollection = Model.ParamNameCollection,
DataForParamCollection = Model.DataForParamCollection,
ParamTypeCollection = Model.ParamTypeCollection,
AllowAdd = Model.AllowAdd,
AllowEdit = Model.AllowEdit
};
settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "Home", Action = "GridViewPartialAddNew", ViewName = Model.ViewName };
settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "Home", Action = "GridViewPartialUpdate", ViewName = Model.ViewName };
settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "Home", Action = "GridViewPartialDelete", ViewName = Model.ViewName };
settings.SettingsEditing.BatchUpdateRouteValues = new {
Controller = "Home", Action = "BatchEditingUpdateModel",
ViewName = Model.ViewName,
PrimaryKeyCollection = Model.PrimaryKeyCollection,
TableEditorList = Model.TableEditorList,
ColumnComboBoxCollection = Model.ColumnComboBoxCollection,
ColumnReadOnlyCollection = Model.ColumnReadOnlyCollection,
ColumnHideCollection = Model.ColumnHideCollection,
ParamNameCollection = Model.ParamNameCollection,
DataForParamCollection = Model.DataForParamCollection,
ParamTypeCollection = Model.ParamTypeCollection,
AllowAdd = Model.AllowAdd,
AllowEdit = Model.AllowEdit
};
if (Model.AllowEdit.ToLower() == "true")
{
settings.SettingsEditing.Mode = GridViewEditingMode.Batch;//Kieu view chinh sua
}
else { settings.SettingsEditing.Mode = GridViewEditingMode.PopupEditForm; }
settings.SettingsBehavior.ConfirmDelete = true;//Cho phep hien thi thong bao xac nhan
settings.SettingsBehavior.ColumnResizeMode = ColumnResizeMode.Control;//Cho phep chinh sua do rong cot
settings.Width = 800;//Chieu rong cua gridview
settings.Settings.HorizontalScrollBarMode = ScrollBarMode.Auto;
settings.SettingsPager.Mode = GridViewPagerMode.ShowPager;
settings.SettingsPager.PageSize = 50;
settings.Settings.VerticalScrollableHeight = 300;
settings.Settings.VerticalScrollBarMode = ScrollBarMode.Auto;
settings.SettingsPager.Visible = true;
settings.Settings.ShowGroupPanel = true;
settings.Settings.ShowFilterRow = true;
settings.Settings.ShowHeaderFilterButton = true;//Hien thi bo loc cho column
//Tao cot gia de tranh tinh trang hien thi lai cac Column an khi Callback
MVCxGridViewColumn fakeco = new MVCxGridViewColumn();
fakeco.Visible = false;
fakeco.Width = 0;
fakeco.EditFormSettings.Visible = DefaultBoolean.False;
settings.Columns.Add(fakeco);
settings.SettingsBehavior.AllowSelectByRowClick = true;
settings.DataBound = (sender, e) =>
{
//Build Column Tool Automatic
((MVCxGridView)sender).Columns.Insert(0, CreateCommandColumn(Model.AllowEdit,Model.AllowAdd));
//Add custom Column
foreach (var child in Model.ModelForDisplayColumnList)
{
MVCxGridViewColumn dc = new MVCxGridViewColumn();
dc.Caption = child.Caption;
dc.FieldName = child.ColumnName;
if(child.IsHidden)//Neu de an hoan toan se khong lay duoc du lieu da chinh sua
{ dc.Width = 0; }
//dc.Visible = !child.IsHidden;
dc.ReadOnly = child.IsReadOnly;
switch (child.DataType)
{
case "datetime":
dc.ColumnType = MVCxGridViewColumnType.DateEdit;
var DateEditProperties = dc.PropertiesEdit as DateEditProperties;
DateEditProperties.DisplayFormatString = "dd/MM/yyyy hh:mm tt";
//Cho phep chinh ngay, gio
DateEditProperties.UseMaskBehavior = true;
//Dinh dang hien thi khi chinh sua
DateEditProperties.EditFormat = EditFormat.Custom;
DateEditProperties.EditFormatString = "dd/MM/yyyy hh:mm tt";
DateEditProperties.TimeSectionProperties.Visible = true;//Hien khung chinh gio
break;
case "combobox":
dc.ColumnType = MVCxGridViewColumnType.ComboBox;
var DropDownEditProperties = dc.PropertiesEdit as ComboBoxProperties;
DropDownEditProperties.DataSource = child.DataSourceForComboBoxColumn;
DropDownEditProperties.ValueField = child.DataSourceForComboBoxColumn.Columns[0].ColumnName;
DropDownEditProperties.TextFormatString = "{0}";
foreach (DataColumn childcolumn in child.DataSourceForComboBoxColumn.Columns)
{
DropDownEditProperties.Columns.Add(childcolumn.ColumnName, childcolumn.ColumnName);
}
break;
case "boolean":
case "bit":
dc.ColumnType = MVCxGridViewColumnType.CheckBox;
break;
case "byte[]":
dc.ColumnType = MVCxGridViewColumnType.BinaryImage;
//var ImageEditProperties = dc.PropertiesEdit as BinaryImageEditProperties;
//ImageEditProperties.ImageWidth = 50;
//ImageEditProperties.ImageHeight = 50;
break;
//case "string":
// dc.ColumnType = MVCxGridViewColumnType.ComboBox;
// var ComboBoxEditProperties = dc.PropertiesEdit as ComboBoxProperties;
// ComboBoxEditProperties.DataSource = ModelForDisplayColumnList;
// ComboBoxEditProperties.TextField = "DataType";
// ComboBoxEditProperties.ValueField = "Caption";
// break;
}
((MVCxGridView)sender).Columns.Add(dc);
}
};
settings.KeyFieldName = Model.PrimaryKeyCollection;
});
if (ViewData["EditError"] != null){
grid.SetEditErrorText((string)ViewData["EditError"]);
}
}
#grid.Bind(Model.DataSourceForGrid).GetHtml()

I want to insert "An error occurred object reference not set to an instance of an object while insert and update new record" into database

I want to insert and update data into database on button click but when I fill all fields and start debugging and when dubugger is on buyer code this error is occurred "object reference not set to an instance of an object". Kindly help me.......
protected void btnSaveChanges_Click(object sender, EventArgs e)
{
if (Convert.ToInt32(ViewState["BuyerId"]) > 0)
{
oBuyer = new Buyer();
//Fill object with Text box values
oBuyer.BuyerId = Convert.ToInt32(ViewState["BuyerId"]);
oBuyer.BuyerCode = txtBuyerCode.Text;
oBuyer.SunCode = txtSunCode.Text;
oBuyer.BuyerName = txtBuyerName.Text;
oBuyer.BuyerAddress1 = txtBuyerAddress1.Text;
oBuyer.BuyerAddress2 = txtBuyerAddress2.Text;
oBuyer.BuyerAddress3 = txtBuyerAddress3.Text;
oBuyer.BuyerAddress4 = txtBuyerAddress4.Text;
oBuyer.BuyerPostCode = txtBuyerPostcode.Text;
oBuyer.BuyerPhone = txtBuyerPhone.Text;
oBuyer.BuyerFax = txtBuyerFax.Text;
oBuyer.BuyerEmail = txtBuyerMail.Text;
oBuyer.PfaCode = txtBuyerPFACode.Text;
oBuyer.Guarantee = Convert.ToDecimal(txtBuyerGuarantee.Text);
oBuyer.DefaultDestination = ddlBuyerDefaultDestination.SelectedValue;
oBuyer.HbaLevy = chkHBALeavy.Checked;
oBuyer.SfiaWhite = chkSFIAPelagic.Checked;
oBuyer.SfiaPelagic = chkSFIAPelagic.Checked;
oBuyer.MarketBox = txtBuyerMarketBox.Text;
oBuyer.Comments = txtComments.Text;
oBuyer.BuyerRegistrationNo = txtBuyerRigistrationNo.Text;
}
else
{
//Fill object with Text box values
oBuyer.BuyerCode = txtBuyerCode.Text;
oBuyer.SunCode = txtSunCode.Text;
oBuyer.BuyerName = txtBuyerName.Text;
oBuyer.BuyerAddress1 = txtBuyerAddress1.Text;
oBuyer.BuyerAddress2 = txtBuyerAddress2.Text;
oBuyer.BuyerAddress3 = txtBuyerAddress3.Text;
oBuyer.BuyerAddress4 = txtBuyerAddress4.Text;
oBuyer.BuyerPostCode = txtBuyerPostcode.Text;
oBuyer.BuyerPhone = txtBuyerPhone.Text;
oBuyer.BuyerFax = txtBuyerFax.Text;
oBuyer.BuyerEmail = txtBuyerMail.Text;
oBuyer.PfaCode = txtBuyerPFACode.Text;
oBuyer.Guarantee = Convert.ToDecimal(txtBuyerGuarantee.Text);
oBuyer.DefaultDestination = ddlBuyerDefaultDestination.SelectedValue;
oBuyer.HbaLevy = chkHBALeavy.Checked;
oBuyer.SfiaWhite = chkSFIAPelagic.Checked;
oBuyer.SfiaPelagic = chkSFIAPelagic.Checked;
oBuyer.MarketBox = txtBuyerMarketBox.Text;
oBuyer.Comments = txtComments.Text;
oBuyer.BuyerRegistrationNo = txtBuyerRigistrationNo.Text;
}
//enter into nSYScatch6 service
bool saveBuyer = nSYSCatch6ServiceInitiator.SaveBuyer(oBuyer);
if (saveBuyer)
{
}
Response.Redirect(Request.RawUrl);
}
You are missing an oBuyer = new Buyer(); in the else branch.

Resources