How to change UnitPrice via Dynamics GP API - microsoft-dynamics

I would like to change UnitPrice when create an order via Dynamics GP API,
So I run next code:
// Create a sales order object
var salesOrder = new SalesOrder();
// Create a sales document type key for the sales order
var salesOrderType = new SalesDocumentTypeKey();
salesOrderType.Type = SalesDocumentType.Order;
// Populate the document type key of the sales order object
salesOrder.DocumentTypeKey = salesOrderType;
// Create a customer key
var customerKey = new CustomerKey();
customerKey.Id = customerSummary[0].Key.Id;
// Set the customer key property of the sales order object
salesOrder.CustomerKey = customerKey;
// Create a batch key
var batchKey = new BatchKey();
batchKey.Id = "01-INBOUND";
// Set the batch key property of the sales order object
salesOrder.BatchKey = batchKey;
// Create a sales order line to specify the ordered item
var salesOrderLine = new SalesOrderLine();
// Create an item key
var orderedItem = new ItemKey();
orderedItem.Id = "AA1111";
// Set the item key property of the sales order line object
salesOrderLine.ItemKey = orderedItem;
// Create a sales order quantity object
var orderedAmount = new Quantity();
orderedAmount.Value = 1;
// Set the quantity of the sales order line object
salesOrderLine.Quantity = orderedAmount;
// THIS DOESN'T WORK
salesOrderLine.UnitPrice = new MoneyAmount { Value = 1.11m, Currency = "USD" };
// Discount works ok
// salesOrderLine.Discount = new MoneyPercentChoice { Item = new MoneyAmount { Value = 1.25m } };
// Create an array of sales order lines
// Initialize the array with sales order line object
SalesOrderLine[] orders = { salesOrderLine };
// Add the sales order line array to the sales order
salesOrder.Lines = orders;
// Get the create policy for the sales order object
var salesOrderCreatePolicy = dynamicsGP.GetPolicyByOperation("CreateSalesOrder", context);
// Create the sales order
dynamicsGP.CreateSalesOrder(salesOrder, context, salesOrderCreatePolicy);
But line to change UnitPrice doesn't work.
salesOrderLine.UnitPrice = new MoneyAmount { Value = 1.11m, Currency = "USD" };
What I'm doing wrong? Appreciate any help.
Thank you!

Found solution:
In Dynamics GP Web Service Policy Configuration for Update Sales
Invoice Policy, you need to update the “Calculate Unit Price Behavior”
to “Do Not Calculate”.
Also, make Sure that you have selected the right Company and assigned
proper roles for the policy. The role should not be Default.
Source: https://www.cloudfronts.com/dynamics-gp-sales-invoice-unit-price-always-0/

Related

How to update item by Composite Primary Key in Dynamodb

I have a table called friends:
Friend 1 | Friend 2 | Status
Friend 1 is my HASH attribute and Friend 2 is my range attribute.
I would like to update an item's staus attribute where friend 1 = 'Bob' and friend 2 = 'Joe'. Reading through the documentation on http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/JavaDocumentAPICRUDExample.html I can only see how to update an item by 1 key, how do I include the other key?
Here you go:
DynamoDBQueryExpression<Reply> queryExpression = new DynamoDBQueryExpression<Reply>()
.withKeyConditionExpression("Id = :val1 and ReplyDateTime > :val2")
.withExpressionAttributeValues(
...
where Id is the Hash Key and ReplyDateTime is the Range Key.
Reference:
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.QueryScanExample.html
I'm writing example where you can make update of multiple item in single table. I have primary key as id and range key as Datetime.
Actually there is no feature available in dynamodb so what i'm doing here is first query all the variable with hash key and range key of which i want to make update. Once all data are stored in List then loading data with it's hash key and rangekey and changing or updating field using set and save it.
Since I'm editing in hash key so, hash key original will be there we need to delete it. If you need to update in next attribute no need. I haven't added deleting code write yourself. You can query if you have confusion your entry with hash key will be still and new entry with new hash key will be added.
Code is below:
public static void main(String[] args) {
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
DynamoDBMapper mapper = new DynamoDBMapper(client);
client.setEndpoint("http://localhost:8000/");
String fromDate = "2016-01-13";
String toDate = "2016-02-05";
User user = new User();
user.setId("YourHashKey");
LocalDate frmdate = LocalDate.parse(fromDate, DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate todate = LocalDate.parse(toDate, DateTimeFormatter.ISO_LOCAL_DATE);
LocalDateTime startfrm = frmdate.atStartOfDay();
LocalDateTime endto = todate.atTime(23, 59, 59);
Condition rangeCondition = new Condition().withComparisonOperator(ComparisonOperator.BETWEEN.toString()).withAttributeValueList(new AttributeValue().withS(startfrm.toString()), new AttributeValue().withS(endto.toString()));
DynamoDBQueryExpression<User> queryExpression = new DynamoDBQueryExpression<User>().withHashKeyValues(user).withRangeKeyCondition("DATETIME", rangeCondition);
List<User> latestReplies = mapper.query(User.class, queryExpression);
for (User in : latestReplies) {
System.out.println(" Hashid: " + in.getId() + " DateTime: " + in.getDATETIME() + "location:" + in.getLOCID());
User ma = mapper.load(User.class, in.getId(), in.getDATETIME());
ma.setLOCID("Ohelig");
mapper.save(ma);
}
}

System.ListException: Before Insert or Upsert list must not have two identically equal elements

I am receiving this error upon inserting new records executed by a trigger:
"System.ListException: Before Insert or Upsert list must not have two identically equal elements"
Below is trigger:
trigger createCETAccount on Account (before update) {
//trigger runs after the update of an Account record
//create a set of all the unique Account IDs
Set<id> AIds = new Set<id>();
//for each instance of the trigger being fired if the Contact field is not blank
//and the Contact Exact Target Send field is not blank and has changed from what it was previously - add that record's ID to the MTIds Set
for (Integer i = 0; i < Trigger.new.size(); i++)
{
if(Trigger.new[i].Contact_Exact_Target_Send__c != Trigger.old[i].Contact_Exact_Target_Send__c && Trigger.new[i].Contact_Exact_Target_Send__c != null)
{
AIds.add(Trigger.new[i].Id);
}
}
//query for all the Account records for the unique AIds in the records
List <Account> aList = new List<Account> ([Select Id, Contact_Exact_Target_Send__c from Account where Id in :AIds]);
//List all the Contacts associated with the Account
List <Contact> ContactList = new List <Contact> ([Select Id, AccountId, isPrimary__c from Contact where AccountId in :AIds ORDER BY isPrimary__c ASC, createdDate DESC]);
//Create a list of ContactExactTarget records
List <ContactExactTarget__c> CETList = new List<ContactExactTarget__c> ([Select ID, Account__c from ContactExactTarget__c where Account__c in :AIds]);
List <ContactExactTarget__c> CETList2 = new List<ContactExactTarget__c>;
//iterate over the list of Account records being processed in the trigger
for(Account acc: aList){
//create a new ContactExactTarget send record for each instance
ContactExactTarget__c objCET = new ContactExactTarget__c();
objCET.ET_Code__c = acc.Contact_Exact_Target_Send__c;
objCET.Account__c = acc.Id;
//add the record to the CETList defined above
CETList.add(objCET);
}
//add the related Contact to the CET record
for(Contact con : ContactList) {
for (ContactExactTarget__c cet : CETList){
if (con.AccountId == cet.Account__c)
cet.Contact__c = con.Id;
CETList2.add(cet);
}
}
//upsert the list to insert the new records
upsert CETList2;
}

What is the preferred method of updating Money fields in Dynamics CRM 2013 via Web Services?

I have an entity in CRM that has some Money fields on them. At the time of the creation of the entity there is no value for those fields, so the entity is created and saved. However if I then have values and go to update them (either through the UI or Web Services) I basically get an error stating "The currency cannot be null".
In the UI:
I then get a red circle with an X through it if I go to update the value.
In the code (web service call):
var crmService = new CrmServiceReference.IFAAContext(new Uri(crmWebServicesUrl));
crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
var crmAccount = crmService.AccountSet.Where(a => a.AccountId == accountId).FirstOrDefault();
crmAccount.myitems_MoneyValueItem.Value = 10.0m;
crmService.UpdateObject(crmAccount);
crmService.SaveChanges()
I then get the "The currency cannot be null" on the .SaveChanges() call.
In the code (second attempt):
var crmService = new CrmServiceReference.IFAAContext(new Uri(crmWebServicesUrl));
crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
var crmAccount = crmService.AccountSet.Where(a => a.AccountId == accountId).FirstOrDefault();
var crmCurrency = crmService.TransactionCurrencySet.Where(c => c.ISOCurrencyCode == "AUD").First();
crmService.SetLink(crmAccount, "TransactionCurrency_Account", crmCurrency);
//crmService.SaveChanges() /* tried with this uncommented as well to try and "set currency" before setting value */
crmAccount.myitems_MoneyValueItem.Value = 10.0m;
crmService.UpdateObject(crmAccount);
crmService.SaveChanges()
So this attempt fails in the same way, however if I run it a second time (without the currency and SetLink) so that the currency was saved before then it does work - hence the atempt to do a second .SaveChanges() but really need it to sort of work the first time through.
In the code (third attempt):
var crmService = new CrmServiceReference.IFAAContext(new Uri(crmWebServicesUrl));
crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
var crmAccount = crmService.AccountSet.Where(a => a.AccountId == accountId).FirstOrDefault();
crmAccount.athos_MoneyValueItem= new CrmServiceReference.Money() { Value = 10.0m };
crmService.UpdateObject(crmAccount);
crmService.SaveChanges()
This doesn't appear to work either
When you create a new record containing a Money field (or updating an existing one where no Money fields are filled before) , you need to specify the currency, the right field to set is TransactionCurrencyId (logical name transactioncurrencyid), it's a lookup (so inside the code is an EntityReference) to the currency entity.
assuming you have the Guid of your currency stored inside the currencyId variable:
var crmAccount = crmService.AccountSet.Where(a => a.AccountId == accountId).FirstOrDefault();
crmAccount.TransactionCurrencyId = new EntityReference(TransactionCurrency.LogicalName, currencyId);
crmAccount.myitems_MoneyValueItem = new Money(10.0m); //better to update the money field with this syntax
crmService.UpdateObject(crmAccount);
crmService.SaveChanges()
CRM 2013 expects a Money object for a currency field.
crmAccount.myitems_MoneyValueItem = new Money(10.0m);
You shouldn't have to explicitly declare a currency unless your CRM organization doesn't have a default currency set (and since you need to set this when creating an organization, it should always be set).
It looks like if I do a lookup on currency (shame as an extra data call) and then use that to set the TransactionCurrencyId it then "works" ... seems like I shouldn't have to do this as I do have a default set for the organisation though. But this does appear to be working in that it results in being able to update those fields.
var crmCurrency = crmService.TransactionCurrencySet.Where(c => c.ISOCurrencyCode == currencyCode).First();
var crmService = new CrmServiceReference.IFAAContext(new Uri(crmWebServicesUrl));
crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
var crmAccount = crmService.AccountSet.Where(a => a.AccountId == accountId).FirstOrDefault();
crmAccount.TransactionCurrencyId = new CrmServiceReference.EntityReference() { Id = crmCurrency.TransactionCurrencyId, LogicalName = "transactioncurrency", Name = crmCurrency.CurrencyName };
crmAccount.myitems_MoneyValueItem.Value = 10.0m;
crmService.UpdateObject(crmAccount);
crmService.SaveChanges();
i am doing the same thing as you but unable to set the money field value during service.create.
I have already put in
entity.Attributes["transactioncurrencyid"] = currencyGuid;
entity.Attributes["new_moneyfield"] = new Money(123.45M);
but in the end, the record is created with the transactioncurrency field populated, while the money field is blank.
Its a custom workflow on CRM online 2016 by the way..

Great Plains Find Sales Orders

I have created sales orders in Great Plains, however, I cannot find them in the right place in the system. Although my code executes without any errors, I do not find this transaction under Sales > All Sales Transactions. Instead, I see them under Sales > Sales Documents.
Is it in a pending state?
public void CreateOrder()
{
CompanyKey companyKey;
Context context;
SalesOrder salesOrder;
SalesDocumentTypeKey salesOrderType;
CustomerKey customerKey;
BatchKey batchKey;
SalesOrderLine salesOrderLine;
ItemKey orderedItem;
Quantity orderedAmount;
Policy salesOrderCreatePolicy;
// Create a context with which to call the service
context = new Context();
// Specify which company to use (sample company)
companyKey = new CompanyKey();
companyKey.Id = (-1);
// Set up the context object
context.OrganizationKey = (OrganizationKey)companyKey;
// Create a sales order object
salesOrder = new SalesOrder();
// Create a sales document type key for the sales order
salesOrderType = new SalesDocumentTypeKey();
salesOrderType.Type = SalesDocumentType.Order;
// Populate the document type key of the sales order object
salesOrder.DocumentTypeKey = salesOrderType;
// Create a customer key
customerKey = new CustomerKey();
customerKey.Id = "JONESJ008";
// Set the customer key property of the sales order object
salesOrder.CustomerKey = customerKey;
// Create a batch key
batchKey = new BatchKey();
batchKey.Id = "SALES ORDERS";
// Set the batch key property of the sales order object
salesOrder.BatchKey = batchKey;
// Create a sales order line to specify the ordered item
salesOrderLine = new SalesOrderLine();
// Create an item key
orderedItem = new ItemKey();
orderedItem.Id = "32X IDE";
// Set the item key property of the sales order line object
salesOrderLine.ItemKey = orderedItem;
// Create a sales order quantity object
orderedAmount = new Quantity();
orderedAmount.Value = 4;
// Set the quantity of the sales order line object
salesOrderLine.Quantity = orderedAmount;
// Create an array of sales order lines
// Initialize the array with sales order line object
SalesOrderLine[] orders = { salesOrderLine };
// Add the sales order line array to the sales order
salesOrder.Lines = orders;
// Get the create policy for the sales order object
salesOrderCreatePolicy = wsDynamicsGP.GetPolicyByOperation("CreateSalesOrder", context);
// Create the sales order
wsDynamicsGP.CreateSalesOrder(salesOrder, context, salesOrderCreatePolicy);
}
I have looked in Sales > All Sales Transactions. I can use the API to pull this order out. I am using the sample company file, Fabrikam, Inc. Here's how I set up my context:
public GPOrders()
{
wsDynamicsGP = new DynamicsGP();
// Be sure the default credentials are used
wsDynamicsGP.UseDefaultCredentials = true;
// Create a context with which to call the web service
context = new Context();
// Specify which company to use (sample company)
companyKey = new CompanyKey();
companyKey.Id = (-1);
// Set up the context object
context.OrganizationKey = (OrganizationKey)companyKey;
context.CultureName = "en-US";
}
I found them under Sales > Sales Documents. The transactions never posted, so they weren't under Sales > All Sales Transactions.

CF10 new query()

I am creating a query inside a function. Everything works fine until this line:
ulist = new query();
Then I get the error:
Could not find the ColdFusion component or interface query.
Code:
//GET USERS LISTS
remote query function getUserLists(userid) {
//CONFIGURE twitter4j
init();
//DEFINE USER LIST QUERY
var userLists = querynew("id, name, member_count", "Integer, VarChar, Integer");
//GET THE USER LISTS
getLists = t4j.getUserLists(#arguments.userid#);
//BUILD THE USER LIST QUERY
for (i=1;i LTE ArrayLen(getLists);i=i+1) {
newRecord = queryAddRow(userLists);
newRecord = querySetCell(userLists, "id", getLists[i].getId());
newRecord = querySetCell(userLists, "name", getLists[i].getName());
newRecord = querySetCell(userLists, "member_count", getLists[i].getMemberCount());
}
//SORT THE USER LIST BY NAME
ulist = new query();
ulist.setDBType("query");
ulist.setAttributes(sourceQuery=userLists);
ulist.setSQL("select * from sourceQuery order by name");
userListsSorted = ulist.execute().getresult();
//RETURN THE SORTED USER LIST QUERY
return userListsSorted;
}
As per Twitter, make sure you have a custom tag path pointing to [instance]/customtags - which should be there by default. You could use a mapping, pointing to one of the subdirectories within that [instance]/customtags directory, eg: /coldfusion pointing to [instance]\CustomTags\com\adobe\coldfusion, then use:
ulist = new coldfusion.query();
// etc
I'd just use the custom tag directory approach though.
Try using the full path:
ulist = new com.adobe.coldfusion.query()