Create a record on DirPartyTable from code? - axapta

I have to create a new record on DirPartyTable .
I used this code:
DirPartyTable _myDirPartyTable;
myPartyNumber = DirPartyTable::getNewPartyNumber((webSession() == null));
myDirPartyTable = DirPartyTable::createNew(myPartyType , myName, myPartyNumber);
// or without partynumber
myDirPartyTable = DirPartyTable::createNew(myPartyType , myName);
But in both cases the standard method generate two Sequence ParyNumber.
In Debu mode I saw the system get two times the PartyNumber .
How can I create a record without creating holes in the sequence numeric?
I tried to use this another code:
select forupdate myDirPartyTable;
myDirPartyTable.name = ....;
//etc
myDirPartyTable.insert();
But does not create the record.
Thanks,
enjoy!

DirPartytable is the basis table of address book framework and is the top level of table inheritance hierarchy see references in Implementing the Global Address Book Framework (White paper)
You shouldn't try to directly create a party but create from your entity which implement the DirParty framework. When you create a vendor, you don't create a DirParty (with herited tables) and then create a VendTable and link them all together. Creating a vendor will do it directly.
Then, if you still encounter two times Party number calls, log a case at Microsoft support.
ulisses: I solved problem, I have to create before the PartyType (Organization or Person etc...)and after update my created DirPartyTable.

Just try the AxDirPartyTable Class like:
AxDirPartyTable axDirPartyTable;
axDirPartyTable = AxDirPartyTable::construct();
axDirPartyTable.parmName(myName);
axDirPartyTable.parmPartyNumber(myPartyNumber);
axDirPartyTable.save();
Examples could be found here: How to create a record in Global address book throgh code.

Related

In App Maker, how do you make dynamic table cell text?

In App Maker, I am displaying a table and want to replace table cell data with different text using a data lookup from another table. Assume two tables, Departments and Employees.
Departments is two fields, DeptID and DeptDescription.
Employees is multiple fields including DeptID.
In the table listing for Employees, I would like to replace the DeptID with the DeptDescription. (The page datasource is Employees. I do not want to set up a relationship between the data models.)
I am guessing I want to do some scripting in the onDataLoad event for the table cell label for DeptID. I have this much so far:
app.datasources.Departments.query.filters.DeptID._equals = widget.datasource.item.DeptID;
app.datasources.Departments.newQuery().run();
widget.text = app.datasources.Departments.item.DeptDescription;
I know this is not correct, but am I close?
This answer is untested, but I wanted to present a possible solution that would not require a lot of DB calls, especially ones that make repeated calls to a server script which might consume a lot of processing time when you do line item calls.
Set up a separate datasource under the Department model. Change the default 'Query Builder' to 'Query Script' and add a parameter of type 'list(number)' or 'list(string)', this should match your Primary Key field type. Uncheck the 'auto load' option.
In your 'Query Script' portion enter the following code:
query.filters.Id._in = query.parameters.YourParameter;
return query.run();
Go to your Employees datasource that is supposed to generate your table and find your 'On Load' client script section. In this section enter the following code:
var departmentsDs = app.datasources.YourDepartmentsDs;
departmentsDs.properties.YourParameter = datasource.items.map(function(deptIds) {return deptIds.DeptID;});
departmentDs.load();
Now go the page that contains your table. If you have not already create a label widget do so now. In this label widget for the text binding enter the following:
#datasources.YourDepartmentsDs.loaded && (#datasources.YourDepartmentsDs.items).map(function(Id){return Id.Id}).indexOf(#widget.datasource.item.DeptID) !== -1 ? #datasources.YourDepartmentDs.items[(#datasources.YourDepartmentsDs.items).map(function(Id){return Id.Id}).indexOf(#widget.datasource.item.DeptID)].DeptDescription : 'Unable to retrieve Dept Description'
As stated this is untested and I wrote the code from memory without App Maker in front of me so it may require some additional tweaking. Going with the first option presented by J.G. would also be a very viable solution though. And I apologize but the code formatter does not seem to be working for me.
1 way) Create an aggregate table that joins your tables if you need to bypass using the relations feature. This way you can use sql to join the two tables in the datasource definition
2) if you don't want to make a new table. Change the text from a value binding to "more options"
=getDescription(#datasource.item.DeptId)
and then the code you wrote in a client side script
function getDescription(id){
google.script.run
.withSuccessHandler(function successHandler(result){ return result;})
.withFailureHandler( function failureHandler(e){ console.log(" Failed" +e);})
.queryValue(id);
}
server side script:
function queryValue(id){
var query = app.models.Departments.newQuery();
query.filters.DeptID._equals = id;
var results = query.run();
return results[0]["DeptDescription"];
}
that last line might be results[0].DeptDescription

Entity Framework - How to return a strongly typed object containing multiple Entities?

I have three tables in SQL Server: Company, Financial and FinancialHistory.
Relationships are:
Company -> Financial (1-1)
Financial -> FinancialHistory (1-Many)
Having generated an Entity Model, I want to return one larger "Entity" that contains ALL the columns from Company and Financial and a select few from FinancialHistory so that I can maintain a sort across multiple GridViews at the front end. Basically I want to avoid returning a dynamic List type which is where i'm at currently, I want a more strongly typed return type.
Is there any feature in Entity Framework 6 that allows me to do this via the Model diagram or do I have to create my own class and use it separately to the Model? An example of the class and instructions would help.
NOTE: I flatten out the FinancialHistory data and create dynamic columns in a DataTable before assigning to GridViews.
Originally this was a Stored Procedure that used PIVOT and generated dynamic columns but I wanted to move it over to EF and use LINQ.
When querying you can project the results into any type. While that type won't be updatable (you need to directly modify entity types) it works very well when querying.
var res = await (from cpy in myDbContent.Companies
// get two newest financial results
let fin = cpy.financials
let finResRecent = fin.History.OrderByDescending(h => h.FinancialYear)
let finResLast = finResRecent.FirstOrDefault()
let finResPrev = finResRecent.Skip(1).FirstOrDefault()
select new {
Company = cpy,
Financials = fin,
LastResults = finResLast,
PreviousResults = finresPrev
}
).ToListAsync();
(Inside the query many operators – like Single – can't be used, but FirstOrDefault can)

How to create a merged table with FusionTable API

The Fusiontable API (https://developers.google.com/fusiontables/docs/v2/using#CreatingTables) allows you to create a new base table. The description here (https://developers.google.com/fusiontables/docs/v2/reference/table/insert) implies you can specify basetableIds, but using the "Try this API" I have not successfully create a merged table. I have one table with map geometry, which I don't want to duplicate, but want to let users specify their own colors for the geometry.
Has anyone been able to do this? If so, how do you specify the columns to join on?
Thanks.
Does the base table have the location type columns? If the "map geometry" column/columns have location type set then you may not be able to create a new base table from the existing tableId as there are warnings throughout the docs about using the API to modify or update columns which are two-column locations.
So I think that by "creating" a new table from a base table id which has columns defined as locations you also create new columns and as such wouldn't be able to do this via API.
Try to change the column types to strings and then create the new table. Revert back to location once completed if this is the case?
Hope that helps.
I recently ran into this problem and thought i would post my solution. It appears that creating merge tables via the API is done by creating views with the sql query endpoint.
From the Docs:
To create a new merged table, use the following syntax in an HTTP POST
request
CREATE VIEW <new_table_name>
AS (SELECT <column_spec> { <column_spec>}*
FROM <table_list>)
So you would generate something like this if you were merging two tables on a 'zipcode' column for example:
CREATE VIEW 'My New Table'
AS (
SELECT T1.'zipcode', T2.'state', T2.'area', T2.'latitude', T2.'longitude', T2.'geometry'
FROM somefusiontableid AS T1
LEFT OUTER JOIN someotherfusiontableid AS T2 ON T1.'zipcode' = T2.'zipcode'
)
Hope this helps anyone else who runs into this.

EF4 slow association access

I'm building an ASP.NET 4 web application using EF4 and I have tables like this:
Product
Attribute
Product_Attribute_Map
Product_Attribute_Map is a cross table, many to many. So Product can have zero or many Attribute and vice versa.
In code I do this:
//Attribute a = new Attribute(); // Edit:
Attribute a = (from a in context.Attributes where a.AttributeID = 1 select a).First();
a.Name = "test";
Product.Attributes.Add(a);
I noticed a problem which makes this very slow. EF4 will execute this SQL on the server:
SELECT
[Extent2].* FROM [dbo].[Product_Attribute_Map] AS [Extent1]
INNER JOIN [dbo].[Product] AS [Extent2] ON [Extent1].[ProductID] = [Extent2].[ProductID]
WHERE [Extent1].[AttributeID] = #p1
I don't understand why it does this. An Attribute may be assigned to 10.000 Products, which makes this a bad query. It takes over 5 seconds to add an Attribute to a Product...
How can I prevent EF4 from selecting all attributes? And just select the attributes for this product.
Thanks
Edit: This is only using POCO t4 template. EntityObject template doesnt have this problem.
My guess: This happens because of LazyLoading used together with FixUpCollections generated by POCO template. When you add attribute to product, fixup collection will perform reverse operation as well - it will add prduct to attribute but first access to products collection in attribute will trigger lazy loading and so your query is executed. I don't like fixup collections ... You can modify POCO template to not use them or you can delete Products navigation property in Attribute (if you don't need it).

How do I update an Entity Reference using a SelectList in edit form?

This is a follow-up to the discussion in this post. I am not sure how to ask the follow-up question in a 2-month-old thread; so I apologize if there is a better way.
Anyway, to reiterate I have an ASP.NET MVC Edit form, and one of the fields is a select list. I get the values fine, but I am having trouble to update the primary entity after Post. Obviously, I have the key to the lookup entity, but it seems crazy to have to load all lookups. So, the suggested solution is entity reference
For clarity, let's say I have a customer as main entity, and title (Mr / Mrs / Dr, etc.) as the lookup.
So, the link above suggests the following:
customer.TitleReference.EntityKey = new EntityKey("MyEntities.Titles", "Id",
Int32.Parse(formData["personTitle"]);
So far, so good. I assign the entity key (and I see in the debugger that is indeed what I expect). But I can't figure out how to get the new value saved along with other customer fields. I am doing the following:
var originalCustomer = (from c in MyEntities.Customers
where c.Id = customer.Id select c).first();
MyEntities.ApplyPropertyChanges(originalCustomer.EntityKey.EntitySetName,
customer);
This updates all customer fields, except for lookups. Intuitively, it is (somewhat) understandable, since if I specify originalCustomer.EntityKey.EntitySetName, ApplyPropertyChanges ignores originalCustomer.TitleReference.EntityKey.EntitySetName.
But if I do specify originalCustomer.TitleReference.EntityKey.EntitySetName, runtime complains that the entity is null (which is also understandable, since I didn't assign anything to the entity; only to entity reference.
As is probably obvious, I am going circles around what seems to be quite straightforward situation. However, I can't find any tutorials that cover it (which is strange in itself).
Furthermore, I have a more complex problem... the customer may have multiple addresses and the address has state... hopefully, once I figure out the titles - I can extrapolate.
By the way, the example (customer - title - address) is fictitious; but it models the problem quite well.
This should work:
var originalCustomer = (from c in MyEntities.Customers
where c.Id = customer.Id select c).First();
originalCustomer.TitleReference.EntityKey = new EntityKey("MyEntities.Titles", "Id",
Int32.Parse(formData["personTitle"]);
context.SaveChanges()

Resources