Linq to SQL InsertOnSubmit for multiple objects - linq-to-sql

I have a problem with Linq to SQL InsertOnSubmit, which only seems to work for the first item in a table.
For example with the following:
var noteDetail1 = new NoteDetail() { Title = "Test Note Title 1", NoteText = "Test note" };
var waiverDetail1 = new WaiverDetail() { Title = "Test Waiver Title 1", NoteText = "Test waiver details text" };
var riskDetail1 = new RiskDetail() { Title = "Test Risk Title 1", NoteText = "Test risk details text" };
context.Notes.InsertOnSubmit(noteDetail1);
context.Notes.InsertOnSubmit(riskDetail1);
context.Notes.InsertOnSubmit(waiverDetail1);
context.SubmitChanges();
I only get the first entity ("Test Note Title 1") inserted into the database. If I place a SubmitChanges after each InsertOnSubmit, all the rows are successfully inserted.
The above Types are all inherited from a Note class, so are inserted into the same table.
I am, however, experiencing the same problem with non-derived classes.
I've spent a long time looking at this but can't find what I've done wrong. The whole idea of InsertOnSubmit/SubmitChanges is so that you can do multiple changes so there must be something simple I am missing.

The problem was that I had overriden Equals in my entity classes so that entities with the same Id were considered the same. Obviously, Linq to SQL is using this at some point and getting the result that all new entities are equal (because they all have the Id of 0).
Thanks Jonathan for being my "Rubber Duck".

Related

Nodejs Array keeps distributing array over multiple lines

To keep this short, i m working on a small discord bot. The bot is supposed to grab a servers banlist and then put it into its database. The problem is, to make a bulk insert, you appearently need an array that is stuctured like this
[
["blah 1", "bluh 1"],
["blah 2", "bluh 2"]
]
The problem that i m facing is, it distorts the formatting of the array for some reason
[
["blah 1", "bluh 1"],
[
"blah 1",
"bluh 1"
],
]
This is the code i use to create the array
list.forEach(element => {
if(element.reason === null){ var reason = "No reason Given"}else{ var reason = element.reason}
var userArray = [
element.user.id,
element.user.username,
element.user.discriminator,
reason,
element.user.bot
]
banArray.push(userArray)
})
Okay, to put this short again (its 4:11 am here right now, and i m lacking a lot of sleep). I found the problem i was having. I tried to use an array in my prepared statement while putting the unknown value into brackets.
queryStmt = "INSERT INTO tbl_bans (dtUserId, dtUserName, dtDiscriminator, dtReason, dtBot) VALUES (?)";
Notice the (?). The problem is, that i simply didnt look correctly at the code sample, and overlooked that there were no () around the ? in the sample.

Mongo db and using maps in queries

Im new to mongo and am trygin to figure out queries, im using java driver
I have a document in the database which is as follows
{"name":"joe", "surname":"bloggs", "other": {"name":"fred", "surname" : "flint"}, "important" : "important info that does not chnage" }
Now i want to do a upsert on the document and only update it if it does not exist
I have the following which i wan tto insert if it doesnt exist and update if it does.
Bson filter = Filters.and(
Filters.eq("name", oldObj.getName()),
Filters.eq("surname", oldObj.getSurname()),
Filters.eq("translations", oldObj.getOtherMap())
);
Document documentToInsertUpdate = new Document();
documentToInsertUpdate.put("important", newObj.getInfo());
documentToInsertUpdate.put("name", newObj.getName());
documentToInsertUpdate.put("surname", newObj.getSurname());
documentToInsertUpdate.put("other", newObj.getOtherMap());
Bson update = new Document("$set", documentToInsertUpdate);
UpdateOptions options = new UpdateOptions().upsert(true);
collection.updateOne(filter, update, options, getSingleResultCallback(new ArrayList<Translations>()));
there seems to be a problem when i try to set the "other" section of the json in the filter and the document, it doesnt work. If i remove the "other" sections from the filter and documentToInsertUpdate it works fine.
How can i work with the second part i.e
"other": {"name":"fred", "surname" : "flint"}

Make dynamic name text field in Postman

I'm using Postman to make REST API calls to a server. I want to make the name field dynamic so I can run the request with a unique name every time.
{
"location":
{
"name": "Testuser2", // this should be unique, eg. Testuser3, Testuser4, etc
"branding_domain_id": "52f9f8e2-72b7-0029-2dfa-84729e59dfee",
"parent_id": "52f9f8e2-731f-b2e1-2dfa-e901218d03d9"
}
}
In Postman you want to use Dynamic Variables.
The JSON you post would look like this:
{
"location":
{
"name": "{{$guid}}",
"branding_domain_id": "52f9f8e2-72b7-0029-2dfa-84729e59dfee",
"parent_id": "52f9f8e2-731f-b2e1-2dfa-e901218d03d9"
}
}
Note that this will give you a GUID (you also have the option to use ints or timestamps) and I'm not currently aware of a way to inject strings (say, from a test file or a data generation utility).
In Postman you can pass random integer which ranges from 0 to 1000, in your data you can use it as
{
"location":
{
"name": "Testuser{{$randomInt}}",
"branding_domain_id": "52f9f8e2-72b7-0029-2dfa-84729e59dfee",
"parent_id": "52f9f8e2-731f-b2e1-2dfa-e901218d03d9"
}
}
Just my 5 cents to this matter. When using randomInt there is always a chance that the number might eventually be present in the DB which can cause issues.
Solution (for me at least) is to use $timestamp instead.
Example:
{
"username": "test{{$timestamp}}",
"password": "test"
}
For anyone who's about to downvote me this post was made before the discussion in comments with the OP (see below). I'm leaving it in place so the comment from the OP which eventually described what he needs isn't removed from the question.
From what I understand you're looking for, here's a basic solution. It's assuming that:
you're developing some kind of script where you need test data
the name field should be unique each time it's run
If your question was more specific then I'd be able to give you a more specific answer, but this is the best I can do from what's there right now.
var counter = location.hash ? parseInt(location.hash.slice(1)) : 1; // get a unique counter from the URL
var unique_name = 'Testuser' + counter; // create a unique name
location.hash = ++counter; // increase the counter by 1
You can forcibly change the counter by looking in the address bar and changing the URL from ending in #1 to #5, etc.
You can then use the variable name when you build your object:
var location = {
name: unique_name,
branding_domain_id: 'however-you-currently-get-it',
parent_id: 'however-you-currently-get-it'
};
Add the below text in pre-req:
var myUUID = require('uuid').v4();
pm.environment.set('myUUID', myUUID);
and use the myUUID wherever you want
like
name: "{{myUUID}}"
It will generate a random unique GUID for every request
var uuid = require('uuid');
pm.globals.set('unique_name', 'testuser' + uuid.v4());
add above code to the pre-request tab.
this was you can reuse the unique name for subsequent api calls.
Dynamic variable like randomInt, or guid is dynamic ie : you donot know what was send in the request. there is no way to refer it again, unless it is send back in response. even if you store it in a variable,it will still be dynamic
another way is :
var allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var shuffled_unique_str = allowed.split('').sort(function(){return 0.5-Math.random()}).join('');
courtsey refer this link for more options

Getting and displaying JSON data fields using HTML and AngularJS

Im new to angularJS and web designing as a whole. Im trying to get a data field(or element) from a JSON. For example, this is what the JSON looks like
{
"Name":"Raymond Eugene Monce",
"Dateofbirth":"1924-0308T00:00:00Z",
"Ethnicity":"Caucasian",
"Languages":["{English}"],
},
and I'm trying to get the "Name" data field. This is what my .js file looks like,
var profile = angular.module('profile', ['ui.bootstrap','ngResource']);
profile.controller("profileController", ["$scope","$resource", function($scope, $resource) {
// get the user id
$scope.userid = sessionStorage["cerestiuserid"];
// json we get from server
$scope.apicall = sessionStorage["cerestihome"]; // NEED TO CHANGE API
// grabs the user we want
$scope.userResource = $resource($scope.apicall + "/api/userprofile/",
{Userid:21},
{'get':{method: 'POST'}}
);
// fetch JSON
$scope.userResource.get(function(result) {
// get the name field
$scope.name = result;
sessionStorage["name"] = JSON.stringify(result);
});
and my .html file,
<div ng-controller = "profileController" style="float:left">
<!-- profile pic -->
<div class="pull-left">
<div class="container-fluid">
<div class="profile">
<div class="row">
<div class="center-block">
<div class="profilePic">
<img ng-src="{{profilePic()}}" class="img-responsive">
<!-- name field -->
<label class="caption">
<h4>{{name.name}}</h4>
</label>
</div>
Again, Im not having problems with the Database or API calls. I just want to know how I can get and display the name field of the JSON. Thanks.
strelok2010's comment above should work although that depends on if your result really looks like the one defined at the top of your question.
Your result seems to be a normal javascript object not JSON. (yeah they are different, and that confused me when I learned it.) I assume that because you stringify the result from a javascript object into JSON. Therefore if that is working right your result is either a javascript object or an array of javascript objects. I'm assuming an array. You might want to check though.
I noticed your earlier post had a related problem.
In that one you were asking to access a property of an object that was in an array. In that case it was result as well. Here was the answer from your previous question
var result = [{"name": "Jason"
"date of birth": "february 23, 2985"
....
}];
var firstResultsName = result[0].name;
There are two things I am unsure of due to the inconsistency between this and your last question.
First your name property in your results object is spelled with a capital N here as opposed to a lower case n in your last question.
Keep in mind that capitilization matters in javascript.
Second your result in your last question was an array of objects and in this it seems to be just an object.
So depending on which one it is will determine your solution. So instead of writing every possible solution I'll show you how to determine the solution.
Remember we are dealing with a normal array of javascript objects. I'll try to go into detail so it's extra clear (sorry I heard you were new to web developement, I'm assuming JavaScript too.), but sorry if it's a little too detailed. I will also be breaking it into parts to go deeper into the array of objects that I'll use in my example, but traversing into the data structure can all be done in a single line as I will show.
You can only do actions on the 'outermost-form' (by the way 'outermost-form' is just a term I'll use for clarification it's not really a technical term.) and work your way into the collection (object/array/string)
As an example we have an array of people, with the array being the 'outermost-form'
var people = [
{
"name": "Bob",
"occupation": "Architect",
"date of birth": "01/23/83"
},
{
"name": "Timothy",
"Occupation": "Accountant",
"date of birth": "02/23/78"
}
];
If we saw the value of people at this moment it not surprisingly be.
[
{
"name": "Bob",
"occupation": "Architect",
"date of birth": "01/23/83"
},
{
"name": "Timothy",
"Occupation": "Accountant",
"date of birth": "02/23/78"
}
]
Start with the Array
Since it's an array as the 'outermost-form' we can get one of its values using an index. Just like any other array. Just for a bit of contrast I'll show you how what we are doing is similar to any other array by showing an example of an array by itself
// simple array example
var array = ["foo", "bar", "baz"];
array[0] // returns "foo"
// more simple array example, but less practical (it's more just for showing how javascript can work.)
["foo", "bar", "baz"][2] // returns "baz"
Back to our main example. Let's make a variable person and store our first person in the people array in that value.
var person = people[0];
Now if saw our person variable it would equal the following
{
"name": "Bob",
"occupation": "Architect",
"date of birth": "01/23/83"
}
You can see just like the normal array it grabs the first item in the array. You can see how we are slowly traversing into our people data structure. (that being an array of objects.)
Enter the Object
Okay so now we have the person object, but we want the name of that person so since we are dealing with an object we have to access its properties we can do this with either 'dot notation', e.g. <object>.<property>, or 'bracket notation' which can be done with either a variable or a string for the property name. e.g. <object>.["<property>"] or <object>.[<variable>]
So just as a side example I will show you what it normally takes to get the value of a property of an object just so you can compare and see there's no 'magic' going on. Keep in mind javascript is case-sensitive. Also javascript objects properties can go with or without surrounding quotes unlike JSON. One last thing having a space in the property name forces us to use quotes, and also forces us to access that property via bracket notation.
var result;
var obj = { foo: 1, Bar: 2, "foo bar": 3 };
var randomVarName = "Bar"; // notice the capital B in Bar is important since it was declared that way.
result = obj.foo; // result equals 1
result = obj[randomVarName]; // result equals 2
result = obj["foo bar"]; // result equals 3
Back again to our main train of thought. So we have traversed into our people array to find the person object now let's get their name.
var name = person.name;
The value of name would be.
"Bob"
You can do with that what you wish. You could have also used any of the previous ways to get an objects property including bracket notation.
Do Everything we just did in a Single Line
So to write that all in one line you would just write
people[0].name
Apply to your Question
So to apply to your question if your result looks like this
var result = [
{
"name": "Jason"
"date of birth": "february 23, 2985"
....
}
];
Then you need this to get the name
result[0].name
If it's just this
var result = {
"name": "Jason"
"date of birth": "february 23, 2985"
....
}
Then you just need
result.name
As asked in the comment if you want to get the date of birth property out of the object you need to use bracket notation to get the element out of an object. Bracket notation is one of the two object property accessors the other being dot notation. I covered both at the enter the object section. It can be used at anytime, but is usable in some cases that dot notation does not work.
An example and quote from MDN:
get = object[property_name];
object[property_name] = set;
property_name is a string. The string does not have to be a valid identifier; > it can have any value, e.g. "1foo", "!bar!", or even " " (a space).
So since certain character like spaces can't be used in dot notation bracket notation must be used in those special cases when those characters are present.
Below is the bracket notation of the date of birth.
result["date of birth"]
Like I said before it can be used anywhere, but generally dot notation is preferred for its brevity. So just to show that, we will show the name field being accessed using bracket notation:
result["name"]
One additional reason you may want to use bracket notation is for its ability to use variables like so.
var prop_name = "date of birth";
result[prop_name];
which actually if you understand the principle of that example the MDN example might make more sense.
If you have a question feel free to leave me a comment.

Map Reduce with Relational Databases

I have 2 relational tables
Table A (Person 1, Title of Book Read)
Table B (Book Title, Author Name)
I'm creating a map-reduce job which counts the books by author which are read by every person in table 1.
This means that if there were 2 books by the same author and the person read both, then the map-reduce would yield:
(Person1, Author 1, 2);
My map function (at the Meta-level) is:
map {
emit(TableB.BookTitle, 1)
}
and my reduce function is:
reduce function (title,values)
{
while(values.hasNext())
{
if(title == tableA.bookRead)
sum+=values
}
output.collect(tableA.person1, tableB.author, sum)
}
I know there are some holes to be filled between the person reading the books but I'm not quite sure how to approach it? Also would I have to run this query for every person in the Table B?
We can break the given problem into two jobs:
1) In the first part we should create a map reduce job with two mapper. For First Mapper-A Table A is the input and for second Mapper-B table B is the input. And there will be only one reducer.
Mapper A emits "BooK Title" as Key and "Person Name#Table-A".
Mapper B emits "Book Title" as Key and "Author Name#Table-B"
Since in Map-Reduce records for one key goes to same reducer and in this job we just have one reducer so records will reach over there like
{Book Title,
Then you need to implement logic to extract out Person Name and Author Name. At the reducer end and Reducer will emit its output as:
Book Title %Author Name%PersonName
for eg.
while(values.hasNext())
{
String line = values.next().toString();
String[] det_array = line.split("#");
if(det_array[0].equals("person_book"))
{
person_name = det_array[1];
emit_value = emit_value + person_name + ",";
}
else if(det_array[0].equals("auth_book") && !author_seen)
{
author_name = det_array[1];
emit_value = emit_value + "%" + author_name + "%" + ",";
author_seen = true;
}
}
output.collect(new Text(key),new Text(emit_value));
Then Your Final Output File Will Look Like:
Book Title %Author_Name%Person Name
2) In the Second Map Reduce Job: Code Just One Mapper and Reducer. Input for Your Job is of format:
Book Title %Author_Name%Person Name1,PersonName2 etc..
For Your Mapper Output Key is Author_Name+Person and Value is 1.
As at this stage you have Combination of Author_Name and Person in Reducer you just need to count 1 and emit outout as Person Name, Author Name and Total Count.
Please let me know if this is not clear to you or you would like to see actual java code.
THanks !!