Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I has to use a construct like
string json = await SendGraphGetRequest("/users", null);
var jsonObj = JObject.Parse(json);
var values = (JArray)jsonObj["value"];
foreach (var value in values)
List<Users> Users = new List<Models.Users>()
{
foreach (var value in values)
{
};
};
How i have to correct the syntax?
I want to bring values from the json Obj in to the list.
Let's try to break down what you're trying to do into 3 simple steps. First you need to create a List data structure to store your users. Then you'll need to add some users to your empty list. Then finally you can enumerate your list with a for-each loop:
// First create a list of your users.
List<Model.Users> users = new List<Models.Users>();
// Add some users to the list.
users.Add(new Model.Users())
...
...
...
// Now you can loop through the list
foreach (var user in users)
{
// do something with the current user
user.DoSomething();
};
Hope this helps!
You can rewrites it with Linq
List<Users> Users = values.Select(value => new Models.Users( ... )).ToList();
Instead ... or new Models.Users( ... ) you can use your logic
Is each value in values a Users object?
If so,
List<Users> Users = new List<Models.Users>(values);
The List<Users> is initialized with the items in the values collection.
Or, perhaps each value contains some properties that you would use to construct your object:
var Users = new List<Models.Users>();
foreach (var value in values)
{
var newUser = new Users();
//Just making these up.
newUser.Name = value.Name;
newUser.Id = value.UserId;
Users.Add(newUser);
}
var Users = new List<Models.Users>();
foreach (var value in values)
{
var newUser = new Users();
//Just making these up.
newUser.Name = value.Name;
newUser.Id = value.UserId;
Users.Add(newUser);
}
The rest of these examples do the exact same thing - they're just shorthand.
var Users = new List<Models.Users>();
foreach (var value in values)
{
Users.Add(new Users{Name=value.Name, Id=value.UserId});
}
This is using Linq. It does the exact same thing as above. We use it primarily because it looks cool, but the syntax is different until you get used to it.
var Users = new List<Models.Users>(values.Select(
value=>new Users{Name=value.Name, Id=value.UserId}));
It's doing this:
var Users = new List<Models.Users>([some set of Users to initialize the collection]);
and this is the set of users being used to to initialize the collection:
values.Select(value=>new Users{Name=value.Name, Id=value.UserId})
In other words, for each item in values select (create) a new Users object.
Related
I have one list and in that list I am adding values based on class. See below for details.
result.ContactList = contactsResult.Item2.Select(x => new PrjContact() {
Id = x.ID,
UserId = x.UserId,
Name = xName,
Email = x.Email,
}).ToList();
Now I need to call one more API and pass this UserId in that API and get phone number for that user.
Then need to add that phone number in above list in result.ContactList.
I have tried in this way.
foreach (var user in contactsResult.Item2)
{
UserInfo = API.GetUserDetail(user.UserId);
result.ContactList.Select(x => new ProjectContactView()
{
Phone = UserInfo.PhoneNumber
});
}
But this is not working.
This doesn't do anything:
result.ContactList.Select(x => new ProjectContactView()
{
Phone = UserInfo.PhoneNumber
});
Sure, it iterates over result.ContactList and projects it into a new collection. But (1) you don't do anything with that collection and (2) it overwrites every object in that collection with an entirely new object that has only one property set.
For starters, if you want to modify result.ContactList then iterate over that:
foreach (var user in result.ContactList)
{
}
Then if the goal here is to use a property on user to fetch data and update user then just update user:
foreach (var user in result.ContactList)
{
var userInfo = API.GetUserDetail(user.UserId);
user.Phone = userInfo.PhoneNumber
}
I am trying to add an item to DynamoDB only if it doesn't exist already. I have tried the below code and doesn't look like the query filter is being applied for SaveAsync. I don't get an exception even when an item with the primary key (CommentId, CommentType) already exists.
public Task Add(Comment comment)
{
var config = new DynamoDBOperationConfig();
var partitionKeyCondition = new ScanCondition("CommentId", ScanOperator.NotEqual, 1);
var rangeKeyCondition = new ScanCondition("CommentType", ScanOperator.NotEqual, "UserComment");
config.QueryFilter.Add(partitionKeyCondition);
config.QueryFilter.Add(rangeKeyCondition);
return DynamoDBContext.SaveChangesAsync(comment, config);
}
You'll want to do a Conditional Put: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html#Expressions.ConditionExpressions.PreventingOverwrites
Here's a basic example:
var client = new AmazonDynamoDBClient();
Client.PutItem(new PutItemRequest
{
Item = new Dictionary<string, AttributeValue>
{
{"Id", new AttributeValue("Item-unique-id")},
{"Vale", new AttributeValue("Hello World")},
},
// cause put to fail if there is already an item with the same key
ConditionExpression = "attribute_not_exists(Id)"
});
There's more details in this question: Is it possible to do a conditional put or update in DynamoDB?
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
This is my controller:
string responseString = reader.ReadToEnd();
dynamic jsonData = JsonConvert.DeserializeObject(responseString);
var results = new List<Result>();
foreach (var item in jsonData.items)
{
results.Add(new Result {
Title = item.title,
Link = item.link,
Snippet = item.snippet,
});
db.Results.AddRange(results);
db.SaveChanges();
}
return View(results.ToList());
But I get this error:
Violation of PRIMARY KEY constraint 'PK_Result'. Cannot insert duplicate key in object 'dbo.Result'. The duplicate key value is (0).
The statement has been terminated.
How can I solve that?
var results = new List<Result>();
foreach (var item in jsonData.items)
{
results.Add(new Result {
Title = item.title,
Link = item.link,
Snippet = item.snippet,
});
db.Results.AddRange(results);
db.SaveChanges();
}
On the first line you have initialized new List.
Then on each enumeration of jsonData.items:
you add new instance of Result type to results list.
you add the whole collection to db.Results DbSet. Because of db.Results.AddRange.
I think that you wanted to have something like this:
var results = new List<Result>();
foreach (var item in jsonData.items)
{
var result = new Result {
Title = item.title,
Link = item.link,
Snippet = item.snippet,
};
db.Results.Add(result);
}
db.SaveChanges();
May be you should include primary key value in results.Add() method.
Here you are trying to add values for title, link and snippet.
I believe none of them is primary key.
That's why it takes default value(0) for primary key.
You can check primary key field in your database table and include that as well in results.Add() method.
Here's what I'm trying to do:
Create a list with some values from mysql.
Search this list with a variable ( I named it Existed )
If Existed contains a specific string, then do some actions.
Here's a sample of my list data:
List ( name users )
Facebook
Google
Yahoo
Strongman
Zombies
Stratovarius
If Existed inside users contains Strong, then perform some action.
My code so far is below. The problem is that it never enters the action and for some reason I believe it does not see "Strong" right.
List<string> users = dbm.FindManagers();
foreach (var Existed in users)
{
if (Existed.Contains(rName_Add_User_result))
{
dbm.AddSubuser(Existed, rName_result);
}
}
Can't reproduce. This works for me:
var rName_Add_User_result = " Strong ";
//List<string> users = dbm.FindManagers();
var users = new List<string>() {"Facebook", "Google", "Yahoo", "Strongman", "Zombies", "Stratovarius"};
foreach (var Existed in users.Where(u => u.ToUpper().Contains(rName_Add_User_result.ToUpper().Trim()))
{
//dbm.AddSubuser(Existed, rName_result);
Console.WriteLine(Existed);
}
Result:
Strongman
Not sure but could be because of case sensitivity. Try converting it to lower and then compare
if (Existed.ToLower().Contains(rName_Add_User_result))
{
dbm.AddSubuser(Existed, rName_result);
}
In our company we created a custom Issues app. Additionally to using this app in the web interface, we also want to be able to change the state of an issue (new, acknowledged, test, resolved, ...) automatically via git commit hooks. The basics are working fine (ie change state, add notes, ...), but we also want to change the responsibility for the current item to a specific user. In that special case, it's the creator if this item.
My first try was the following:
var appid = 1234; var itemid = 1;
var item = podio.ItemService.GetItemByAppItemId(appid, itemid);
var update = new Item {ItemId = item.ItemId};
var creator = item.CreatedBy.Id;
var resp = update.Field<ContactItemField>("responsibility");
resp.ContactIds = new List<int>{creator.Value};
//change some other fields as well
podio.ItemService.UpdateItem(update);
This throws an "Object not found" exception, because in the resp.ContactIds one must not set the UserId but the ProfileId.
I then tried to get the ProfileId of the item-creator via
podio.ContactService.GetUserContactField(creator.Value, "profile_id");
but this also throws an exception "(Authentication as app is not allowed for this method").
So how can I get an appropriate profile id for the user when I use authentication as app?
OK, I found a workaround for it, not sure, if this is possible for other scenarios, but it works for the current case.
Instead of using the C# interface for setting the ContactIds for the ContactItemField, I set the json values directly.
var appid = 1234; var itemid = 1;
var item = podio.ItemService.GetItemByAppItemId(appid, itemid);
var update = new Item {ItemId = item.ItemId};
var creator = item.CreatedBy.Id;
var resp = update.Field<ContactItemField>("responsibility");
resp.ContactIds = new List<int>(); // set to an empty list, so that resp.Values is initialized to an empty JArray
var u = new JObject { {"value", new JObject { {"type" , "user" }, {"id", creator } } } };
responsibleField.Values.Add(u); //add the new user to the Values of the field
//change some other fields as well
podio.ItemService.UpdateItem(update);
And if I set the value with type user I can use the known userid and the API on the server takes care of the lookup.