_userManager.ReplaceClaimAsync error Id = 414, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}" - asp.net-core

In my controller asp.net core 6.0 I got this error when execute ReplaceClaimAsync:
Id = 414, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"
var user11 = _userManager.FindByIdAsync(User.Id).Result;
user11.Email = user.Email;
var Result = _userManager.UpdateAsync(user11).Result;
if (!Result.Succeeded)
{
ModelState.AddModelError(Result.Errors.First().Code, Result.Errors.First().Description);
//throw new Exception(result.Errors.First().Description);
return BadRequest(ModelState);
}
var claimsOriginaux = _userManager.GetClaimsAsync(user11);
var claimOld = claimsOriginaux.Result.FirstOrDefault(r => r.Type == JwtClaimTypes.GivenName);
var claimNew = new Claim(JwtClaimTypes.GivenName, User.GivenName);
if (claimNew.Value != claimOld.Value)
{
var temp = _userManager.ReplaceClaimAsync(user11, claimOld, claimNew);
}
return NoContent(); //success
Any clue?

You are calling a bunch of async methods, and you are not using them the way you should.
You should await all async methods, instead of calling the .Result property.

Using await
var user11 = await _userManager.FindByIdAsync(User.Id);
user11.Email = user.Email;
var Result = await _userManager.UpdateAsync(user11);
if (!Result.Succeeded)
{
ModelState.AddModelError(Result.Errors.First().Code, Result.Errors.First().Description);
//throw new Exception(result.Errors.First().Description);
return BadRequest(ModelState);
}
var claimsOriginaux = await _userManager.GetClaimsAsync(user11);
var claimOld = claimsOriginaux.Result.FirstOrDefault(r => r.Type == JwtClaimTypes.GivenName);
var claimNew = new Claim(JwtClaimTypes.GivenName, User.GivenName);
if (claimNew.Value != claimOld.Value)
{
var temp = await _userManager.ReplaceClaimAsync(user11, claimOld, claimNew);
}
return NoContent(); //success
or
Using GetAwaiter()
var user11 = _userManager.FindByIdAsync(User.Id).GetAwaiter().GetResult();
user11.Email = user.Email;
var Result = _userManager.UpdateAsync(user11).GetAwaiter().GetResult();
if (!Result.Succeeded)
{
ModelState.AddModelError(Result.Errors.First().Code, Result.Errors.First().Description);
//throw new Exception(result.Errors.First().Description);
return BadRequest(ModelState);
}
var claimsOriginaux = _userManager.GetClaimsAsync(user11).GetAwaiter().GetResult();
var claimOld = claimsOriginaux.Result.FirstOrDefault(r => r.Type == JwtClaimTypes.GivenName);
var claimNew = new Claim(JwtClaimTypes.GivenName, User.GivenName);
if (claimNew.Value != claimOld.Value)
{
var temp = _userManager.ReplaceClaimAsync(user11, claimOld, claimNew).GetAwaiter().GetResult();
}
return NoContent(); //success

Related

Why is hangfire triggering multiple times

I configured hangfire to run 2 cron jobs. In the recurring jobs tab I can see the jobs and the next run time is correct but I have received over 15 emails that are triggered by the function hangfire is calling and I can't see the history of those calls on the succeeded jobs tab on hangfire. I want the function to be called once everyday. PS: there is just one server showing on hangfire
```recurringJobManager.AddOrUpdate("RecurringDeposits", () => serviceProvider.GetService<IRecurringDeposits>().AutomatedDepositsAsync(), Cron.Daily(8, 0));
recurringJobManager.AddOrUpdate("RecurringWithdrawals", () => serviceProvider.GetService<IRecurringWithdrawals>().AutomatedWithdrawalsAsync(), ```
the function
```public async Task AutomatedDepositsAsync()
{
var coreAccounts = await _dbContext.CustomerAccounts
.Include(x => x.Customer)
.Where(x => x.IsActive
&& (x.Product.Code == coreAccountCode || x.Product.Code == privateGroupCode || x.Product.Code == publicGroupCode || x.Product.Code == myPurseAccountCode)
&& x.RecurringCredit && x.CreditInterval != 0 && x.PlanEndDate == null)
.ToListAsync();
if(coreAccounts != null)
{
foreach (var acct in coreAccounts)
{
var firstTran = await _dbContext.xxx
.Where(x => x.IsApproved
&& x.Channel == "Card" && x.AccountId == xx.Id)
.OrderBy(x => x.IsApprovedDate)
.FirstOrDefaultAsync();
var card = _dbContext.CustomerCards
.Where(x => x.UserId == acct.Customer.Id && x.IsDeleted == false)
.OrderBy(x => x.CreationTime)
.LastOrDefault();
if (card==null)
{
continue;
}
if (acct.CreditInterval == 1 && DateTime.UtcNow.Date > firstTran.IsApprovedDate)
{
await DebitCustomerCard(firstTran, acct.Customer.Email, acct, card);
}
else if (acct.CreditInterval == 7)
{
var firstDepositDate = firstTran.IsApprovedDate;
var firstDepositDay = firstDepositDate.Value.DayOfWeek;
var Today = DateTime.UtcNow.DayOfWeek;
if(DateTime.UtcNow.Date > firstDepositDate && firstDepositDay == Today)
{
await DebitCustomerCard(firstTran, acct.Customer.Email, acct, card);
}
}
else if (acct.CreditInterval == 30)
{
var firstDepositDate = firstTran.IsApprovedDate;
var firstDepositDay = firstDepositDate.Value.Day;
var currentMonth = DateTime.UtcNow.Month;
var currentyear = DateTime.UtcNow.Year;
CultureInfo provider = CultureInfo.InvariantCulture;
var NextDepositDate = DateTime.ParseExact(firstDepositDay + "/" + currentMonth + "/" + currentyear, "dd/MM/yyyy", provider);
if(DateTime.UtcNow.Date > firstDepositDate && DateTime.UtcNow.Date == NextDepositDate.Date)
{
await DebitCustomerCard(firstTran, acct.Customer.Email, acct, card);
}
}
}
}
}
public async Task DebitCustomerCard(CustomerContribution firstTransaction, string custEmail, CustomerAccount custAcct, CustomerCard Card)
{
var contribution = await _dbContext.Contributions.AddAsync(new CustomerContribution
{
Account = firstTransaction.Account,
Amount = firstTransaction.Amount,
Tenor = firstTransaction.Tenor,
Rate = firstTransaction.Rate,
ExpectedReturn = firstTransaction.ExpectedReturn,
ChannelCode = Card.AuthCode,
Channel = "Card",
});
await _dbContext.SaveChangesAsync();
if (contribution == null)
{
//do something
return;
}
var reference = $"CRD-{DateTime.UtcNow:yyyyMMddHHmmssffff}{Utils.GenerateRandomString(4)}";
var transactionLog = new TransactionLog
{
Account = firstTransaction.Account,
Amount = firstTransaction.Amount,
TransactionDate = DateTime.UtcNow,
Type = TransactionType.SingleDebit,
Reference = reference,
Narration = "Automatic Deposit"
};
await _dbContext.TransactionLogs.AddAsync(transactionLog);
await _dbContext.SaveChangesAsync();
var postingResponse = await _postingService
.ChargeCustomerAccount(new xxxxx.ChargeCustomerRequest
{
Amount = firstTransaction.Amount,
AuthCode = Card.AuthCode,
Email = custEmail,
Reference = reference
});
if (postingResponse.OperationResult != OperationResult.Success)
{
//do something
return;
}
transactionLog.ExtReference = postingResponse.Data?.Reference;
transactionLog.Status = postingResponse.OperationResult.ToString();
_dbContext.TransactionLogs.Update(transactionLog);
custAcct.AvailableBalance += firstTransaction.Amount;
custAcct.TotBalance += firstTransaction.Amount;
custAcct.TotDeposit += firstTransaction.Amount;
_dbContext.CustomerAccounts.Update(custAcct);
contribution.Entity.IsApproved = true;
contribution.Entity.IsApprovedDate = DateTime.UtcNow;
_dbContext.Contributions.Update(contribution.Entity);
await _dbContext.SaveChangesAsync();
}
```

How to avoid duplicated headlines from news api?

I am using a news api where I am often getting many duplicate headlines. How can I adapt my code to avoid this?
final response = await http.get(url);
final jsonData = jsonDecode(response.body);
if (jsonData[Strings.status] == Strings.ok) {
jsonData[Strings.articles].forEach((element) {
if (element[Strings.urlToImg] != null &&
element[SharedStrings.description] != null) {
ArticleModel articleModel = ArticleModel(
title: element[SharedStrings.title],
author: element[Strings.author],
description: element[SharedStrings.description],
url: element[Strings.urlText],
urlToImage: element[Strings.urlToImg],
content: element[Strings.content], //context
);
news.add(articleModel);
getNews() async {
News newsClass = News();
await newsClass.getNews();
articles = newsClass.news;
setState(() => _loading = false);
}
before the line
news.add(articleModel);
Add this:
var isDuplicated = false;
for (var new in news) {
if (new.title == articleModel.title) {
isDuplicated = true;
}
}
if (!isDuplicated) {
// Now you can add it
news.add(articleModel);
}

Saving data from XMLHttpRequest Response to my IndexedDB

I have created a json file containing my Sql Server datas. With the XmlHttpRequest's GET method, I am reading json file and iterating and saving those records to my IndexedDB.. Everything is working fine.. After the end of the iteration, I wrote a code to alert the user.. But the alert message is displayed very quickly, but when I see it in the console window, the saving operation is till processing.. I want to alert the user, only after the operation is completed..
My code is,
if (window.XMLHttpRequest) {
var sFileText;
var sPath = "IDBFiles/Reservation.json";
//console.log(sPath);
var xhr = new XMLHttpRequest();
xhr.open("GET", sPath, 1);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
if (xhr.responseText != "") {
sFileText = xhr.responseText;
//console.log(sFileText);
var val = JSON.parse(sFileText);
var i = 0;
var value = val.length;
for(var i in val)
{
var code = val[i].RTM_res_category_code;
var desc = val[i].RTM_res_category_edesc;
addReserv(code, desc);
}
if(i >= value-1) {
console.log("Reservation Load Completed... "+i);
document.getElementById("status").innerHTML = "Reservation Loading Success...";
}
}
}
}
xhr.send();
}
//Passing Parameters to Reservation
function addReserv(code, desc)
{
document.querySelector("#status").innerHTML = "Loading Reservation.. Please wait...";
var trans = db.transaction(["Reservation"], "readwrite");
var store = trans.objectStore("Reservation");
//console.log(store);
var reserv={ RTM_res_category_code : code, RTM_res_category_edesc : ''+desc+'' };
var request = store.add(reserv);
request.onerror = function(e) {
console.log(e.target.error.name);
document.querySelector("#status").innerHTML = e.target.error.name;
}
request.onsuccess = function(e) {
console.log("Reservation Saved Successfully.");
//document.querySelector("#status").innerHTML = "Reservation Loaded Successfully.";
}
}
Thanks for the question.
What you are currently doing works, but the alert comes to soon because of the async nature of the IDB.
What you should to avoid this.
1. Create your transaction only once.
2. Do all your operations in this one transaction.
3. The transaction object has an oncomplete callback you can use to notify the user.
Concrete on your example. Instead of looping over the items in the ajax callback, pass the collection to your add method and loop there
if (window.XMLHttpRequest) {
var sFileText;
var sPath = "IDBFiles/Reservation.json";
//console.log(sPath);
var xhr = new XMLHttpRequest();
xhr.open("GET", sPath, 1);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
if (xhr.responseText != "") {
sFileText = xhr.responseText;
//console.log(sFileText);
var val = JSON.parse(sFileText);
import(val);
}
}
}
xhr.send();
}
function import(values)
{
document.querySelector("#status").innerHTML = "Loading Reservation.. Please wait...";
var trans = db.transaction(["Reservation"], "readwrite");
var store = trans.objectStore("Reservation");
var i = 0;
var value = val.length;
for(var i in val)
{
var code = val[i].RTM_res_category_code;
var desc = val[i].RTM_res_category_edesc;
var reserv={ RTM_res_category_code : code, RTM_res_category_edesc : ''+desc+'' };
var request = store.add(reserv);
request.onerror = function(e) {
console.log(e.target.error.name);
document.querySelector("#status").innerHTML = e.target.error.name;
}
request.onsuccess = function(e) {
console.log("Reservation Saved Successfully.");
//document.querySelector("#status").innerHTML = "Reservation Loaded Successfully.";
}
}
trans.oncomplete = function () {
console.log("Reservation Load Completed... "+i);
document.getElementById("status").innerHTML = "Reservation Loading Success...";
}
}

Custom Authentication Azure Mobile Services by Api

I am creating a custom authentication via API on Azure Mobile Service, and picked based on this answer:
Registering and login users in Azure Mobile Services
Then joined with the code of the previous link to create the authentication token.
But I get "internal server error" when I invoke the API. The error happens in here: "...results.length..."
var crypto = require('crypto');
var iterations = 1000;
var bytes = 32;
var aud = "Custom";
var masterKey = "wkeHEoWUaPJSHsSOcWgmVLOZbIpeeg92";
var _request;
var _response;
exports.post = function(request, response) {
var user = request.body.userName;
var pass = request.body.password;
_request = request;
_response = response
validateUserNamePassword(user, pass, function(error, userId, token) {
if (error) {
response.send(401, { error: "Unauthorized" });
} else {
response.send(200, { user: userId, token: token });
}
});
}
function validateUserNamePassword(user, pass, funcao){
var accounts = _request.service.tables.getTable('account');
accounts
.where({ userid : user })
.read({
success: function(results)
{
if (results.length === 0)
{
_response.send(401, { error: "Unauthorized1" });
console.log("Incorrect username or password");
_request.respond(401, "Incorrect username or password");
}
else
_response.send(401, { error: "Unauthorized2" });
var account = results[0];
hash(item.password, account.salt, function(err, h) {
var incoming = h;
if (slowEquals(incoming, account.password)) {
var expiry = new Date().setUTCDate(new Date().getUTCDate() + 30);
var userId = aud + ":" + account.id;
_request.respond(200, {
userId: userId,
token: zumoJwt(expiry, aud, userId, masterKey)
});
}
else {
_request.respond(401, "Incorrect username or password");
}
});
}
}
});
}
function hash(text, salt, callback) {
crypto.pbkdf2(text, salt, iterations, bytes, function(err, derivedKey){
if (err) { callback(err); }
else {
var h = new Buffer(derivedKey).toString('base64');
callback(null, h);
}
});
}
function slowEquals(a, b) {
var diff = a.length ^ b.length;
for (var i = 0; i < a.length && i < b.length; i++) {
diff |= (a[i] ^ b[i]);
}
return diff === 0;
}
function zumoJwt(expiryDate, aud, userId, masterKey) {
var crypto = require('crypto');
function base64(input) {
return new Buffer(input, 'utf8').toString('base64');
}
function urlFriendly(b64) {
return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(new RegExp("=", "g"), '');
}
function signature(input) {
var key = crypto.createHash('sha256').update(masterKey + "JWTSig").digest('binary');
var str = crypto.createHmac('sha256', key).update(input).digest('base64');
return urlFriendly(str);
}
var s1 = '{"alg":"HS256","typ":"JWT","kid":0}';
var j2 = {
"exp":expiryDate.valueOf() / 1000,
"iss":"urn:microsoft:windows-azure:zumo",
"ver":1,
"aud":aud,
"uid":userId
};
var s2 = JSON.stringify(j2);
var b1 = urlFriendly(base64(s1));
var b2 = urlFriendly(base64(s2));
var b3 = signature(b1 + "." + b2);
return [b1,b2,b3].join(".");
}
I'm invoking like this:
try
{
var loginInput = new JObject();
loginInput.Add("userName", "breno");
loginInput.Add("password", "test");
var loginResult = await LoginAuthenticationService.InvokeApiAsync("login", loginInput);
LoginAuthenticationService.CurrentUser = new MobileServiceUser((string)loginResult["user"]);
LoginAuthenticationService.CurrentUser.MobileServiceAuthenticationToken = (string)loginResult["token"];
}
catch (MobileServiceInvalidOperationException e)
{
var exception = e;
}
If you're getting this error "Failed to load script file 'login.js': SyntaxError: Unexpected token }" as seen in the comments, there is a syntax issue with your script. You'll need to go through your scripts and figure out where the issue is at.

serialize Ext.data.JsonStore content

How do you serialize the JsonStore content? I tried Ext.encode(store.data.items), but it throws an exception "too many recursions".
Here's a quick function that should work
function(store) {
if(typeof(store) != 'object') { return ''; }
var dataArray = [];
var encodedData = '';
var data = store.data.items;
Ext.each(data, function(item, index, array) {
dataArray.push(item.data);
});
return Ext.encode(dataArray);
},
Here's another option that uses the each() function on the store itself.
function getEncodedStoreItems(storeName) {
var encodedData = "";
if (typeof storeName !== "undefined") {
var store = Ext.data.StoreManager.lookup(storeName);
if (store != null) {
var data = [];
store.each(function(item, index, count) {
data.push(item.data);
});
encodedData = Ext.encode(data);
}
}
return encodedData;
}