I'm trying to put some objects in a mutableListOf, but all of them ended up overriding.
class Users {...}
class dbUsers{
var users = Users()
val list = mutableListOf(users)
fun addUser(phone: Int, name: String){
users.phone = phone
users.name = name
list.add(users)
}
}
fun main() {
var dbAccess = dbUsers()
dbAccess.addUser(8439, "Thiago")
dbAccess.addUser(12312, "Maria")
println(dbAccess.list[0].name)
println(dbAccess.list[1].name)
}
When We print at position 1, we see that was override
You have initialized Users object only once, at the class level in dbUsers. You need to create new object everytime before adding the user to the list. Move the users initialization within the method instead
class dbUsers{
val list = mutableListOf<Users>()
fun addUser(phone: Int, name: String){
var users = Users()
users.phone = phone
users.name = name
list.add(users)
}
}
It looks like the list is referencing from users and since users itself is updated every time, you get this results.
There are two ways you can approach this issue ,
Creating a new user every-time calling addUser , this is easy
If you have other data in Users than name and phone , you can just make a DeepCopy of your object by add in a new function in your class copy() like
class YourClass () {
// Your class other stuffs here
fun copy(): YourClass { //Get another instance of YourClass with the values like this!
val json = Gson().toJson(this)
return Gson().fromJson(json, YourClass::class.java)
}
}
then by using yourClassObject.copy() you will get a new instance with same values
fun addUser(phone: Int, name: String){
val newUsers = users.copy()
newUsers.phone = phone
newUsers.name = name
list.add(newUsers)
}
Related
I've added a custom method called customMethod to a model, like so:
class Prize extends Model {
customMethod(){
return 'test'
}
}
When I use find to get a prize by primary key I can call this method no problem
const prize = await Prize.find(1);
return prize.customMethod();
//returns 'test'
but when if I get a prize any other way, through a relationship or by querying by a field, I can't access this method.
const countrysPrizes = await country.prizes().fetch();
for (const key in countrysPrizes) {
if (countrysPrizes.hasOwnProperty(key)) {
const prize = countrysPrizes[key];
return prize.customMethod();
//returns 500 - prize.customMethod is not a function
}
}
How can I access this method while iterating through multiple of the object?
You need to use <fetched_object>.rows because of VanillaSerializer
Example code :
const user = await User.find(1);
const posts = await user.posts().fetch();
posts.rows.forEach(post=> { // use .rows
console.info(post.customMethod()); // Your custom method
});
I've had trouble using the basic foreach loop. So I used .foreach()
An output example with fetch() :
In my use case, I have a student enrolling to a specific program which in turn creates a student state on the ledger.
Now, if the same student enrolls with same credentials again, I want to avoid it and throw some exception or message.
One solution, I can think of is, I can query the vault before creating the student state and if that student is not found in the ledger than only he is allowed to enroll.
But, this seems like a vague idea.
Can someone provide a better approach or some other way I am not aware of?
You should implement schema for your state as in this example:
class CashState(
val owner: AbstractParty,
val pennies: Long) : ContractState, QueryableState {
override val participants get() = listOf(owner)
override fun generateMappedObject(schema: MappedSchema): PersistentState {
return when (schema) {
is CashSchemaV1 -> CashSchemaV1.PersistentCashState(
this.owner,
this.pennies
)
else -> throw IllegalArgumentException("Unrecognised schema $schema")
}
}
override fun supportedSchemas(): Iterable<MappedSchema> = listOf(CashSchemaV1)
}
The schema itself:
object CashSchema
#CordaSerializable
object CashSchemaV1 : MappedSchema(schemaFamily = CashSchema.javaClass, version = 1, mappedTypes = listOf(PersistentCashState::class.java)) {
#Entity
#Table(name = "contract_cash_states")
class PersistentCashState(
#Column(name = "owner_name", unique=true, nullable = true)
var owner: AbstractParty?,
#Column(name = "pennies", nullable = false)
var pennies: Long
) : PersistentState()
}
The key point is to make the columns unique, so when you add duplicate value the exception is thrown.
docs
I am using Dynamodb.net in my application.
I have the following code.
var creds = new BasicAWSCredentials(awsId, awsPassword);
var dynamoClient = new AmazonDynamoDBClient(creds,
awsDynamoDbRegion);
var context = new DynamoDBContext(dynamoClient);
List<ScanCondition> conditions = new List<ScanCondition>();
conditions.Add(new ScanCondition("Id", ScanOperator.Equal, myId));
var response = await context.ScanAsync<Data>(conditions).GetRemainingAsync();
return response;
My Data Model is as:
[DynamoDBTable("MyTable")]
public class Data
{
[DynamoDBHashKey]
public string Id{ get; set; }
public string Name { get; set; }
}
We are harcoding the table table name in our model "Data" as
[DynamoDBTable("MyTable")]
How can we not hardcode this. Is it possible to apply the table name in my actual code itself instead of giving in the model?
Thanks
Is OverrideTableName in DynamoDBOperationConfig what you are looking for ?
Description:
Property that indicates the table to save an object to overriding the
DynamoDBTable attribute declared for the type.
Example:
var x = await DbContext.LoadAsync<T>("hash", new DynamoDBOperationConfig {
OverrideTableName = "NewTableName",
IndexName = indexName
});
Also what you are looking for might be table prefix for every request of DbContext. It will append this prefix to every table. Useful if you want to isolate application specific tables like AppName-MyTable...
Example:
return new DynamoDBContextConfig
{
TableNamePrefix = "MyAppIdentifier",
ConsistentRead = false,
};
another option is to use different prefixes for the tables via
Amazon.DynamoDBv2.DataModel.DynamoDBContextConfig.TableNamePrefix
Property that directs DynamoDBContext to prefix all table names with a specific string. > If property is null or empty, no prefix is used and default table names are used.
https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/DynamoDBv2/TDynamoDBContextConfig.html
e.g.:
var credentials = new StoredProfileAWSCredentials("default");
var client = new AmazonDynamoDBClient(credentials, RegionEndpoint.USEast1);
var config = new DynamoDBContextConfig{
TableNamePrefix = "Test."
};
var ctx = new DynamoDBContext(client, config);
await ctx.SaveAsync(item);
If I have a model type defined like this:
App.Model = DS.Model.extend({});
How could I construct the type from a string like 'model';
I dwant to be to be generic about using the store, instead of having to be specific like this:
App.store.load(App.model, obj);
If I understand you correctly, you can solve your issue using Ember.getPath, see http://jsfiddle.net/pangratz666/SGsU7/:
App.Model = Ember.Object.extend();
var capitalize = function(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
var string = 'model';
var capitalizedString = capitalized(string); // Model
var type = Ember.getPath(App, capitalizedString);
console.log(type === App.Model); // true
I'm trying to reproduce the Activities page in Microsoft CRM 4.0 via web services. I can retrieve a list of activities, and I believe I need to use ActivityPointers to retrieve the entities but have so far been unsuccessful. Would I need to loop through every single entity returned from the first query to retrieve the ActivityPointer for it? And if so, how would I then get the "Regarding" field or Subject of the activity (eg: email).
The code to retrieve the activities is:
var svc = GetCrmService();
var cols = new ColumnSet();
cols.Attributes = new[] { "activityid", "addressused", "scheduledstart", "scheduledend", "partyid", "activitypartyid", "participationtypemask", "ownerid" };
var query = new QueryExpression();
query.EntityName = EntityName.activityparty.ToString();
query.ColumnSet = cols;
LinkEntity link = new LinkEntity();
//link.LinkCriteria = filter;
link.LinkFromEntityName = EntityName.activitypointer.ToString();
link.LinkFromAttributeName = "activityid";
link.LinkToEntityName = EntityName.activityparty.ToString();
link.LinkToAttributeName = "activityid";
query.LinkEntities = new[] {link};
var activities = svc.RetrieveMultiple(query);
var entities = new List<ICWebServices.activityparty>();
RetrieveMultipleResponse retrieved = (RetrieveMultipleResponse) svc.Execute(request);
//var pointers = new List<activitypointer>();
foreach (activityparty c in activities.BusinessEntities)
{
entities.Add(((activityparty)c));
//the entities don't seem to contain a link to the email which they came from
}
Not sure if I understand your problem, but the field "activityid" in the activitypointer object is the same activityid as the underlying activity (email, task, phonecall, etc). The regardingobjectid is the link to the regarding entity.
Heres what you need to get the equivalent of the Activities page
ColumnSet cols = new ColumnSet()
{
Attributes = new string[] { "subject", "regardingobjectid", "regardingobjectidname", "regardingobjectidtypecode", "activitytypecodename", "createdon", "scheduledstart", "scheduledend" }
};
ConditionExpression condition = new ConditionExpression()
{
AttributeName = "ownerid",
Operator = ConditionOperator.Equal,
Values = new object[] { CurrentUser.systemuserid.Value } //CurrentUser is an systemuser object that represents the current user (WhoAmIRequest)
};
FilterExpression filter = new FilterExpression()
{
Conditions = new ConditionExpression[] { condition },
FilterOperator = LogicalOperator.And
};
QueryExpression query = new QueryExpression()
{
EntityName = EntityName.activitypointer.ToString(),
ColumnSet = cols,
Criteria = filter
};
BusinessEntityCollection activities = svc.RetrieveMultiple(query);
foreach (activitypointer activity in activities)
{
//do something with the activity
//or get the email object
email originalEmail = (email)svc.Retrieve(EntityName.email.ToString(), activity.activityid.Value, new AllColumns());
}