JSTree creating duplicate nodes when loading data with create_node - jstree

I'm having an issue when I'm trying to load my initial data for JSTree; I have 2 top level nodes attached to the root node but when I load them it looks like the last node added is being duplicated within JSTree. At first it looked as if it was my fault for not specifically declaring a new object each time but I've fixed that. I'm using .net MVC so the initial data is coming from the model that is passed to my view (that is the data passed into the data parameter of the method).
this.loadInitialData = function (data) {
var tree = self.getTree();
for (var i = 0; i < data.length; i++) {
var node = new Object();
node.id = data[i].Id;
node.parent = data[i].Parent;
node.text = data[i].Text;
node.state = {
opened: data[i].State.Opened,
disabled: data[i].State.Disabled,
selected: data[i].State.Selected
};
node.li_attr = { "node-type": data[i].NodeType };
node.children = [];
for (var j = 0; j < data[i].Children.length; j++) {
var childNode = new Object();
childNode.id = data[i].Children[j].Id;
childNode.parent = data[i].Children[j].Parent;
childNode.text = data[i].Children[j].Text;
childNode.li_attr = { "node-type": data[i].Children[j].NodeType };
childNode.children = data[i].Children[j].HasChildren;
node.children.push(childNode);
}
tree.create_node("#", node, "last");
}
}
My initial code was declaring node like the following:
var node = {
id: data[i].Id
}
I figured that was the cause of what I'm seeing but fixing it has not changed anything. Here is what is happening when I run the application; on the first pass of the method everything looks like it is working just fine.
But after the loop is run for the second (and last) time here is the final result.
It looks like the node objects are just a copy of each other, but when I run the code through the debugger I see the object being initialized each time. Does anyone have an idea what would cause this behavior in JSTree? Should I be using a different method to create my initial nodes besides create_node?
Thanks in advance.

I found the issue; I didn't realize but I was setting my id property to the same id for both node groups. After I fixed it everything started working as expected.

Related

bing maps upgrading from v7 to v8 error with userMapView

I'm upgrading a project from using the bing maps v7 ajax api to using the v8 api. I've run into a problem where I'm getting back a message saying that "The waypoint you entered cannot be found." So I backed up and modified a sample screen to do what I'm doing and it works fine. So I've narrowed it down (with fiddler) to the REST calls that are made for each waypoint getting an error saying the userMapView is out of range in the first case but works fine in the second. I'm not really sure why this might be different in the sample code versus my actual app. Here are the two URLs. The first is the one that fails:
https://dev.virtualearth.net/REST/v1/Locations/?q=Cincinnati%2C%20OH&o=json&culture=en-US&jsonp=Microsoft.Maps.NetworkCallbacks.f5de44&key=MY_BING_MAPS_KEY&maxResults=5&userMapView=39.18820190429691,-180,39.18820190429691,-180&inclnb=0&incl=
https://dev.virtualearth.net/REST/v1/Locations/?q=cincinnati%2C%20oh&o=json&culture=en-US&jsonp=Microsoft.Maps.NetworkCallbacks.f66617&key=MY_BING_MAPS_KEY&maxResults=5&userMapView=39.02836016935031,-85.12275695800781,39.34768093312603,-85.12275695800781&inclnb=0&incl=
If I replace the userMapView parameter of the first URL with those of the second, the first URL works too. It seems obvious that the "-180" degree part is incorrect, but I don't know how it is getting there.
BTW, both of these URLs were generated using my dev key.
Thanks for any help!
EDIT:
Here's the bulk of the code that runs into trouble. Prior to this I've new'd the Map. This code is the callback from the loadModule of the Directions module. The code is a little convoluted beyond that though as I'm plugging in origins and destinations from the form. Also note, not that it makes much difference, that userAddress is passed into this function as true.
function createDrivingRoute(useAddress) {
directionsManager = new Microsoft.Maps.Directions.DirectionsManager(bmap);
locs = [];
var fromWayPoint;
fromWayPoint = new Microsoft.Maps.Directions.Waypoint({ address: fromAddressSearch });
locs.push(fromWayPoint);
directionsManager.addWaypoint(fromWayPoint);
if (toLocationArray != null) {
if (toLocationArray.length == 1) {
if (toLocationArray[0] == false) {
toLocationArray = [];
}
}
}
if (useAddress) {
if (toLocationArray != null) {
for (i = 0; i < toLocationArray.length; i++) {
//var toWayPointLoc = new Microsoft.Maps.Directions.Waypoint({ location: toLocationArray[i] });
var toWayPointLoc = new Microsoft.Maps.Directions.Waypoint({ address: toLocationArray[i] });
locs.push(toWayPointLoc);
directionsManager.addWaypoint(toWayPointLoc);
}
for (i = 0; i < toAddressArray.length; i++) {
var toWayPoint = new Microsoft.Maps.Directions.Waypoint({ address: toAddressArray[i] });
locs.push(toWayPoint);
directionsManager.addWaypoint(toWayPoint);
}
} else {
for (i = 0; i < toAddressArray.length; i++) {
var toWayPoint = new Microsoft.Maps.Directions.Waypoint({ address: toAddressArray[i] });
locs.push(toWayPoint);
directionsManager.addWaypoint(toWayPoint);
}
}
} else {
if (toLocationArray != null) {
for (i = 0; i < toLocationArray.length; i++) {
//var toWayPointLoc = new Microsoft.Maps.Directions.Waypoint({ location: toLocationArray[i] });
var toWayPointLoc = new Microsoft.Maps.Directions.Waypoint({ address: toLocationArray[i] });
locs.push(toWayPointLoc);
directionsManager.addWaypoint(toWayPointLoc);
}
}
for (i = 0; i < toAddressArray.length; i++) {
var toWayPoint = new Microsoft.Maps.Directions.Waypoint({ address: toAddressArray[i] });
locs.push(toWayPoint);
directionsManager.addWaypoint(toWayPoint);
}
}
if ($get("<%= chkReturnOrigin.ClientID %>").checked) {
var returnWayPoint = new Microsoft.Maps.Directions.Waypoint({ address: fromAddressSearch });
directionsManager.addWaypoint(fromWayPoint);
}
// Set the element in which the itinerary will be rendered
directionsManager.setRenderOptions({ itineraryContainer: '#directions' });
// Specify a handler for when the directions are calculated
if (directionsUpdatedEventObj) {
Microsoft.Maps.Events.removeHandler(directionsUpdatedEventObj);
directionsUpdatedEventObj = null;
}
directionsUpdatedEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', onDirectionsDisplayedEvent);
if (directionsErrorEventObj) {
Microsoft.Maps.Events.removeHandler(directionsErrorEventObj);
directionsErrorEventObj = null;
}
directionsErrorEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', onDirectionsErrorEvent);
loadedRoute = null;
loadedSteps = [];
directionsManager.calculateDirections();
var destAddress = $get("<%= DestAddressList.ClientID %>").value;
if (destAddress == null || destAddress == "") {
document.getElementById("DistTotal").innerHTML = '';
}
}
Haven't seen this issue before, very odd. Take a look at your code, if you are using the Search module to do the geocoding, don't set the bounds option and see if it that corrects the issue. The bounds property is used to set the userMapView property of the REST request. If that works, then there is likely an issue with the LocationRect object being passed in, or how the search module uses it. I'll take a look into the source code to see if there is a bug that might be causing this.
Update 1: Now that I see your edit and see that you are using the directions manager I'm able to see that the userMapView is automatically added from the map. Not sure why it would be adding such incorrect values though. It looks like they are adding the same coordinate twice rather than adding the northwest and southeast coordinates. Will see if I can verify this by digging through the code.
Update 2: I've found the bug in the code. I have logged this with the development team so that they can resolve it the next time they touch the code for the search manager. The issue is that the west value is being added to the userMapView request twice, but not adding east value.
Update 3: Good news, this bug is now resolved in the experimental branch of Bing Maps. You can try this out by adding "&branch=experimental" to the map script URL. This will be added to the release branch in the next regular update planned for February.

Manatee.Trello Moving Cards

I'm writing a small application to manage Trello Boards in only a few aspects such as sorting Cards on a List, moving/copying Cards based on Due Date and/or Labels, archiving Lists on a regular basis and generating reports based on Labels, etc. As such, I've been putting together a facade around the Manatee.Trello library to simplify the interface for my services.
I've been getting comfortable with the library and things have been relatively smooth. However, I wrote an extension method on the Card class to move Cards within or between Lists, and another method that calls this extension method repeatedly to move all Cards from one List to another.
My issue is that when running the code on a couple of dummy lists with 7 cards in one, it completes without error, but at least one card doesn't actually get moved (though as many as 3 cards have failed to move). I can't tell if this is because I'm moving things too rapidly, or if I need to adjust the TrelloConfiguration.ChangeSubmissionTime, or what. I've tried playing around with delays but it doesn't help.
Here is my calling code:
public void MoveCardsBetweenLists(
string originListName,
string destinationListName,
string originBoardName,
string destinationBoardName = null)
{
var fromBoard = GetBoard(originBoardName); // returns a Manatee.Trello.Board
var toBoard = destinationBoardName == null
|| destinationBoardName.Equals(originBoardName, StringComparison.OrdinalIgnoreCase)
? fromBoard
: GetBoard(destinationBoardName);
var fromList = GetListFromBoard(originListName, fromBoard); // returns a Manatee.Trello.List from the specified Board
var toList = GetListFromBoard(destinationListName, toBoard);
for (int i = 0; i < fromList.Cards.Count(); i++)
{
fromList.Cards[i].Move(1, toList);
}
}
Here is my extension method on Manatee.Trello.Card:
public static void Move(this Card card, int position, List list = null)
{
if (list != null && list != card.List)
{
card.List = list;
}
card.Position = position;
}
I've created a test that replicates the functionality you want. Basically, I create 7 cards on my board, move them to another list, then delete them (just to maintain initial state).
private static void Run(System.Action action)
{
var serializer = new ManateeSerializer();
TrelloConfiguration.Serializer = serializer;
TrelloConfiguration.Deserializer = serializer;
TrelloConfiguration.JsonFactory = new ManateeFactory();
TrelloConfiguration.RestClientProvider = new WebApiClientProvider();
TrelloAuthorization.Default.AppKey = TrelloIds.AppKey;
TrelloAuthorization.Default.UserToken = TrelloIds.UserToken;
action();
TrelloProcessor.Flush();
}
#region http://stackoverflow.com/q/39926431/878701
private static void Move(Card card, int position, List list = null)
{
if (list != null && list != card.List)
{
card.List = list;
}
card.Position = position;
}
[TestMethod]
public void MovingCards()
{
Run(() =>
{
var list = new List(TrelloIds.ListId);
var cards = new List<Card>();
for (int i = 0; i < 10; i++)
{
cards.Add(list.Cards.Add("test card " + i));
}
var otherList = list.Board.Lists.Last();
for(var i = 0; i < cards.Count; i++)
{
Move(card, i, otherList);
}
foreach (var card in cards)
{
card.Delete();
}
});
}
#endregion
Quick question: Are you calling TrelloProcessor.Flush() before your execution ends? If you don't, then some changes will likely remain in the request processor queue when the application ends, so they'll never be sent. See my wiki page on processing requests for more information.
Also, I've noticed that you're using 1 as the position for each move. By doing this, you'll end up with an unreliable ordering. The position data that Trello uses is floating point. To position a card between two other cards, it simply takes the average of the other cards. In your case, (if the destination list is empty), I'd suggest sending in the indexer variable for the ordering. If the destination list isn't empty, you'll need to calculate a new position based on the other cards in the list (by the averaging method Trello uses).
Finally, I like the extension code you have. If you have ideas that you think would be useful to add to the library, please feel free to fork the GitHub repo and create a pull request.

Unable to add data in archive table in Entity Framework

I wrote the code to update my table (SecurityQuestionAnswer) with new security password questions and move to old questions to another table (SecurityQuestionAnswersArchives). Total no of security questions is 3. I am able to update the current table, but when I add the same rows to history table, it shows weird data: only two records are added instead of 3 and the data is also duplicated. My code is as follows:
if (oldQuestions.Any())
{
var oldquestionstoarchivelist = new List<SecurityQuestionAnswersArchives>();
var oldquestionstoarchive =new SecurityQuestionAnswersArchives();
for (int i = 0; i < 3; i++)
{
oldquestionstoarchive.Id = oldQuestions[i].Id;
oldquestionstoarchive.SecurityQuestionId = oldQuestions[i].SecurityQuestionId;
oldquestionstoarchive.Answer = oldQuestions[i].Answer;
oldquestionstoarchive.UpdateDate = oldQuestions[i].UpdateDate;
oldquestionstoarchive.IpAddress = oldQuestions[i].IpAddress;
oldquestionstoarchive.SecurityQuestion = oldQuestions[i].SecurityQuestion;
oldquestionstoarchive.User = oldQuestions[i].User;
oldquestionstoarchivelist.Add(oldquestionstoarchive);
}
user.SecurityQuestionAnswersArchives = oldquestionstoarchivelist;
//await Store.UpdateAsync(user);
_dbContext.ArchiveSecurityQuestionAnswers.AddRange(oldquestionstoarchivelist);
_dbContext.SecurityQuestionAnswers.RemoveRange(oldQuestions);
await _dbContext.SaveChangesAsync();
oldquestionstoarchivelist.Clear();
}
UPDATE 1
The loop looks fine, It iterates three times(0,1,2), which is expected. First issue is with AddRange function to which I was passing a list , but it takes an IEnumerable input, I rectified it using following code.
IEnumerable<SecurityQuestionAnswersArchives> finalArchiveses = oldquestionstoarchivelist;
_dbContext.ArchiveSecurityQuestionAnswers.AddRange(finalArchiveses);
The other issue is duplicate data , which I am unable to figure out where the issue is. Please help me in finding this out.
Your help is much appreciated !
Got it ! Just sharing in case anybody has same issue.
The problem was with initialization at wrong place. I moved
var oldquestionstoarchive =new SecurityQuestionAnswersArchives();
in side the Forloop, now the variable will hold the unique values over each iteration.
var oldquestionstoarchivelist = new List<SecurityQuestionAnswersArchives>();
for (int i = 0; i < 3; i++)
{
var oldquestionstoarchive = new SecurityQuestionAnswersArchives();
oldquestionstoarchive.SecurityQuestionId = oldQuestions[i].SecurityQuestionId;
oldquestionstoarchive.Answer = oldQuestions[i].Answer;
oldquestionstoarchive.UpdateDate = oldQuestions[i].UpdateDate;
oldquestionstoarchive.IpAddress = oldQuestions[i].IpAddress;
oldquestionstoarchive.SecurityQuestion = oldQuestions[i].SecurityQuestion;
oldquestionstoarchive.User = oldQuestions[i].User;
oldquestionstoarchivelist.Add(oldquestionstoarchive);
}

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.

.Net Entity Framework SaveChanges is adding without add method

I'm new to the entity framework and I'm really confused about how savechanges works. There's probably a lot of code in my example which could be improved, but here's the problem I'm having.
The user enters a bunch of picks. I make sure the user hasn't already entered those picks.
Then I add the picks to the database.
var db = new myModel()
var predictionArray = ticker.Substring(1).Split(','); // Get rid of the initial comma.
var user = Membership.GetUser();
var userId = Convert.ToInt32(user.ProviderUserKey);
// Get the member with all his predictions for today.
var memberQuery = (from member in db.Members
where member.user_id == userId
select new
{
member,
predictions = from p in member.Predictions
where p.start_date == null
select p
}).First();
// Load all the company ids.
foreach (var prediction in memberQuery.predictions)
{
prediction.CompanyReference.Load();
}
var picks = from prediction in predictionArray
let data = prediction.Split(':')
let companyTicker = data[0]
where !(from i in memberQuery.predictions
select i.Company.ticker).Contains(companyTicker)
select new Prediction
{
Member = memberQuery.member,
Company = db.Companies.Where(c => c.ticker == companyTicker).First(),
is_up = data[1] == "up", // This turns up and down into true and false.
};
// Save the records to the database.
// HERE'S THE PART I DON'T UNDERSTAND.
// This saves the records, even though I don't have db.AddToPredictions(pick)
foreach (var pick in picks)
{
db.SaveChanges();
}
// This does not save records when the db.SaveChanges outside of a loop of picks.
db.SaveChanges();
foreach (var pick in picks)
{
}
// This saves records, but it will insert all the picks exactly once no matter how many picks you have.
//The fact you're skipping a pick makes no difference in what gets inserted.
var counter = 1;
foreach (var pick in picks)
{
if (counter == 2)
{
db.SaveChanges();
}
counter++;
}
I've tested and the SaveChanges doesn't even have to be in the loop.
The below code works, too.
foreach (var pick in picks)
{
break;
}
db.SaveChanges()
There's obviously something going on with the context I don't understand. I'm guessing I've somehow loaded my new picks as pending changes, but even if that's true I don't understand I have to loop over them to save changes.
Can someone explain this to me?
Here's updated working code based on Craig's responses:
1) Remove the Type then loop over the results and populate new objects.
var picks = (from prediction in predictionArray
let data = prediction.Split(':')
let companyTicker = data[0]
where !(from i in memberQuery.predictions
select i.Company.ticker).Contains(companyTicker)
select new //NO TYPE HERE
{
Member = memberQuery.member,
Company = db.Companies.Where(c => c.ticker == companyTicker).First(),
is_up = data[1] == "up", // This turns up and down into true and false.
}).ToList();
foreach (var prediction in picks)
{
if (includePrediction)
{
var p = new Prediction{
Member = prediction.Member,
Company = prediction.Company,
is_up = prediction.is_up
};
db.AddToPredictions(p);
}
}
2) Or if I don't want the predictions to be saved, I can detach the predictions.
foreach (var prediction in picks) {
if (excludePrediction)
{
db.Detach(prediction)
}
}
The reason is here:
select new Prediction
{
Member = memberQuery.member,
These lines will (once the IEnumerable is iterated; LINQ is lazy) :
Instantiate a new Prediction
Associate that Prediction with an existing Member, *which is attached to db.
Associating an instance of an entity with an attached entity automatically adds that entity to the context of the associated, attached entity.
So as soon as you start iterating over predictionArray, the code above executes and you have a new entity in your context.