Entity Framework not adding multiple objects - asp.net-core

Im trying to add some dummy content into my database. I have a sample object called "obj", and I'm using a for loop to insert data like the code below:
public async Task<Post> Add(Post obj)
{
if (db != null)
{
obj.Id = 0;
for (int i = 0; i < 100; i++)
{
await db.Post.AddAsync(obj);
}
await db.SaveChangesAsync();
return obj;
}
return null;
}
However, it does add only 1 record into database, could you please explain what's wrong here?

Can you create object of post inside the loop and try again?
for (int i = 0; i < 100; i++)
{
Post obj = new Post();
await db.Post.AddAsync(obj);
}

If you run the below commands before calling saved changes you can see what changes EF Core has queued up.
var post = new Post();
for (int i = 0; i < 10; i++)
{
await db.Posts.AddAsync(dev);
}
db.ChangeTracker.DetectChanges();
Debug.WriteLine(db.ChangeTracker.DebugView.LongView);
await db.SaveChangesAsync();
This will write to Debug that one post is currently being tracked.
for (int i = 0; i < 10; i++)
{
var post = new Post();
await db.Posts.AddAsync(dev);
}
db.ChangeTracker.DetectChanges();
Debug.WriteLine(db.ChangeTracker.DebugView.LongView);
await db.SaveChangesAsync();
This will right to the Debug window the 10 posts are currently being tracked.
In your code when you AddAsync(obj), obj isn't a new object and EF Core is already tracking obj.
Moving Post obj = new Post() into the loop creates a new object for EF Core to track. If these objects aren't being added to the DB my guess would be that they don't meet a requirement for the Post model.
Either way playing around with
db.ChangeTracker.DetectChanges();
Debug.WriteLine(db.ChangeTracker.DebugView.LongView);
should help you be able to track down exactly what's going on.
I do hope you find this information helpful :)

You can try to use AddRange.
public async Task<Post> Add(Post obj)
{
if (db != null)
{
List<Post>=new List<Post>();
obj.Id = 0;
for (int i = 0; i < 100; i++)
{
l.Add(obj);
}
await db.Post.AddRangeAsync(l);
await db.SaveChangesAsync();
return obj;
}
return null;
}

Related

Photoshop Scripting: Relink Smart Object

I'm working on a script that should go through a photoshop document and relink all visible linked objects to a new specified file. I've gotten the loop working so that it cycles through every layer and collects only the visible layers, but for the life of me I can't find if there's a method available to relink a smart object. The closest I've found is this script:
https://gist.github.com/laryn/0a1f6bf0dab5b713395a835f9bfa805c
but when it gets to desc3.putPath(idnull, new File(newFile));, it spits out an error indicating that the functionality may not be present in the current Photoshop version. The script itself is 4 years old so it may be out of date.
Any help would be appreciated!
MY script as it stands is below:
// SELECT FILE //
var files = File.openDialog("Please select new linked file");
var selectedFile = files[0];
// GET ALL LAYERS //
var doc = app.activeDocument;
var allLayers = [];
var allLayers = collectAllLayers(doc, allLayers);
function collectAllLayers (doc, allLayers)
{
for (var m = 0; m < doc.layers.length; m++)
{
var theLayer = doc.layers[m];
if (theLayer.typename === "ArtLayer")
{
allLayers.push(theLayer);
}
else
{
collectAllLayers(theLayer, allLayers);
}
}
return allLayers;
}
// GET VISIBLE LAYERS //
var visibleLayers = [];
for (i = 0; i < allLayers.length; i++)
{
var layer = allLayers[i];
if (layer.visible && layer.kind == LayerKind.SMARTOBJECT)
{
visibleLayers.push(layer);
}
}
// REPLACE LAYERS
for (i = 0; i < visibleLayers.length; i++)
{
var layer = visibleLayers[i];
//--> REPLACE THE FILE HERE
}
Note: I am aware that this script currently may be error-prone if you don't know exactly how it works; I'm not intending to publish it at this time so I'm not super concerned with that at the moment. Mostly I just need the core functionality to work.
I used an AM function for getting visible smart objects — it works much faster. But if you want you can use yours. The important bit is relinkSO(path);: it'll also work in your script (just don't forget to select a layer: activeDocument.activeLayer = visibleLayers[i];)
Note that it works similar to Photoshop Relink to File command — if used on one instance of Smart Object all the instances are going to be relinked. If you want to relink only specific layers you'll have to break instancing first (probably using the New Smart Object via Copy command)
function main() {
var myFile = Folder.myDocuments.openDlg('Load file', undefined, false);
if (myFile == null) return false;
// gets IDs of all smart objects
var lyrs = getLyrs();
for (var i = 0; i < lyrs.length; i++) {
// for each SO id...
// select it
selectById(lyrs[i]);
// relink SO to file
relinkSO(myFile);
// embed linked if you want
embedLinked()
}
function getLyrs() {
var ids = [];
var layers, desc, vis, type, id;
try
{
activeDocument.backgroundLayer;
layers = 0;
}
catch (e)
{
layers = 1;
}
while (true)
{
ref = new ActionReference();
ref.putIndex(charIDToTypeID('Lyr '), layers);
try
{
desc = executeActionGet(ref);
}
catch (err)
{
break;
}
vis = desc.getBoolean(charIDToTypeID("Vsbl"));
type = desc.getInteger(stringIDToTypeID("layerKind"));
id = desc.getInteger(stringIDToTypeID("layerID"));
if (type == 5 && vis) ids.push(id);
layers++;
}
return ids;
} // end of getLyrs()
function selectById(id) {
var desc = new ActionDescriptor();
var ref = new ActionReference();
ref.putIdentifier(charIDToTypeID('Lyr '), id);
desc.putReference(charIDToTypeID('null'), ref);
executeAction(charIDToTypeID('slct'), desc, DialogModes.NO);
} // end of selectById()
function relinkSO(path) {
var desc = new ActionDescriptor();
desc.putPath( charIDToTypeID('null'), new File( path ) );
executeAction( stringIDToTypeID('placedLayerRelinkToFile'), desc, DialogModes.NO );
} // end of relinkSO()
function embedLinked() {
executeAction( stringIDToTypeID('placedLayerConvertToEmbedded'), undefined, DialogModes.NO );
} // end of embedLinked()
}
app.activeDocument.suspendHistory("relink SOs", "main()");

Changes reflecting in payload but is not getting applied on target widget in workdetails page in casemanager 5.2.1

In Workdetails page, under ‘Documents’ tab, when I set the alignment to ‘center’ from ‘right’ for the column value, its getting updated in payload but is not actually getting applied on target widget.
I have tried thru controller/Grid as well but its not getting set. Attached snap of same. A pointer in this regard would be of immense help.
Here is the snip:
var callbackFolderContent = function (resultset)
{
var classText = 'Abc';
var found = 0;
for (var i=0; i < resultset.length; i++)
{
var items = resultset[i].resultSet.items;
for (var j=0; j < items.length; j++)
{
var pos = id.indexOf(classText);
if(pos !== -1)
{
var PC= items[j].resultSet.structure.cells[0][3];
if(PC.styles=="text-align:right;")
{
PC.styles="text-align:center;";
var NEWpc=PC.styles; //Its reflecting in payload.
alert("Changed aligning to: "+NEWpc);
}
found ++;
} //end f if loop
} //end of inner for loop
} //end of for loop
if (found < 1)
{
payload.stateCode = 4;
payload.hideMessage=true;
abort({silent:true});
}
else
{
complete();
}
}; //end of callback function

why qml listmodel sync failed when in the worker thread,and how to solve it?

how can i change the text of the button without clicked in the listview delegate?
when i solved the question above,there is a new question.i can't use the worker to sync the model,but when i use sync not in the worker,although it has some error occured from qtcreator,but it works to sync the data role in the model ,and often, sync will fail.
dataloader.js:
WorkerScript.onMessage = function(msg) {
msg.model.sync();
}
PrinterList.qml:
WorkerScript{
id:worker
source:"dataloader.js"
}
function cmpPname(prnName)
{
console.log("cmpPname");
var tmpName = prnName.replace(/_/g," ");
console.log("tmpName=",tmpName);
var pname = new Array;
pname= Jsclient.g_str.split(',');
tmpName = tmpName.split(',');
console.log("pModel.count=",pModel.count);
for(var i = 0;i < pname.length;i++){
if(tmpName == pname[i]){
console.log("pname[%1]=".arg(i),pname[i]);
Jsclient.pstate = "Added";
pModel.setProperty(i,"prstate",qsTr(Jsclient.pstate));
// pModel.get(2).prstate = qsTr(Jsclient.pstate);
sync(); **//this works!!but often failed too.**
}else{
Jsclient.pstate = "Add";
pModel.setProperty(i,"prstate",qsTr(Jsclient.pstate));
}
worker.sendMessage({"model":pModel}); **//this failed,why?**
}
}
finally,i solved the question.
dataloader.js:
WorkerScript.onMessage = function(msg) {
console.log(msg.index,msg.prstate);
msg.model.setProperty(msg.index,"prstate",msg.prstate);
msg.model.sync();
}
list.qml:
worker.sendMessage({"index":i,"prstate":qsTr("Added"),"model":pModel});

I can't figure out how to call a variable from another method

I am am trying to call a variable in another method to my array.
var Com = the difficulty for the game. But the method below I'm trying to call the var Com, for: var c = Com.GetChoice();
Not sure why I can not figure out how to call it.
public object SetDiff()
{
Console.WriteLine("Enter difficulty #: (1 = Easy, 2 = Normal, 3 = Impossible)");
var diff = Console.ReadLine();
int mode;
int.TryParse(diff, out mode);
if (mode == 1)
{
Console.Clear();
var Com = new Easy();
return Com;
}
if (mode == 2)
{
Console.Clear();
var Com = new Medium();
return Com;
}
if (mode == 3)
{
Console.Clear();
var Com = new Hard();
return Com;
}
else
{
Console.WriteLine("That is not a valid input.");
return SetDiff();
}
} // Apparently you can't set variables in a switch.
public int[] FaceOff(int num)
{
int PlayerWin = 0;
int ComWin = 0;
int Tie = num + 1;
// TODO : Get rid of TIES!
for (int i = 0; i < num; i++)
{
var p = p1.GetChoice();
var c = Com.GetChoice();
You have many different options:
Pass as parameter
public int[] FaceOff(int num, int Com){...}
make a "global" variable
private int Com;
I would also recommend you to learn OOP (Object Orientated Programming) basics.

Roslyn - replace node and fix the whitespaces

In my program I use Roslyn and I need to replace a node with a new node. For example, if I have code like
public void Foo()
{
for(var i = 0; i < 5; i++)
Console.WriteLine("");
}
and I want to insert brackes for for statement, I get
public void Foo()
{
for(var i = 0; i < 5; i++)
{
Console.WriteLine("");
}
}
I tried to use NormalizeWhitespace, but if I use it on for statement, I get
public void Foo()
{
for(var i = 0; i < 5; i++)
{
Console.WriteLine("");
}
}
However, I'd like to have for statement formatted correctly. Any hints how to do it?
EDIT:
I solved it by using:
var blockSyntax = SyntaxFactory.Block(
SyntaxFactory.Token(SyntaxKind.OpenBraceToken).WithLeadingTrivia(forStatementSyntax.GetLeadingTrivia()).WithTrailingTrivia(forStatementSyntax.GetTrailingTrivia()),
syntaxNodes,
SyntaxFactory.Token(SyntaxKind.CloseBraceToken).WithLeadingTrivia(forStatementSyntax.GetLeadingTrivia()).WithTrailingTrivia(forStatementSyntax.GetTrailingTrivia())
);
However, the answer from Sam is also correct.
You need to use .WithAdditionalAnnotations(Formatter.Annotation), but only on the specific element you want to format. Here's an example from the NullParameterCheckRefactoring project.
IfStatementSyntax nullCheckIfStatement = SyntaxFactory.IfStatement(
SyntaxFactory.Token(SyntaxKind.IfKeyword),
SyntaxFactory.Token(SyntaxKind.OpenParenToken),
binaryExpression,
SyntaxFactory.Token(SyntaxKind.CloseParenToken),
syntaxBlock, null).WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation);