How can I add a way to track a collection of entities and flag them on/off (to signal if a process has been done to them)? - entity-framework

My first idea is extend the partial class 'Step' which is an entity. I could add a bool property and then set that true/false as I complete processing on them.. But then every time I regenerate the DBContext after making changes to the DB won't I have to manually keep doing this? OR is some other way.. The code below explains what I am trying to do
if ((si.StepID == 20) || (si.StepID == 23) || (si.StepID == 24))
{
//Step is a process. Each Step must be run in order
//get list of steps in tasks in RUN (1,2,3,4...) order
int stepToRun = 0;
var stepsInTask = InstanceExpert.GetAllStepsInTaskOrderedByRunOrder(ti.TaskInstanceID);
//Get which step is next to be processed
foreach (Step s in stepsInTask)
{
//get the stepToRun
//Need to extend STEP Entity property with a bool??
}
//Take that step and run the specific function
if (stepToRun == 20)
{
}
if (stepToRun == 23)
{
}
if (stepToRun == 24)
{
}

Related

How to pass more than one record between two forms?

I want to pass more than one record between two forms. The user opens Form-A, selects multiple records and then clicks a button that opens Form-B.
In Form-B there are two (or more) StringEdit controls and they should display values from the selected records.
I know how to pass only one record, to do that I use the following code in a method of Form-B:
if (element.args().parmEnumType() == enumNum(NoYes)
&& element.args().parmEnum() == NoYes::Yes)
{
myTable = element.args().record();
stringEdit.text(myTable.Field);
}
How should I change my code so that I can set the text of another StringEdit control to the field value of the next record that the user selected?
To do this, you can use an args to pass the records, which you will need to prepare in your Form-A, as below (taking the SalesTable as example);
int recordsCount;
SalesTable salesTable;
container con;
Args args = newArgs();
// gets the total records selected
recordsCount = salesTable_ds.recordsMarked().lastIndex();
salesTable = salesTable_ds.getFirst(1);
while(salesTable)
{
// storing recid of selected record in container
con = conIns(con,1, salesTable.RecId);
salesTable = SampleTable_ds.getNext(); // moves to next record
}
// passing container converted to string
args.parm(con2Str(con,','));
Then on your Form-B, you will need to override the init() method to read the args you created,
In order to retrieve passed arguments in the recipient from. Override the init() method of new form as shown
public void init()
{
container con;
int i;
super();
// string to container
con = str2con(element.args().parm(),'','');
// for sorting
for(i = 1;i<= conLen(con) ;i++)
{
salesTable_ds.query().dataSourceTable(Tablenum(SalesTable)).addRange(fieldNum(SalesTable,RecId)).value(SysQuery::value(conPeek(con,i)));
}
}
Hope it helps.
Taken from Ax-Forum
This will typically imply looping through the selected records in Form-A and changing the query in Form-B.
The idiomatic way to loop through selected records involves a for loop and the getFirst and getNext methods of the datasource:
SalesLine sl;
FormDataSourcs ds = _salesLine.dataSource();
for (sl = ds.getFirst(true) ? ds.getFirst(true) : ds.cursor(); sl; sl = ds.getNext())
{
//Do your thing, add a query range
}
The MultiSelectionHelper class may be of use here, as it does the thing:
public void init()
{
MultiSelectionHelper ms;
super();
if (element.args() && element.args().caller() && element.args().record())
{
this.query().dataSourceTable(tableNum(SalesLine)).clearDynalinks();
ms = MultiSelectionHelper::createFromCaller(element.args().caller());
ms.createQueryRanges(this.query().dataSourceTable(tablenum(SalesLine)), fieldstr(SalesLine, InventTransId));
}
}

declare variable to store linq entity for conditional statements

I am trying to look up record using if I have the key then use Find if not use Where
private ApplicationDbContext db = new ApplicationDbContext();
public bool DeactivatePrice(int priceId = 0, string sponsorUserName = "")
{
var prices = db.BeveragePrices;
// if we have an id then find
if (priceId != 0)
{
prices = prices.Find(priceId);
}
else
{
prices = prices.Where(b => b.UserCreated == sponsorUserName);
}
if (prices != null)
{
// do something
}
return true;
I get the following error for
prices = prices.Find(priceId);
Cannot convert app.Model.BeveragePrices from system.data.entity.dbset
I am copying the pattern from this answer but something must be different.
Seems you forgot to put a predicate inside the Find function call. Also you need to do ToList on the collection. The second option is a lot more efficient. The first one gets the whole collection before selection.
Another note commented by #Alla is that the find returns a single element. So I assume another declaration had been made for 'price' in the first option I state down here.
price = prices.ToList.Find(b => b.PriceId == priceId);
Or
prices = prices.Select(b => b.PriceId == priceId);
I assume the field name is PriceId.

Trying to work with down() method from ExtJS 4.2.1

I am trying to find a specific element from my page using ExtJS 4 so I can do modifications on it.
I know its id so it should not be a problem BUT
-I tried Ext.getCmp('theId') and it just return me undefined
-I tried to use down('theId') method by passing through the view and I still get a nullresponse.
As I know the id of the element I tried again the two methods by setting manually the id and it didn't work neither.
Do these two methods not function?
How should I do?
Here is the concerned part of the code :
listeners: {
load: function(node, records, successful, eOpts) {
var ownertree = records.store.ownerTree;
var boundView = ownertree.dockedItems.items[1].view.id;
var generalId = boundView+'-record-';
// Add row stripping on leaf nodes when a node is expanded
//
// Adding the same feature to the whole tree instead of leaf nodes
// would not be much more complicated but it would require iterating
// the whole tree starting with the root node to build a list of
// all visible nodes. The same function would need to be called
// on expand, collapse, append, insert, remove and load events.
if (!node.tree.root.data.leaf) {
// Process each child node
node.tree.root.cascadeBy(function(currentChild) {
// Process only leaf
if (currentChild.data.leaf) {
var nodeId = ""+generalId+currentChild.internalId;
var index = currentChild.data.index;
if ((index % 2) == 0) {
// even node
currentChild.data.cls.replace('tree-odd-node', '')
currentChild.data.cls = 'tree-even-node';
} else {
// odd node
currentChild.data.cls.replace('tree-even-node', '')
currentChild.data.cls = 'tree-odd-node';
}
// Update CSS classes
currentChild.triggerUIUpdate();
console.log(nodeId);
console.log(ownertree.view.body);
console.log(Ext.getCmp(nodeId));
console.log(Ext.getCmp('treeview-1016-record-02001001'));
console.log(ownertree.view.body.down(nodeId));
console.log(ownertree.view.body.down('treeview-1016-record-02001001'));
}
});
}
}
You can see my console.log at the end.
Here is what they give me on the javascript console (in the right order):
treeview-1016-record-02001001
The precise id I am looking for. And I also try manually in case...
h {dom: table#treeview-1016-table.x-treeview-1016-table x-grid-table, el: h, id: "treeview-1016gridBody", $cache: Object, lastBox: Object…}
I checked every configs of this item and its dom and it is exactly the part of the dom I am looking for, which is the view containing my tree. The BIG parent
And then:
undefined
undefined
null
null
Here is the item I want to access:
<tr role="row" id="treeview-1016-record-02001001" ...>
And I checked there is no id duplication anywhere...
I asked someone else who told me these methods do not work. The problem is I need to access this item to modify its cls.
I would appreciate any idea.
You are looking for Ext.get(id). Ext.getCmp(id) is used for Ext.Components, and Ext.get(id) is used for Ext.dom.Elements. See the docs here: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext-method-get
Ok so finally I used the afteritemexpand listener. With the ids I get the elements I am looking for with your Ext.get(id) method kevhender :).
The reason is that the dom elements where not completely loaded when I used my load listener (it was just the store) so the Ext.get(id) method couldn't get the the element correctly. I first used afterlayout listener, that was correct but too often called and the access to the id was not so easy.
So, here is how I did finally :
listeners: {
load: function(node, records, successful, eOpts) {
var ownertree = records.store.ownerTree;
var boundView = ownertree.dockedItems.items[1].view.id;
var generalId = boundView+'-record-';
if (!node.tree.root.data.leaf) {
// Process each child node
node.tree.root.cascadeBy(function(currentChild) {
// Process only leaf
if (currentChild.data.leaf) {
var nodeId = ""+generalId+currentChild.internalId;
var index = currentChild.data.index;
if ( (index % 2) == 0 && ids.indexOf(nodeId) == -1 ) {
ids[indiceIds] = nodeId;
indiceIds++;
}
console.log(ids);
}
});
}
},
afteritemexpand: function( node, index, item, eOpts ){
/* This commented section below could replace the load but the load is done during store loading while afteritemexpand is done after expanding an item.
So, load listener makes saving time AND makes loading time constant. That is not the case if we just consider the commented section below because
the more you expand nodes, the more items it will have to get and so loading time is more and more important
*/
// var domLeaf = Ext.get(item.id).next();
// for ( var int = 0; int < node.childNodes.length; int++) {
// if (node.childNodes[int].data.leaf && (int % 2) == 0) {
// if (ids.indexOf(domLeaf.id) == -1) {
// ids[indiceIds] = domLeaf.id;
// indiceIds++;
// }
// }
// domLeaf = domLeaf.next();
// }
for ( var int = 0; int < ids.length; int++) {
domLeaf = Ext.get(ids[int]);
if (domLeaf != null) {
for ( var int2 = 0; int2 < domLeaf.dom.children.length; int2++) {
if (domLeaf.dom.children[int2].className.search('tree-even-node') == -1){
domLeaf.dom.children[int2].className += ' tree-even-node';
}
}
}
}
},
With ids an Array of the ids I need to set the class.
Thank you for the method.

Jumping between forms in C# that are in random order

Created a survey style application using forms, it contains 30 forms. For example, the first page asks the user to check which surveys to load, and according to their checks it opens up the correct form. Everything works correctly in one direction. The way I have the program set up is the first page saves static Boolean variables, The control class (Main method), checks if the variables are true or false then opens the corresponding forms. Like this;
if (Survey.r == true || Survey.s == true || SurveySelection.M == true )
{
Form6 newform6 = new Form6();
Form6.Hide();
Form6.ShowDialog();
Form7 newform7 = new Form6();
Form7.Hide();
Form7.ShowDialog();
}
if (Survey.t == true)
{
Form12 newform12 = new Form12();
newform12.Hide();
newform12.ShowDialog();
}
And So on in total 30 forms. The next button on each form just contains this.Hide(), on them.
The problem is if I were to add a back button on this Survey,
I am not sure how to handle it, since the survey is not linear is more logical since it depends on the type of survey the user chooses.
It could load forms 4,19,24,26 in one instance and 3, 6, 9 in other. I need help or guidance implementing a back button to this logic. Any help would be appreciated.
Thirty forms is not a lot. You could create a List and maintain a pointer to the current location.
private InitializeKnowSequence()
{
_formIndex = 0;
_formsList.Add(new Form2());
_formsList.Add(new Form2());
_formsList.Add(new Form3());
_formsList.Add(new Form4());
}
private void NavigatePrior()
{
if (_formIndex > 0)
{
_formsList[_formIndex--].Hide();
_formsList[_formIndex].Show();
}
}
private void NavigateNext()
{
if(_formIndex<_formsList.Count()-1)
{
_formsList[_formIndex++].Hide();
_formsList[_formIndex].Show();
}
}
Then add a PushForm(Form form) method for logical branches forward
private void PushForm(Form form)
{
_formsList.Add(form);
NavigateNext();
}

Is there an Update Object holder on Entity Framework?

I'm currently inserting/updating fields like this (if there's a better way, please say so - we're always learning)
public void UpdateChallengeAnswers(List<ChallengeAnswerInfo> model, Decimal field_id, Decimal loggedUserId)
{
JK_ChallengeAnswers o;
foreach (ChallengeAnswerInfo a in model)
{
o = this.FindChallengeAnswerById(a.ChallengeAnswerId);
if (o == null) o = new JK_ChallengeAnswers();
o.answer = FilterString(a.Answer);
o.correct = a.Correct;
o.link_text = "";
o.link_url = "";
o.position = FilterInt(a.Position);
o.updated_user = loggedUserId;
o.updated_date = DateTime.UtcNow;
if (o.challenge_id == 0)
{
// New record
o.challenge_id = field_id; // FK
o.created_user = loggedUserId;
o.created_date = DateTime.UtcNow;
db.JK_ChallengeAnswers.AddObject(o);
}
else
{
// Update record
this.Save();
}
}
this.Save(); // Commit changes
}
As you can see there is 2 times this.Save() (witch invokes db.SaveChanges();)
when Adding we place the new object into a Place Holder with the AddObject method, in other words, the new object is not committed right away and we can place as many objects we want.
But when it's an update, I need to Save first before moving on to the next object, is there a method that I can use in order to, let's say:
if (o.challenge_id == 0)
{
// New record
o.challenge_id = field_id;
o.created_user = loggedUserId;
o.created_date = DateTime.UtcNow;
db.JK_ChallengeAnswers.AddObject(o);
}
else
{
// Update record
db.JK_ChallengeAnswers.RetainObject(o);
}
}
this.Save(); // Only save once when all objects are ready to commit
}
So if there are 5 updates, I don't need to save into the database 5 times, but only once at the end.
Thank you.
Well if you have an object which is attached to the graph, if you modify values of this object, then the entity is marked as Modified.
If you simply do .AddObject, then the entity is marked as Added.
Nothing has happened yet - only staging of the graph.
Then, when you execute SaveChanges(), EF will translate the entries in the OSM to relevant store queries.
Your code looks a bit strange. Have you debugged through (and ran a SQL trace) to see what is actually getting executed? Because i can't see why you need that first .Save, because inline with my above points, since your modifying the entities in the first few lines of the method, an UPDATE statement will most likely always get executed, regardless of the ID.
I suggest you refactor your code to handle new/modified in seperate method. (ideally via a Repository)
Taken from Employee Info Starter Kit, you can consider the code snippet as below:
public void UpdateEmployee(Employee updatedEmployee)
{
//attaching and making ready for parsistance
if (updatedEmployee.EntityState == EntityState.Detached)
_DatabaseContext.Employees.Attach(updatedEmployee);
_DatabaseContext.ObjectStateManager.ChangeObjectState(updatedEmployee, System.Data.EntityState.Modified);
_DatabaseContext.SaveChanges();
}