List not updating in .NET - c#

I tried to update a list . I tried the code in debug mode , and the code was executed without any errors. But the value was not updated. Why would this be? I have shared the code below.
foreach (var r in respondents)
{
foreach(var v in completesMap.VendorView)
{
if(v.Value.Contains(r.Status))
{
r.Status=v.Key;
break;
}
}
}
completesMap.VendorView is a key-value pair which I hard-coded in appsettings.json file , respondents is a Dto

I have created an example using your code and it works.
You can see how it works at this link. You can also copy and paste that code to your IDE and debug it & see if it works at your machine also.

Working Code
List<Respondent> respondents = new List<Respondent>()
{
new Respondent { Status = "Active"},
new Respondent { Status = "Active"},
new Respondent { Status = "InActive"},
};
var completesMap = new Map
{
VendorView = new List<VendorView>()
{
new VendorView{ Value = "This is Active" , Key = "Key1" },
new VendorView{ Value = "this is not active", Key = "Key2" }
}
};
foreach (var r in respondents)
{
foreach (var v in completesMap.VendorView)
{
if (v.Value.Contains(r.Status))
{
r.Status = v.Key;
break;
}
}
}
var x = respondents[1].Status;
Debugger Output

Related

Recurly Adding Addon To Subscription Error

I am using the .NET API for Recurly, and I am trying to add an addon to a subscription. Here is my code that I used to create the addon:
var addOnReq = new AddOnCreate()
{
Code = "myCode",
Name = "myName",
DefaultQuantity = 1,
Currencies = new List<AddOnPricing>() {
new AddOnPricing() {
Currency = "USD",
UnitAmount = 100,
UnitAmountDecimal = "100.00"
}
}
};
AddOn addOn = RecurlyClient.CreatePlanAddOn("myPlanId", addOnReq);
And here is the code I am trying to execute when adding the addon to a subscription of the plan in which the addon was added:
var changeReq = new SubscriptionChangeCreate()
{
Timeframe = RecurlyConstants.ChangeTimeframe.Now,
AddOns = new List<SubscriptionAddOnUpdate>() {
new SubscriptionAddOnUpdate() {
Code = "myCode"
}
}
};
foreach (var addOnn in changeReq.AddOns)
{
addOnn.UnitAmount = 100;
}
SubscriptionChange change = RecurlyClient.CreateSubscriptionChange("mySubscriptionId", changeReq);
This is the error I get back in an exception:
Add-ons add on is invalid
What am I doing wrong? Any support is appreciated.
This is a fixed based add on. The recurly documentation is not proving to be helpful, I think.

How can I use begins_with method on sort key using c# in DynamoDB

If I was to use the high level model, I might try something like this:
public async void GetBooksData()
{
GetItemRequest request = new GetItemRequest
{
TableName = "Customer",
Key = new Dictionary<string, AttributeValue>
{
{"UserName", new AttributeValue{S="a"} },
{"BookNum", new AttributeValue { S = starts_with(queryTerm)} }
}
};
try
{
var response = await client.GetItemAsync(request);
if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
{
if (response.Item.Count > 0)
{
foreach (var item in response.Item)
{
MessageBox.Show("Value : \n" + item.Value.S);
}
}
}
}
catch (InternalServerErrorException iee)
{
MessageBox.Show(iee);
}
}
I need to use the method 'begins_with' for getting 2 items what UserName is 'a' and the BookNum are book_1 and book_2. This is possible in the high level interface in Java. As an example as to what can be done on the range key in Java:
public List<Comment> allForItemWithMinRating(String itemId, int minRating) {
Comment comment = new Comment();
comment.setItemId(itemId);
Condition condition = new Condition()
.withComparisonOperator(ComparisonOperator.GE)
.withAttributeValueList(
new AttributeValue()
.withN(Integer.toString(minRating)));
DynamoDBQueryExpression<Comment> queryExpression
= new DynamoDBQueryExpression<Comment>()
.withHashKeyValues(comment)
.withRangeKeyCondition(
"rating",
condition
)
.withScanIndexForward(false);
return mapper.query(Comment.class, queryExpression);
}
In the low level interface for C# you can achieve this as so:
var requestDynamodb = new QueryRequest
{
TableName = "GroupEdEntries",
KeyConditionExpression = "partition_key = :s_Id and begins_with(sort_key, :sort)",
ExpressionAttributeValues = new Dictionary<string, AttributeValue> {
{":s_Id", new AttributeValue { S = my_id }},
{":sort", new AttributeValue { S = sort_key_starts_with }}
},
ConsistentRead = true
};
var results = await client.QueryAsync(requestDynamodb);
where the keys are called partition_key and sort_key. However, this returns the results as attribute values, which then need to be converted into POCOs one property at a time. It requires using reflection and is made more complicated using converters. It seems strange that this fundamental functionality (as well as other functionality) isn't supported in the C# SDK.
I ended up using reflection to create the tables based on the attributes, when this is also supported by default in Java. Am I missing a high level API for C#?
It's a bit of a different syntax and I can't find it documented anywhere (other than in code comments), but this works for me:
string partition_key = "123";
string sort_key_starts_with = "#type"
List<object> queryVal = new List<object>();
queryVal.Add(sort_key_starts_with);
var myQuery = context.QueryAsync<GroupEdEntry>(partition_key, QueryOperator.BeginsWith, queryVal);
var queryResult = await myQuery.GetRemainingAsync();

How to replace multiple values in json file using c#?

I need to replace the Filename and Location in json file with new value if the API number exists in json or else it should add new json array with API,File and location.I have written foreach loop to do it but each time the contents are added to list the if condition takes the new api added and compares to the list so it keeps adding the same api again and again to json file.Plz help me resolve this..
List<DPIndex> items = JsonConvert.DeserializeObject<List<DPIndex>>(json);
foreach (var item in items)
{
foreach (var list in dpIndexList)
{
if (item.API == list.API)
{
item.File = list.File;
item.Location = list.Location;
}
else
{
item.API = list.API;
item.File = list.File;
item.Location = list.Location;
}
}
dpNewIndexList.Add(item);
}
string dpIdxObj = JsonConvert.SerializeObject(dpNewIndexList, Formatting.Indented);
Json file is as below:
[
{
"API": "422833682700000000",
"File": "daf420.dat.07-31-2019",
"Location": 2922
},
{
"API": "422833682700000000",
"File": "daf420.dat.07-31-2019",
"Location": 2922
}
]
Here is a code which will add the item to dpIndexList if an item with such "API" doesn't exist there, or will update the item in that list, if an item with such "API" exists:
foreach (var item in items)
{
// Check if the item with such API already exists in dpIndexList
var foundItem = dpIndexList.FirstOrDefault(dpItem => dpItem.API == item.API);
if (foundItem != null)
{
// Exists. Update the item in dpIndexList
foundItem.File = item.File;
foundItem.Location = item.Location;
}
else
{
// Doesn't exist. Adding to dpIndexList
dpIndexList.Add(item);
}
}
For testing locally I used the following dummy lists, and it worked:
var dpIndexList = new List<DPIndex>()
{
new DPIndex
{
API = "1",
File = "File_1_ORIG",
Location = 1111
},
new DPIndex
{
API = "2",
File = "File_2_ORIG",
Location = 2222
},
};
var items = new List<DPIndex>()
{
// Item, which exists in dpIndexList (should update the original)
new DPIndex
{
API = "2",
File = "File_2_UPDATE",
Location = 3333
},
// New item, which doesn't exist in dpIndexList (should be added)
new DPIndex
{
API = "3",
File = "File_3_NEW",
Location = 3333,
},
// Item, which should UPDATE the one above (should update that one)
new DPIndex
{
API = "3",
File = "File_3_UPDATED",
Location = 3333
},
};
P.S. Don't forget to add using System.Linq; to the top of the file.
After going through your code. It looks like you are getting values form
same object and changing it over and over again
Look at the example below
List<DPIndex> dpIndexList = new List<DPIndex>();
DPIndex index = new DPIndex() {
API = "API.1",
File="API1",
Location="1"
};
dpIndexList.Add(index);
index.API = "API.2";
As you can see I have added the index object in List dpIndexList
but after adding it I changed the value of API in same index object which leads to changed value in dpIndex List also.
You are doing the same thing with item here you are changing its state in each iteration. So in the end all values will become what was the final iteration of the loop
I say you create a object in each iteration and add it to list
And for updation use lambda
foreach (var item in items)
{
foreach (var list in dpIndexList)
{
DPIndex it = new DPIndex();
if (item.API == list.API)
{
it.File = list.File;
it.Location = list.Location;
dpNewIndexList.RemoveAll(x=> x.API == list.API);
}
else
{
it.API = list.API;
it.File = list.File;
it.Location = list.Location;
}
dpNewIndexList.Add(it);
}
}
I beleive this would help you

How to Use NRefactory to Modify C# Code

I am trying to use NRefactory to modify an existing piece of C# code. I have tried to use the method described in this article. I'm getting an exception complaining about duplicate changes. Can someone point out what I am doing wrong, and maybe point me in the right direction?
I have the following section of code:
// contains the source code that needs to be modified
var text = "...";
// is the name of the file in which the target class exists
var fileName = "Foo";
// is the name of the target class
var className = "Foo.cs";
// FormattingOptions and TextEditorOptions are properties available to
// the class containing this code...
var parser = new CSharpParser();
var syntaxTree = parser.Parse(text, fileName);
syntaxTree.Freeze();
var document = new StringBuilderDocument();
document.Text = syntaxTree.ToString(FormattingOptions);
using (var documentScript = new DocumentScript(document, FormattingOptions, TextEditorOptions))
{
var typeDeclarations = syntaxTree.Descendants.OfType<TypeDeclaration>().Where(typeDeclaration => typeDeclaration.Name == className);
var templateProviderDeclaration = typeDeclarations.SingleOrDefault();
if (templateProviderDeclaration != null)
{
var constructorDeclarations = templateProviderDeclaration.Descendants.OfType<ConstructorDeclaration>();
foreach (var constructorDeclaration in constructorDeclarations)
{
var assignmentExpressions = constructorDeclaration.Descendants.OfType<AssignmentExpression>();
foreach (var assignmentExpression in assignmentExpressions)
{
var leftExpression = assignmentExpression.Left;
if (leftExpression != null && leftExpression.ToString(FormattingOptions) == "this.templates")
{
var rightExpression = assignmentExpression.Right;
foreach (var arrayInitializerExpression in rightExpression.Children.OfType<ArrayInitializerExpression>())
{
// uses AddTemplate(), which is an extension method
// which takes in an expression and modifies it, and
// returns an expression
var newExpression = ((ArrayInitializerExpression)arrayInitializerExpression).AddTemplate();
documentScript.Replace(arrayInitializerExpression, newExpression);
}
}
}
}
}
// text retrieved here is *clobbered*, by a few characters
text = documentScript.CurrentDocument.Text;
}
Other Code...
public static class ExtensionMethods
{
public static ArrayInitializerExpression AddTemplate(this ArrayInitializerExpression expression)
{
// TODO : will modify the AST for the target expression
return (ArrayInitializerExpression)expression.Clone();
}
}
Update:
I am trying to change a line like this:
this.templates = new Dictionary<string, ITemplate>
{
{ "Foo", new FooTemplate() }
};
to:
this.templates = new Dictionary<string, ITemplate>
{
{ "Foo", new FooTemplate() },
{ "Bar", new BarTemplate() }
};
For the purposes of this question, the exact specifics of the change I am trying to make aren't important though. I suspect that I have something not constructed quite correctly, but I cannot figure out if that's the issue.

LINQ EF copy and paste a record with a difference field

i need copy and paste some records of my table with just but change one field.
here is my code:
using (ClearWhiteDBEntities cwContext = new ClearWhiteDBEntities())
{
var qlstfld = from lstflds in cwContext.tblListFields
where lstflds.listId == theLongSrc
select lstflds;
foreach (var item in qlstfld)
{
tblListField lstFldRow = new tblListField
{
name = item.name,
filterFieldId = item.filterFieldId,
listId = theLongDes, //this field must be change in paste
continueById = item.continueById,
destinationId = item.destinationId,
conditionId = item.conditionId,
userId = userId,
date = Convert.ToDateTime(DateTime.Now.ToShortDateString()),
time = DateTime.Now.TimeOfDay,
IP = trueIp
};
cwContext.AddTotblListFields(lstFldRow);
cwContext.SaveChanges();
}
}
but i get this error:
an error accured white starting a transaction on the provider connection. see the inner exception for details.
what is best solution to copy and paste records but change one field?
If you are using change tracking:
using (ClearWhiteDBEntities cwContext = new ClearWhiteDBEntities())
{
var qlstfld = from lstflds in cwContext.tblListFields
where lstflds.listId == theLongSrc
select lstflds;
foreach (var item in qlstfld)
{
cwContext.ObjectStateManager.ChangeObjectState(item, System.Data.EntityState.Added);
item.Id = 0;
item.listId = theLongDes; //this field must be change in paste
}
cwContext.SaveChanges();
}

Categories

Resources