Cosmos DB pre trigger how to fetch value from another row - c#

In Cosmos DB I have trigger, this is pretrigger. Method for this trigger looks like this:
function CalculateFields(){
var context = getContext();
var request = context.getRequest();
// this is the current request
var itemToCreate = request.getBody();
if(itemToCreate["fileType"] == "DivisionConfig")
{
itemToCreate["column1"] = 2 * item1["column3"];
}
and I want to fetch value from another row, selected by id. itemToCreate is current item, how to get item for id = 1?
Can I do that in this method, or rather I have to pass variable in C# code when I call this trigger:
using (CosmosClient client = new CosmosClient(Endpoint, Key))
{
var container = client.GetContainer(DatabaseId, CollectionId);
ItemResponse<T> response2 = await container.CreateItemAsync(item, new PartitionKey("Mypk"), new ItemRequestOptions { PreTriggers = new List<string> { "CalculateFields" } });
return response2;
}
item1["column3"] is another row from the same collection.

Pre-triggers can only operate on the item itself and cannot accept parameters. I'm not clear on exactly what you're trying to do here but maybe look at using a Post-Trigger instead.

Related

How to see DynamoDB table name in C#?

I can't see the name of the tables already created. I'm working on a project in which I have access to the DynamoDB database through an IAM client, I create the AmazonClient using the credentials and configs that were made available to me, but I can't see the tables already created in the database.
I have already created the client and connected it to the database, I am trying to see the number of tables as follows, but the result is always 0
new code
List<string> currentTables = client.ListTablesAsync().Result.TableNames;
MessageBox.Show(currentTables.Count.ToString());
Try awaiting the API call:
List<string> currentTables = await client.ListTablesAsync().Result.TableNames;
MessageBox.Show(currentTables.Count.ToString());
Try this sync code instead:
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
// Initial value for the first page of table names.
string lastEvaluatedTableName = null;
do
{
// Create a request object to specify optional parameters.
var request = new ListTablesRequest
{
Limit = 10, // Page size.
ExclusiveStartTableName = lastEvaluatedTableName
};
var response = client.ListTables(request);
ListTablesResult result = response.ListTablesResult;
foreach (string name in result.TableNames)
Console.WriteLine(name);
lastEvaluatedTableName = result.LastEvaluatedTableName;
} while (lastEvaluatedTableName != null);

Trying to create a If else statement using String.IsNullOrEmpty(String) to filter out rogue record

I am importing an old database into a new one. The new database requires each record to have a type when imported. The first record does not have a type, therefore I would like to discard it from the import. I am unsure how to write this in C#
At the moment I have
`public async Task RunImport()
` {
_logger.LogInformation(DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss") + " | BATHWORKS IMPORT : Start Import");
//BATHWORKS COMPONENT
string type = null;
IEnumerable<BathworksItem> bathworksItem = await GetBathworksItem();
IEnumerable<BathworksItemDto> BathworksItem = await GetBathworksPortalItems();
IEnumerable<BathworksItem> missingBathworksPortalItems = bathworksItems.Where(x => !bathworksportalItem.Any(y => y.Serial == x.Name));
foreach (BathworksItem missingBathworksPortalItem in bathworksItems)
if (!missingBathworksPortalItem.IsNullOrEmpty(type))
{
BathworksItemDto bathworksItemDto = new BathworksItemDto();
bathworksItemDto.ItemNumber = missingBathworksPortalItem.ItemNumber;
bathworksItemDto.Stock = missingBathworksPortalItem.Stock;
bathworksItemDto.Availbility = missingBathworksPortalItem.Availbility;
bathworksItemDto.Company = missingBathworksPortalItem.Company;
bathworksItemDto.Lastupdate = missingBathworksPortalItem.Lastupdate;
bathworksItemDto.Type = missingBathworksPortalItem.Type;
bathworksItemDto.Name = missingBathworksPortalItem.Name;
await _bathworksItem.InsertItem(bathworksItemDto);
}`
I have tried the above and it does not quite do what I was expecting as it does not discard the rogue record, instead I recieve a error 500.

How to update multiple rows in SQL server in one go without using temp table?

My application has one object called Client. Client have a property called status. I want to update the status of multiple clients based on user input.
Code:
public async Task UpdateStatus(List<ClientModel> clients, string modifyUserId)
{
var clientsToUpdate = clients.Select(x => new ClientViewModel { Id = x.Id, Status = x.StatusCd, ModifyDt = DateTime.UtcNow, MdfyUserId = modifyUserId != null ? modifyUserId : string.Empty});
var parameters = new List<IDbDataParameter>();
foreach (var client in clientsToUpdate)
{
parameters.Add(dbManager.CreateParameter("#ClientId", 4, client.Id, DbType.Int32, ParameterDirection.InputOutput));
parameters.Add(dbManager.CreateParameter("#ModifyDt", client.ModifyDt, DbType.DateTime));
parameters.Add(dbManager.CreateParameter("#ModifyUserId", client.MdfyUserId, DbType.Int32));
await dbManager.ExecuteNonQuery(Constants.StoredProcedures.UpdateClientStatus, CommandType.StoredProcedure, parameters.ToArray());
parameters.Clear();
}
}
Here in above code, call is going to database for every client which I want to improve.
Is there any way to update multiple clients status in one go?

How to efficiently edit data in a database?

The method is supposed to receive data from a server, check if new tokens have been added, and if there are, add them to the database. If the token already exists, update its status but don't add a new row in the table. This is the code I've written so far.
IEnumerable<Token> serverTokens = JsonConvert.DeserializeObject<IEnumerable<Token>>
(server.GetTokens().Content);
IEnumerable<Token> dbTokens = _tokenService.GetAllTokens();
foreach (var token in serverTokens)
{
var dbToken = dbTokens.Where(x => x.Symbol == token.Symbol).FirstOrDefault();
if (dbToken != null)
{
Token editedToken = dbToken;
editedToken.UpdatedOn = DateTime.Now;
editedToken.Active = token.Active;
_tokenService.AddToken(editedToken);
}
else
{
token.UpdatedOn = DateTime.Now;
_tokenService.AddToken(token);
}
}
dbContext.SaveChanges();
The AddToken method is just a simple AddOrUpdate operation.
public void AddToken(Token token)
{
_dbContext.Tokens.AddOrUpdate(token);
//_dbContext.SaveChanges();
}
Now, this code does what it's supposed to, however it's extremely slow. How would I go about optimizing it?
dbTokens.Where(x => x.Symbol == token.Symbol) is IEnumerable
So he will load it each time you call it on the loop.
Store in in a list before the loop
List<Token> dbTokens = _tokenService.GetAllTokens().ToList()

Parse.com - if key exists, update

Currently, I'm sending some data to Parse.com. All works well, however, I would like to add a row if it's a new user or update the current table if it's an old user.
So what I need to do is check if the current Facebook ID (the key I'm using) shows up anywhere in the fbid column, then update it if case may be.
How can I check if the key exists in the column?
Also, I'm using C#/Unity.
static void sendToParse()
{
ParseObject currentUser = new ParseObject("Game");
currentUser["name"] = fbname;
currentUser["email"] = fbemail;
currentUser["fbid"] = FB.UserId;
Task saveTask = currentUser.SaveAsync();
Debug.LogError("Sent to Parse");
}
Okay, I figured it out.
First, I check which if there is any Facebook ID in the table that matches the current ID, then get the number of matches.
public static void getObjectID()
{
var query = ParseObject.GetQuery("IdealStunts")
.WhereEqualTo("fbid", FB.UserId);
query.FirstAsync().ContinueWith(t =>
{
ParseObject obj = t.Result;
objectID = obj.ObjectId;
Debug.LogError(objectID);
});
}
If there is any key matching the current Facebook ID, don't do anything. If there aren't, just add a new user.
public static void sendToParse()
{
if (count != 0)
{
Debug.LogError("Already exists");
}
else
{
ParseObject currentUser = new ParseObject("IdealStunts");
currentUser["name"] = fbname;
currentUser["email"] = fbemail;
currentUser["fbid"] = FB.UserId;
Task saveTask = currentUser.SaveAsync();
Debug.LogError("New User");
}
}
You will have to do a StartCoroutine for sendToParse, so getObjectID has time to look through the table.
It may be a crappy implementation, but it works.
What you need to do is create a query for the fbid. If the query returns an object, you update it. If not, you create a new.
I'm not proficient with C#, but here is an example in Objective-C:
PFQuery *query = [PFQuery queryWithClassName:#"Yourclass]; // Name of your class in Parse
query.cachePolicy = kPFCachePolicyNetworkOnly;
[query whereKey:#"fbid" equalTo:theFBid]; // Variable containing the fb id
NSArray *users = [query findObjects];
self.currentFacebookUser = [users lastObject]; // Array should contain only 1 object
if (self.currentFacebookUser) { // Might have to test for NULL, but probably not
// Update the object and save it
} else {
// Create a new object
}

Categories

Resources