Windows Service not receiving API response when request takes more than 5 mins to process - queue

We have implented a queuing mechanism with windows service which sends API requests in sequential manner. When the API request take more than 5 mins to process, windonws service not taking the subsequent items.
With the log we observed that, windows service not receiving response from API. But when we debug the same things are working fine.
Do we know whether API not giving response back to windows service or something is going on?
Below is the code piece for this issue:
private void ProcessQueueRequestsByEnvironment(EnvironmentTypes environmentType)
{
try
{
var queueRequests = new DbHelper().GetQueueRequestsByEnvironment(environmentType);
if (queueRequests != null && queueRequests.Count > 0)
{
foreach (var queueRequest in queueRequests)
{
LoggingHelper.WriteToFile("======Request Starting - " + environmentType.ToString() + "====== QueueId: " + queueRequest.QueueId + " AnalysisId: " + queueRequest.AnalysisId + " at " + DateTime.Now);
ApiServiceHelper.SendAnalysisRequestToProcess(queueRequest, environmentType);
LoggingHelper.WriteToFile("======Request Completed - " + environmentType.ToString() + "====== QueueId: " + queueRequest.QueueId + " AnalysisId: " + queueRequest.AnalysisId + " at " + DateTime.Now);
}
}
}
catch (Exception ex)
{
if (!ex.Message.Contains("Could not find stored procedure 'SP_GetQueueRequestsToProcess'"))
{
EmailHelper.SendErrorEmailNotification(ex, "QueueProcessingService::ProcessQueueRequestsByEnvironment");
}
LoggingHelper.WriteToFile("======Error occurred while processing " + environmentType.ToString() + " requests at ======" + DateTime.Now + Environment.NewLine + ex.Message + ex.StackTrace);
}
}
....................
public class ApiServiceHelper
{
public static bool SendAnalysisRequestToProcess(QueueItemModel queueItem, EnvironmentTypes environmentType)
{
try
{
using (var client = new HttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan; // Infinite request timeout
string apiUrl = ConfigurationManager.AppSettings["ProductionApiUrl"];
if (environmentType == EnvironmentTypes.STAGING)
{
apiUrl = ConfigurationManager.AppSettings["StagingApiUrl"];
}
client.BaseAddress = new Uri(apiUrl);
client.DefaultRequestHeaders.Add("ServiceRequestKey", ConfigurationManager.AppSettings["ServiceRequestKey"]);
using (StringContent content = new StringContent(JsonConvert.SerializeObject(queueItem), Encoding.UTF8, "application/json"))
{
//HTTP POST
var result = client.PostAsync(apiUrl, content).Result;
bool objResult = JsonConvert.DeserializeObject<bool>(result.Content.ReadAsStringAsync().Result);
return objResult;
}
}
}
catch (Exception ex)
{
LoggingHelper.WriteToFile("======Error occurred while processing the request====== QueueId: " + queueItem.QueueId + " AnalysisId: " + queueItem.AnalysisId + " at " + DateTime.Now + Environment.NewLine + ex.Message + ex.StackTrace);
EmailHelper.SendErrorEmailNotification(ex, "ApiServiceHelper::SendAnalysisRequestToProcess");
return false;
}
}

Related

Firebase fetch inside for loop not working properly

In my project, I took data from the android accessibility stream in a headless background function turned them into an array and split them into chunks for firebase limits, and used a for loop to iterate over them and check in firebase. Sometimes this is not working, especially since I can see the associability service runner but showing data from a bit ago. I think this happens when the user is offline and tried to fetch data from firebase. Can you please have a look at this code and tell me what the issue is and How I should solve it?
N.B: I changed some variable names for privacy purposes. There are no issues with them.
FlutterAccessibilityService.accessStream.listen((event) {
if (event.capturedText != null &&
event.capturedText != "" &&
isCold) {
text = event.capturedText!.toLowerCase();
List textList = getArray(text);
final sharedItems = getSimilarArray(fbtag, textList, sensitivity);
final sharedLocalItems =
getSimilarLocalArray(fbtag, textList, sensitivity);
final sharedAbsItems = getAbsLocalArray(fbtag, textList);
final sharedItemWithLastEval =
getSimilarArray(lastEvaluatedText, textList, sensitivity);
if (text != lastEventText &&
(sharedItemWithLastEval.length == 0 ||
lastEvaluatedText[0] == "first")) {
print("called related content");
print("bg currant text: " +
text.toString() +
" sensitivity: " +
sensitivity.toString() +
" minimumAbsMatch: " +
minimumAbsMatch.toString() +
" shared local items: " +
sharedLocalItems.toString() +
" shared abs items: " +
sharedAbsItems.toString() +
" shared items: " +
sharedItems.toString() +
" last : " +
lastEventText +
" last eval text: " +
lastEvaluatedText.toString() +
" Cold: " +
isCold.toString());
print("captured text: " + text.toString());
//GetRelatedContent(fbtag, event.capturedText);
print(sharedItems);
if (sharedLocalItems.length >= accuracy &&
sharedAbsItems.length >= minimumAbsMatch) {
print("main called");
List result = [];
lastEvaluatedText = sharedItems;
List chunkedList = chunking(sharedItems);
for (int i = 0; i < chunkedList.length; i++) {
FirebaseFirestore.instance
.collection('Content')
.where('keyWords', arrayContainsAny: chunkedList[i])
.get()
.then((value) {
for (int i = 0; i < value.docs.length; i++) {
result.add(value.docs[i].data());
print("sep");
print("result: " + result.toString());
}
if (i == chunkedList.length - 1) {
if (result.isNotEmpty) {
print("final result: " +
result[HighestMatchingIndex(sharedItems, result)[0]]
.toString());
print('result length called' +
' result: ' +
result.toString());
if (HighestMatchingIndex(sharedItems, result)[1] >=
accuracy) {
print('overlay called');
isCold = false;
Timer(Duration(seconds: 60), () {
print("Cold down");
isCold = true;
});
var FinalResult = result[
HighestMatchingIndex(sharedItems, result)[0]];
if (FinalResult['availableCountry']
.contains(country) &&
FinalResult['availableR']
.contains(r)) {
print("all passed");
String l = FinalResult[r]
[country] ??
FinalResult[r]['EN'];
String o =
FinalResult[r]['origin'];
ShowAlert(l, o, r);
}
}
}
}
});
}
}
//
}
lastEventText = text;
}
});

Creating new Objects in JPQL returns only one object

I have a JPA Entity with a large number of fields and millions of records. For a report, I need only some of the fields. So I want to create an Object with the essential fields due to resource constraints. I tried to create a list of new objects in JPQL. It gives only one object as a result, where multiple objects are expected.
String j;
j = "select new lk.gov.health.phsp.pojcs.ClientEncounterComponentBasicDataToQuery("
+ "f.name, "
+ "f.code, "
+ "f.item.code, "
+ "f.shortTextValue, "
+ "f.integerNumberValue, "
+ "f.longNumberValue, "
+ "f.realNumberValue, "
+ "f.booleanValue, "
+ "f.dateValue, "
+ "f.itemValue.code"
+ ") ";
j += " from ClientEncounterComponentItem f "
+ " where f.retired=false "
+ " and f.encounter.id=:eid";
Map m = new HashMap();
m.put("eid", endId);
The EBJ is as follows.
public List<Object> findObjects(String jpql, Map<String, Object> parameters, TemporalType tt) {
TypedQuery<Object> qry = getEntityManager().createQuery(jpql, Object.class);
Set s = parameters.entrySet();
Iterator it = s.iterator();
while (it.hasNext()) {
Map.Entry m = (Map.Entry) it.next();
Object pVal = m.getValue();
String pPara = (String) m.getKey();
if (pVal instanceof Date) {
Date pDate = (Date) pVal;
qry.setParameter(pPara, pDate, TemporalType.DATE);
} else {
qry.setParameter(pPara, pVal);
}
}
try {
return qry.getResultList();
} catch (Exception e) {
return null;
}
}
What am I doing wrong? I am using EclipseLink as the persistence provider.

Select results truncated without error message

I'm using Google Cloud SQL from an App Engine application via Java and JDBC.
I select rows of a table using following code:
public void processGcmRegistrations(String whereCondition, String appName,
String[] appVariants, boolean onlyTestDevices,
String orderByCondition,
GcmRegistrationProcessor processor) throws DbException {
if (whereCondition == null && appName == null)
throw new IllegalArgumentException("One of the parameters \"whereCondition\", " +
"\"appNmae\" must not be null.");
if (whereCondition == null) {
whereCondition = "APP_NAME = '" + appName + "' " +
createInListCondition("APP_VARIANT", appVariants);
if (onlyTestDevices)
whereCondition += " AND TEST_DEVICE = 1 ";
}
String orderByConditionStr = "";
if (orderByCondition != null)
orderByConditionStr = " ORDER BY " + orderByCondition;
String selectStmt = "SELECT GCM_ID, GCM_REGISTRATION_TIME, APP_NAME, APP_VARIANT, " +
"INSTALLATION_ID, DEVICE, LAST_UPDATE " +
"FROM GcmRegistration WHERE " + whereCondition + orderByConditionStr;
log.info("GcmIds Select: " + selectStmt);
ResultSet rs = null;
try {
long start = System.currentTimeMillis();
rs = dbConnection.createStatement().executeQuery(selectStmt);
log.info("Select duration: " + ((System.currentTimeMillis()-start)/1000) + " secs.");
int count = 0;
while (rs.next()) {
GcmRegistration reg = new GcmRegistration();
reg.gcmId = rs.getString(1);
reg.gcmRegistrationTime = rs.getLong(2);
reg.appName = rs.getString(3);
reg.appVariant = rs.getString(4);
reg.installationId = rs.getString(5);
reg.device = rs.getString(6);
reg.lastUpdate = rs.getLong(7);
processor.processGcmRegistration(reg);
count++;
}
log.info(count + " GcmRegistrations processed.");
} catch (Exception e) {
String errorMsg = "Selecting GCM_IDs from table GcmRegistration failed.";
log.log(Level.SEVERE, errorMsg, e);
throw new DbException(errorMsg, e);
} finally {
if (rs != null)
rs.close();
}
}
I always execute this method with the same parameters and receive usually about 152000 rows.
In rare cases (I guess 1 from 50) I receive only about 62000 rows without any exception! rs.next() returns false, although not all result rows are delivered.
For Google: Last time this happened was 8/22/14 23:20 (MEST)

Ado.net Update Command is successful but database is not updated

The following code executes successfully and the return value of cmd.ExecuteNonQuery returns 1 indicating the row was successfully updated but the database is not truly updated. How could that be? I'm using sqlserver2008.
public string updatePost(string id, string head, string body)
{
connection = new SqlConnection(connString);
string cmdStr = "update News set Header = '"+head+"' , [Text] = '"+body+"' where Id = "+int.Parse(id)+"";
string msg = String.Empty;
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(cmdStr, connection);
int effected = cmd.ExecuteNonQuery();
msg += "The 'News Post - id:"+id+"' was successfully updated. Rows effected:"+effected+"";
}
catch (Exception ex)
{
msg = "The attempt to update the 'News Post - id'" + id + " failed with message: " + ex.Message;
}
finally
{
connection.Close();
}
return msg;
}
Try this, this fixes some problems (like sql-injection), perhaps also your update issue:
public string UpdatePost(string id, string head, string body)
{
string msg = "";
string cmdStr = "update News set Header = #header, [Text] = #body where Id = #id";
using (var con = new SqlConnection(connString))
{
try
{
con.Open();
using (var cmd = new SqlCommand(cmdStr, con))
{
cmd.Parameters.AddWithValue("#header", head);
cmd.Parameters.AddWithValue("#body", body);
cmd.Parameters.AddWithValue("#id", int.Parse(id));
int effected = cmd.ExecuteNonQuery();
msg += "The 'News Post - id:" + id + "' was successfully updated. Rows effected:" + effected + "";
}
} catch (Exception ex)
{
msg = "The attempt to update the 'News Post - id'" + id + " failed with message: " + ex.Message;
}
}
return msg;
}

I am using iOS InAppPurchaseManager

with phonegap 1.5.0rc1 and XCode 4.3.
I can not upgrade my mac for the moment.
When I use plugins I do not have any answer, no alert and no message.
I try to do this :
function onDeviceReady() {
processdiv = document.getElementById('processdiv');
processdiv.innerHTML = "Loading...";
window.plugins.inAppPurchaseManager.onPurchased = function(transactionIdentifier, productId, transactionReceipt) {
console.log('purchased: ' + productId);
/* Give coins, enable subscriptions etc */
}
processdiv.innerHTML += "<br />onPurchased OK";
window.plugins.inAppPurchaseManager.onRestored = function(transactionIdentifier, productId, transactionReceipt) {
console.log('restored: ' + productId);
/* See the developer guide for details of what to do with this */
}
processdiv.innerHTML += "<br />onRestored OK";
window.plugins.inAppPurchaseManager.onFailed = function(errno, errtext) {
console.log('failed: ' + errtext);
}
processdiv.innerHTML += "<br />onFailed OK";
}
function requestProdData(prodStr) {
window.plugins.inAppPurchaseManager.requestProductData(prodStr, function(productId, title, description, price) {
console.log("productId: " + productId + " title: " + title + " description: " + description + " price: " + price);
showAlert("productId: " + productId + " title: " + title + " description: " + description + " price: " + price);
window.plugins.inAppPurchaseManager.makePurchase(productId, 1);
}, function(id) {
console.log("Invalid product id: " + id);
showAlert("par la ?? " + id);
}
);
processdiv.innerHTML = "ProductID: " + prodStr + "<br />";
}
Help
I try to add alert in different place of code to know what is the problem.
I had many products in a test app.
I search example to use this plugins. Thanks.
Do not foget to add plugins inAppPurchaseManager in you plugins Cordova.plist :(