Why is hangfire triggering multiple times - hangfire

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();
}
```

Related

Please Report: Excessing number of pending callbacks - React Native Socket.io client

const [markets,setMarkets]=useState(false)
useEffect(() => {
if (socketConnection != null) {
socketConnection.on("url", (data) => {
getData();
markets.length > 0 &&
markets.map((market) => {
if (data.pair == market.pair) {
let newPrice = data.price.toFixed(data.decimalValue);
let oldData = markets.filter(
(market) => market.pair == data.pair
)[0];
let oldIndex = markets.findIndex(
(market) => market.pair == data.pair
);
let oldPrice = oldData.price.toFixed(oldData.decimalValue);
if (newPrice != oldPrice) {
markets[oldIndex].price = data.price;
markets[oldIndex].lastPrice = data.lastPrice;
markets[oldIndex].change = data.change;
markets[oldIndex].oldPrice = oldData.price;
}
}
});
});
setMarkets(markets);
}
}, [socketConnection]);
I am updating my state like this using socket.io-client but getting this error as Please Report : Excessive number of pending requests and app is hanged.Anyone plse help for the issue

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

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

hide index.php from ajax load search in osclass

link look like http://localhost/index.php?page=search&sOrder=dt_pub_date&iOrderType=desc&sPattern=car
// AJAX SEARCH
$('body#body-search').on('change click', '.link-check-box a, .filter-remove a, form.search-side-form input:not(.term), body#body-search #sub-nav a, #home-cat a, #sub-cat a, form.search-side-form select, .sort-it a, .user-type a,.list-grid a, .paginate a', function(event) {
var ajaxStop = false;
if(ajaxSearch == 1 && event.type != 'change') {
event.preventDefault();
}
// Disable on mobile devices when input selected from fancybox
if($(event.target).closest('.search-mobile-filter-box').length) {
if(!$(event.target).closest('#search-sort').length && !$(event.target).closest('.sub-line').length) { // it may not be required
var ajaxStop = true;
//return false;
}
}
var sidebarReload = true;
if($(this).closest('.sidebar-hooks').length || $(event.target).attr('name') == 'locUpdate') {
sidebarReload = false;
}
var sidebar = $('.filter form.search-side-form');
var ajaxSearchUrl = '';
if (event.type == 'click') {
if(typeof $(this).attr('href') !== typeof undefined && $(this).attr('href') !== false) {
ajaxSearchUrl = $(this).attr('href');
}
} else if (event.type == 'change') {
ajaxSearchUrl = baseDir + "index.php?" + sidebar.find(':input[value!=""]').serialize();
}
if(ajaxSearch == 1 && $('input[name="ajaxRun"]').val() != "1" && (ajaxSearchUrl != '#' && ajaxSearchUrl != '') && !ajaxStop) {
if(ajaxSearchUrl == $(location).attr('href')) {
return false;
}
sidebar.find('.init-search').addClass('btn-loading').addClass('disabled').attr('disabled', true);
sidebar.find('input[name="ajaxRun"]').val("1");
$('#search-items').addClass('loading');
$.ajax({
url: ajaxSearchUrl,
type: "GET",
success: function(response){
var length = response.length;
var data = $(response).contents().find('#main').html();
var bread = $(response).contents().find('ul.breadcrumb');
var filter = $(response).contents().find('.filter').html();
sidebar.find('.init-search').removeClass('btn-loading').removeClass('disabled').attr('disabled', false);
sidebar.find('input[name="ajaxRun"]').val("");
$('#main').fadeOut(0, function(){
$('#main').html(data).show(0);
$('#search-items').hide(0);
$('#search-items').removeClass('loading');
$('#search-items').show(0).css('opacity', 0).css('margin-top', '50px').css('margin-bottom', '-50px').animate( { opacity: 1, marginTop:'0', marginBottom:'0'} , 300);
});
if(sidebarReload) {
$('.filter').html(filter);
}
$('ul.breadcrumb').html(bread);

QnA maker get answer from multiple kb

Currently i am getting response from single kb in QnA maker.
Current code.
QnAMaker _qnaservice = new QnAMaker(new QnAMakerEndpoint
{
EndpointKey = _qnaconfig.AuthKey,
Host = _qnaconfig.EndPoint,
KnowledgeBaseId = "{KBID}"
}, new QnAMakerOptions { Top = 3, StrictFilters = channelData.Filters?.ToArray() });
var response = await _qnaservice.GetAnswersAsync(stepContext.Context);
Is there any option to get results from multiple KBs?
The code you have there pulls the top three answers from just the one kb you have from KBID. You have to code to show three answers, and if you're scorethreshold isn't set, its going to return the answer that's something around 0.3 or higher. Then to display them in chat you're going to have to basically iterate through them. For example:
var options = new QnAMakerOptions { Top = 3, ScoreThreshold=0.0F };
var httpClient = _httpClientFactory.CreateClient();
var qnaMaker = new QnAMaker(new QnAMakerEndpoint
{
KnowledgeBaseId = _configuration["QnAKnowledgebaseId"],
EndpointKey = _configuration["QnAEndpointKey"],
Host = _configuration["QnAEndpointHostName"]
},
options,
httpClient);
_logger.LogInformation("Calling QnA Maker");
// The actual call to the QnA Maker service.
var response = await qnaMaker.GetAnswersAsync(turnContext);
if (response != null && response.Length > 0)
{
for (int i = 0; i < response.Length; i++)
{
await turnContext.SendActivityAsync(MessageFactory.Text(response[i].Answer), cancellationToken);
}
}
For my KB, this shows:
Now, if you want to show top three answers from multiple KBs, you're going to have to construct multiple QnAMakers
var qnaMaker = new QnAMaker(new QnAMakerEndpoint
{
KnowledgeBaseId = _configuration["QnAKnowledgebaseId"],
EndpointKey = _configuration["QnAEndpointKey"],
Host = _configuration["QnAEndpointHostName"]
},
options,
httpClient);
var qnaMaker2 = new QnAMaker(new QnAMakerEndpoint
{
KnowledgeBaseId = _configuration["QnAKnowledgebaseId2"],
EndpointKey = _configuration["QnAEndpointKey"],
Host = _configuration["QnAEndpointHostName"]
},
options,
httpClient);
//LATER IN CODE:
var response = await qnaMaker.GetAnswersAsync(turnContext);
var response2 = await qnaMaker2.GetAnswersAsync(turnContext);
if ((response != null && response.Length > 0) && (response2 != null && response2.Length > 0))
{
await turnContext.SendActivityAsync(MessageFactory.Text("Answers from KB1:"), cancellationToken);
for (int i = 0; i < response.Length; i++)
{
await turnContext.SendActivityAsync(MessageFactory.Text(response[i].Answer), cancellationToken);
}
await turnContext.SendActivityAsync(MessageFactory.Text("Answers from KB2:"), cancellationToken);
for (int i = 0; i < response2.Length; i++)
{
await turnContext.SendActivityAsync(MessageFactory.Text(response2[i].Answer), cancellationToken);
}
}
else if (response != null && response.Length > 0)
{
await turnContext.SendActivityAsync(MessageFactory.Text("Answers from JUST KB1:"), cancellationToken);
for (int i = 0; i < response.Length; i++)
{
await turnContext.SendActivityAsync(MessageFactory.Text(response[i].Answer), cancellationToken);
}
}
else if (response2 != null && response2.Length > 0)
{
await turnContext.SendActivityAsync(MessageFactory.Text("Answers from JUST KB2:"), cancellationToken);
for (int i = 0; i < response2.Length; i++)
{
await turnContext.SendActivityAsync(MessageFactory.Text(response2[i].Answer), cancellationToken);
}
}
else
{
await turnContext.SendActivityAsync(MessageFactory.Text("No QnA Maker answers were found."), cancellationToken);
}
Then just do the same length check, and SendActivities for each:

GMaps API - calc route driving into pedestrian area

my calculated route works good so far, but I have some trouble with my destination address.
When the destination is within a pedestrian area (city center), this destination (lat, long) will set to the next valid street. This is probably how it supposed to be, but it's important that I get the route until the specific destination address. What I want: E.g. I drive into the pedestrian area or I drive as far as possible by car and then walk to the destination.
Anyone has an idea how I can solve this problem? I am using the following code, the code works so that is not the problem:
<script type="text/javascript">
var directionsDisplay = new google.maps.DirectionsRenderer({
animation: google.maps.Animation.DROP,
draggable: true
});
var directionsService = new google.maps.DirectionsService();
var map;
var geocoder;
var resultsInput;
var question;
var routeStart, routeEnd;
var travMode;
var frage_gruppen_nr;
var zsf1,zsf2;
var zentrieren;
function initialize() {
geocoder = new google.maps.Geocoder();
routeStart = $('.multiple-short-txt:eq(0) .text:eq(0)');
routeEnd = $('.multiple-short-txt:eq(0) .text:eq(1)');
coords_field_map = $('.text-short:eq(1) .text:eq(0)');
coords_field_map.hide();
zsf1 = $('.multiple-short-txt:eq(1) .text:eq(0)');
zsf2 = $('.multiple-short-txt:eq(1) .text:eq(1)');
var aktuelle_frage = 'r1';
var frage_gruppen_nr = parseInt(aktuelle_frage.substr(1));
frage_gruppen_nr = frage_gruppen_nr - 1;
if(frage_gruppen_nr>1){
routeStart.val('xxxx');
var coords;
var ziel_vorfrage = 'abc';
alert(ziel_vorfrage);
geocoder.geocode( { 'address': ziel_vorfrage}, function(results1, status1) {
if (status1 == google.maps.GeocoderStatus.OK) {
coords = String(results1[0].geometry.location)
}
});
zentrieren = new google.maps.LatLng(coords);
}else{
zentrieren = new google.maps.LatLng(49.759578, 6.644134);
}
travMode = document.getElementsByTagName("SELECT")[0];
question = '{SGQ}_c';
var mapOptions = {
zoom:12,
center: zentrieren
};
map = new google.maps.Map(document.getElementById('gmap_canvas_'+question), mapOptions);
google.maps.event.addListener(directionsDisplay, 'directions_changed', function(event) {
var directions = this.getDirections();
var overview_path = directions.routes[0].overview_path;
var startingPoint = overview_path[0];
var destination = overview_path[overview_path.length - 1];
if (typeof startLatlng === 'undefined' || !startingPoint.equals(startLatlng)) {
startLatlng = startingPoint;
getLocationName(startingPoint, function(name) {
routeStart.val(name);
});
}
if (typeof endLatlng === 'undefined' || !destination.equals(endLatlng)) {
endLatlng = destination;
getLocationName(destination, function(name) {
routeEnd.val(name);
});
}
//alert('startpoint: '+startingPoint);
calculateDistances(startingPoint, destination);
});
directionsDisplay.setMap(map);
resultsInput = $('.text-long:eq(0) .textarea');
$(resultsInput).attr('readonly', true);
}
function calcRoute() {
var coords;
var coords2;
var start = routeStart.val();
geocoder.geocode( { 'address': start}, function(results1, status1) {
if (status1 == google.maps.GeocoderStatus.OK) {
coords = String(results1[0].geometry.location)
}
else {
alert('Die Startadresse konnte nicht gefunden werden.');
}
});
var end = routeEnd.val();
geocoder.geocode( { 'address': end}, function(results2, status1) {
if (status1 == google.maps.GeocoderStatus.OK) {
coords2 = String(results2[0].geometry.location)
}
else {
alert('Die Zieladresse konnte nicht gefunden werden.');
}
});
var selectedMode;
if(travMode.value == 1){
selectedMode = 'DRIVING';
}else if(travMode.value == 2){
selectedMode = 'BICYCLING';
}else if(travMode.value == 3){
selectedMode = 'TRANSIT';
}else if(travMode.value == 4){
selectedMode = 'WALKING';
}
//
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode[selectedMode]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function calculateDistances(origin, destination) {
var selectedMode;
//select travel mode
if(travMode.value == 1){
selectedMode = 'DRIVING';
}else if(travMode.value == 2){
selectedMode = 'BICYCLING';
}else if(travMode.value == 3){
selectedMode = 'TRANSIT';
}else if(travMode.value == 4){
selectedMode = 'WALKING';
}
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode[selectedMode],
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
$(resultsInput).val('Startaddresse: '+origins[i]+'\n\nReiseziel: '+destinations[j]+'\n\nDistanz: '+results[j].distance.text+'\n\nZeit: '+results[j].duration.text+'');
//save result to fields
zsf1.val(results[j].distance.text);
zsf2.val(results[j].duration.text);
}
}
}
}
function getLocationName(latlng, callback) {
geocoder.geocode({
location: latlng
}, function(result, status) {
if (status === google.maps.GeocoderStatus.OK) {
var i = -1;
console.log(result);
// find the array index of the last object with the locality type
for (var c = 0; c < result.length; c++) {
for (var t = 0; t < result[c].types.length; t++) {
if (result[c].types[t].search('locality') > -1) {
i = c;
}
}
}
var locationName = result[0].formatted_address;
callback(locationName);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>