Async /Await call gets stuck in web API - c#

We have a web API application which runs on .net4.6.1. We have tried several times to figure out the root cause where it is getting deadlock, but failed. Below is the code snippet. We are hitting this API endpoint every 1 minute. It will pick 300 transaction at a time for processing from the DB. We have observed that it get stuck when there are no files to process from the DB. Not sure though. It would be helpful if someone can help us.TIA
public class TaxEngineIntegratorController : ApiController
{
public async Task Get(int id)
{
try
{
await MainFileMethod();
}
catch (Exception Ex)
{
SerilogMethods.LogError(log, Ex, "Get");
}
}
public async Task MainFileMethod()
{
List<FileTransaction> lstFTtoLock = new List<FileTransaction>();
try
{
List<int> lstStatusIds = new List<int>();
lstStatusIds.Add(objStatusManager.GetStatusIdbyName(Status.ConversionToXmlSucceded));
lstStatusIds.Add(objStatusManager.GetStatusIdbyName(Status.Reprocess));
//Getting the serviceURL of TRTaxEngine
string seriviceURL = objConfigManager.GetConfigurationdbyKey(ConfigurationList.TRTaxEngineURL);
//Getting the output path for the file to be placed after processing
string outputfilePath = objConfigManager.GetConfigurationdbyKey(ConfigurationList.TRTaxOutputXMLFolder);
FileMasterManager objFileMasterManager = new FileMasterManager();
TRTaxXMLOperations objxmlresp = new TRTaxXMLOperations();
//Getting all the files list for proccessing from the DB
List<FileTransaction> lstFiletoProcess = await objTransManager.GetFileListforProcessingAsync(lstStatusIds, true);
lstFTtoLock = lstFiletoProcess;
if (lstFiletoProcess.Count == 0)
return;
if (lstFiletoProcess.Count > 0)
{
var tasks = new List<Task<string>>();
using (HttpClient httpClnt = new HttpClient())
{
httpClnt.Timeout = TimeSpan.FromMilliseconds(-1);
foreach (FileTransaction item in lstFiletoProcess)
{
TRXMLResponseModel objRespModel = new TRXMLResponseModel();
objRespModel.strxmlResponse = string.Empty;
string fullFileName = item.FilePath + item.ConvertedName;
objRespModel.outputFilename = outputfilePath + item.ConvertedName;
FileMaster fileMaster = objFileMasterManager.GetById(item.FileId);
//Proccessing the file and getting the output filedata
Task<string> t = objxmlresp.GetXMLResponse(seriviceURL, fullFileName, fileMaster.CountryId.GetValueOrDefault(), httpClnt, objFileOperation, objRespModel.outputFilename, item);
tasks.Add(t);
objRespModel.strxmlResponse = await t;
}
var result = await Task.WhenAll(tasks);
}
SerilogMethods.LogCustomException(log, "Http Client Destroyed in Tax Engine", "GetXMLResponse");
}
}
catch (Exception Ex)
{
if (lstFTtoLock != null && lstFTtoLock.Count > 0)
{
objTransManager.UpdateFileTransactionIsPickedtoFalse(lstFTtoLock);
}
throw Ex;
}
}
}
//Getting all the files list for proccessing from the DB
public async Task<List<FileTransaction>> GetFileListforProcessingAsync(List<int> lstStatusList, bool IsActive)
{
try
{
List<FileTransaction> lstFTList = new List<FileTransaction>();
using (SUTBACDEVContext db = new SUTBACDEVContext())
{
//DataTable dtFileTransactions = GetFileTransactionListAsync(lstStatusList, IsActive);
string connectionString = db.Database.GetDbConnection().ConnectionString;
var conn = new SqlConnection(connectionString);
string query = #"[SUTGITA].[GetFileListforProcessing]";
using (var sqlAdpt = new SqlDataAdapter(query, conn))
{
sqlAdpt.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlAdpt.SelectCommand.Parameters.AddWithValue("#StatusId", string.Join(",", lstStatusList.Select(n => n.ToString()).ToArray()));
sqlAdpt.SelectCommand.Parameters.AddWithValue("#IsActive", IsActive);
sqlAdpt.SelectCommand.CommandTimeout = 60000;
DataTable dtFileTransactions = new DataTable();
sqlAdpt.Fill(dtFileTransactions);
if (dtFileTransactions != null && dtFileTransactions.Rows.Count > 0)
{
IEnumerable<long> ids = dtFileTransactions.AsEnumerable().ToList().Select(p => p["id"]).ToList().OfType<long>();
lstFTList = await db.FileTransaction.Include(x => x.File.Country).Where(x => ids.Contains(x.Id)).OrderBy(x => x.Id).ToListAsync();
}
}
}
return lstFTList;
}
catch (Exception ex)
{
throw ex;
}
}
public async Task<string> GetXMLResponse(string baseUrl, string fullFileName, int countryId, HttpClient client, FileOperations objFileOperation, string outputfilePath, FileTransaction item)
{
try
{
var fileData = new StringBuilder(objFileOperation.ReadFile(fullFileName));
using (HttpContent content = new StringContent(TransformToSOAPXml(fileData, countryId), Encoding.UTF8, "text/xml"))
{
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, baseUrl))
{
request.Headers.Add("SOAPAction", "");
request.Content = content;
using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync())
{
using (Stream streamToWriteTo = File.Open(outputfilePath, FileMode.Create))
{
await streamToReadFrom.CopyToAsync(streamToWriteTo);
}
}
var transactionEntry = new FileTransaction
{
FileId = item.FileId,
FilePath = outputfilePath,
ConvertedName = item.ConvertedName,
ActionedBy = Process.Process3,
TimeStamp = DateTime.UtcNow,
StatusId = objStatusManager.GetStatusIdbyName(Status.OutputXmlReceived),
IsActive = true,
CreatedBy = Others.Scheduler,
CreatedOn = DateTime.UtcNow,
ModifiedBy = Others.Scheduler,
ModifiedOn = DateTime.UtcNow
};
//Inserting the new record and Updating isActive filed of previous record in Tranasaction table(Calling updateDataonTRSuccess method of TRTaxXMLOperations class)
await updateDataonTRSuccessAsync(item, transactionEntry);
return "Success";
}
else
{
SerilogMethods.LogCustomException(log, "Error occured in Tax Engine", "GetXMLResponse");
//Log the SOAP response when the SOAP fails with an error message
if (response.Content != null)
{
throw new Exception(await response.Content.ReadAsStringAsync());
}
return null;
}
}
}
}
}
catch (Exception ex)
{
SerilogMethods.LogError(log, ex, "GetXMLResponse");
return null;
}
}
The following changes I have done to make it work to this specific method.
Removal of this line : objRespModel.strxmlResponse = await t;
and added configureawait(false) to this line :List lstFiletoProcess = await objTransManager.GetFileListforProcessingAsync(lstStatusIds, true).ConfigureAwait(false); Below is the working code
public async Task MainFileMethod()
{
List<FileTransaction> lstFTtoLock = new List<FileTransaction>();
try
{
List<int> lstStatusIds = new List<int>();
lstStatusIds.Add(objStatusManager.GetStatusIdbyName(Status.ConversionToXmlSucceded));
lstStatusIds.Add(objStatusManager.GetStatusIdbyName(Status.Reprocess));
//Getting the serviceURL of TRTaxEngine
string seriviceURL = objConfigManager.GetConfigurationdbyKey(ConfigurationList.TRTaxEngineURL);
//Getting the output path for the file to be placed after processing
string outputfilePath = objConfigManager.GetConfigurationdbyKey(ConfigurationList.TRTaxOutputXMLFolder);
FileMasterManager objFileMasterManager = new FileMasterManager();
TRTaxXMLOperations objxmlresp = new TRTaxXMLOperations();
//Getting all the files list for proccessing from the DB
List<FileTransaction> lstFiletoProcess = await objTransManager.GetFileListforProcessingAsync(lstStatusIds, true).ConfigureAwait(false);
lstFTtoLock = lstFiletoProcess;
if (lstFiletoProcess.Count == 0)
return;
if (lstFiletoProcess.Count > 0)
{
var tasks = new List<Task<string>>();
using (HttpClient httpClnt = new HttpClient())
{
httpClnt.Timeout = TimeSpan.FromMilliseconds(-1);
//Getting the files for processing
foreach (FileTransaction item in lstFiletoProcess)
{
TRXMLResponseModel objRespModel = new TRXMLResponseModel();
objRespModel.strxmlResponse = string.Empty;
string fullFileName = item.FilePath + item.ConvertedName;
objRespModel.outputFilename = outputfilePath + item.ConvertedName;
FileMaster fileMaster = objFileMasterManager.GetById(item.FileId);
//Proccessing the file and getting the output filedata
Task<string> t = objxmlresp.GetXMLResponse(seriviceURL, fullFileName, fileMaster.CountryId.GetValueOrDefault(), httpClnt, objFileOperation, objRespModel.outputFilename, item, objTransManager);
tasks.Add(t);
//objRespModel.strxmlResponse = await t;
}
var result = await Task.WhenAll(tasks);
}
}
}
catch (Exception Ex)
{
if (lstFTtoLock != null && lstFTtoLock.Count > 0)
{
objTransManager.UpdateFileTransactionIsPickedtoFalse(lstFTtoLock);
}
throw Ex;
}
}

My Recommendation:
The method "Get(int id)" is somewhat confusing. first, it takes "id" and does nothing with it. Also it return nothing so it is not a "Get" method. It is basically asking for all transactions with status "Status.ConversionToXmlSucceded" & "Status.Reprocess" and are active to be gotten and processed via the "objxmlresp.GetXMLResponse" method... You Dont Have To Await the "MainFileMethod();" in "Get(int id)" just return the task or return Ok(); and allow all the process to go on in the background. You can experiment with reducing the "sqlAdpt.SelectCommand.CommandTimeout = 60000;".

Related

'Unable to deserialize content' when updating Microsoft calendar events in batch on retry

I'm working on an application based on .NET Framework 4.8. I'm using Microsoft Batching API. The below are code snippets
public async Task<List<BatchResponse>> UpdateEventsInBatchAsync(string accessToken, Dictionary<int, Tuple<string, OfficeEvent>> absEvents)
{
var httpMethod = new HttpMethod("PATCH");
var batches = GetUpdateRequestBatches(absEvents, httpMethod);
var graphClient = GetGraphClient(accessToken);
var batchResponses = new List<BatchResponse>();
foreach (var batch in batches)
{
try
{
var batchResponseList = await ExecuteBatchRequestAsync(graphClient, batch).ConfigureAwait(false);
batchResponses.AddRange(batchResponseList);
}
catch (ClientException exc)
{
_logService.LogException("Error while processing update batch", exc);
batchResponses.Add(new BatchResponse
{ StatusCode = HttpStatusCode.InternalServerError, ReasonPhrase = exc.Message });
}
catch (Exception exc)
{
_logService.LogException("Error while processing update batch", exc);
batchResponses.Add(new BatchResponse { StatusCode = HttpStatusCode.InternalServerError, ReasonPhrase = exc.Message });
}
}
return batchResponses;
}
The respective methods used in the above code are mentioned below in respective order-
GetUpdateRequestBatches
private IEnumerable<BatchRequestContent> GetUpdateRequestBatches(Dictionary<int, Tuple<string, OfficeEvent>> absEvents, HttpMethod httpMethod)
{
var batches = new List<BatchRequestContent>();
var batchRequestContent = new BatchRequestContent();
const int maxNoBatchItems = 20;
var batchItemsCount = 0;
foreach (var kvp in absEvents)
{
System.Diagnostics.Debug.Write($"{kvp.Key} --- ");
System.Diagnostics.Debug.WriteLine(_serializer.SerializeObject(kvp.Value.Item2));
var requestUri = $"{_msOfficeBaseApiUrl}/me/events/{kvp.Value.Item1}";
var httpRequestMessage = new HttpRequestMessage(httpMethod, requestUri)
{
Content = _serializer.SerializeAsJsonContent(kvp.Value.Item2)
};
var requestStep = new BatchRequestStep(kvp.Key.ToString(), httpRequestMessage);
batchRequestContent.AddBatchRequestStep(requestStep);
batchItemsCount++;
// Max number of 20 request per batch. So we need to send out multiple batches.
if (batchItemsCount > 0 && batchItemsCount % maxNoBatchItems == 0)
{
batches.Add(batchRequestContent);
batchRequestContent = new BatchRequestContent();
batchItemsCount = 0;
}
}
if (batchRequestContent.BatchRequestSteps.Count < maxNoBatchItems)
{
batches.Add(batchRequestContent);
}
if (batches.Count == 0)
{
batches.Add(batchRequestContent);
}
return batches;
}
GetGraphClient
private static GraphServiceClient GetGraphClient(string accessToken)
{
var graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(requestMessage =>
{
requestMessage
.Headers
.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
return Task.FromResult(0);
}));
return graphClient;
}
ExecuteBatchRequestAsync
private async Task<List<BatchResponse>> ExecuteBatchRequestAsync(IBaseClient graphClient, BatchRequestContent batch)
{
BatchResponseContent response = await graphClient.Batch.Request().PostAsync(batch);
Dictionary<string, HttpResponseMessage> responses = await response.GetResponsesAsync();
var batchResponses = new List<BatchResponse>();
var failedReqKeys = new Dictionary<string, TimeSpan>();
foreach (var key in responses.Keys)
{
using (HttpResponseMessage httpResponseMsg = await response.GetResponseByIdAsync(key))
{
var responseContent = await httpResponseMsg.Content.ReadAsStringAsync();
string eventId = null;
var reasonPhrase = httpResponseMsg.ReasonPhrase;
if (!string.IsNullOrWhiteSpace(responseContent))
{
var eventResponse = JObject.Parse(responseContent);
eventId = (string)eventResponse["id"];
// If still null, then might error have occurred
if (eventId == null)
{
var errorResponse = _serializer.DeserializeObject<ErrorResponse>(responseContent);
var error = errorResponse?.Error;
if (error != null)
{
if (httpResponseMsg.StatusCode == (HttpStatusCode)429)
{
System.Diagnostics.Debug.WriteLine($"{httpResponseMsg.StatusCode} {httpResponseMsg.Content}");
var executionDelay = httpResponseMsg.Headers.RetryAfter.Delta ?? TimeSpan.FromSeconds(5);
failedReqKeys.Add(key, executionDelay);
continue;
}
reasonPhrase = $"{error.Code} - {error.Message}";
}
}
}
var batchResponse = new BatchResponse
{
Key = key,
EventId = eventId,
StatusCode = httpResponseMsg.StatusCode,
ReasonPhrase = reasonPhrase
};
batchResponses.Add(batchResponse);
}
}
if (failedReqKeys.Count == 0) return batchResponses;
return await HandleFailedRequestsAsync(graphClient, failedReqKeys, batch, batchResponses).ConfigureAwait(false);
}
HandleFailedRequestsAsync
private async Task<List<BatchResponse>> HandleFailedRequestsAsync(IBaseClient graphClient, Dictionary<string, TimeSpan> failedReqKeys, BatchRequestContent batch, List<BatchResponse> batchResponses)
{
// Sleep for the duration as suggested in RetryAfter
var sleepDuration = failedReqKeys.Values.Max();
Thread.Sleep(sleepDuration);
var failedBatchRequests = batch.BatchRequestSteps.Where(b => failedReqKeys.Keys.Contains(b.Key)).ToList();
var failedBatch = new BatchRequestContent();
foreach (var kvp in failedBatchRequests)
{
failedBatch.AddBatchRequestStep(kvp.Value);
}
var failedBatchResponses = await ExecuteBatchRequestAsync(graphClient, failedBatch);
batchResponses.AddRange(failedBatchResponses);
return batchResponses;
}
I'm getting an error as on the first line in method ExecuteBatchRequestAsync as
Microsoft.Graph.ClientException: Code: invalidRequest
Message: Unable to deserialize content.
---> System.ObjectDisposedException: Cannot access a closed Stream.
Can anyone nudge me where I'm doing wrong?

This OperationContextScope is being disposed out of order

I am calling WCF service in ASP.NET Core and everything is working fine, but whenever end of using gets executed, I get an error:
This OperationContextScope is being disposed out of order
I believe I am using wrong pattern to call WCF service using async/await but I am not sure what I am doing wrong.
Below is the code I am using to call a service.
[HttpPost]
public async Task<IActionResult> Runcase(IFormCollection formCollection)
{
if (ModelState.IsValid)
{
var runnumber = formCollection["Run number"];
await CallServiceasync();
return RedirectToAction("", "");
}
else
{
return View(formCollection);
}
}
public async Task CallServiceasync()
{
var product = p1.Value;
var a = product.first;
foreach (int Age in a.age)
{
foreach (int Gender in a.sex)
{
foreach (int Healthclass in a.uclass)
{
RequestData requestData = new RequestData()
{
ProductID = 534,
STATE = "CO",
AGE1 = Age,
SEX1 = Gender,
UND_CLASS1 = Healthclass,
};
RecieveResponseasync(requestData);
}
}
}
}
public async Task RecieveResponseasync(InputValues inputValues)
{
string reqedata = "";
string apikey = "001010iZno7001010L";
QuoteEngineService.MarketingSoftwareClient Service = new QuoteEngineService.MarketingSoftwareClient();
await Service.OpenAsync();
try
{
using (OperationContextScope scope = new OperationContextScope(Service.InnerChannel))
{
HttpRequestMessageProperty httpRequestMessage = new HttpRequestMessageProperty();
httpRequestMessage.Headers.Add("apikey", apikey);
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestMessage;
reqedata = inputValues.XmlSerializetoString();
var result = await Service.ProcessRequestAsync(reqedata, "4fa2-ae27");
var outputvalues = new OutputvaluesViewModel();
outputvalues = result.DeserializeToObject();
List<OutputValue> outputs = new List<OutputValue>();
if (outputvalues.InitialPremium != null)
outputs.Add(new OutputValue { Name = "InitialPremium", Result = outputvalues.InitialPremium});
if (outputvalues.TargetPremium != null)
outputs.Add(new OutputValue { Name = "TargetPremium", Result = outputvalues.TargetPremium });
foreach (var output in outputs)
{
await _context.outputValues.AddAsync(output);
await _context.SaveChangesAsync();
}
await Task.Delay(500);
}
}// **At this point I am getting error**
catch (Exception ex)
{
throw;
}
finally
{
if (Service.State == System.ServiceModel.CommunicationState.Opened)
{
await Service.CloseAsync();
}
}
}
From the docs:
Warning
Do not use the asynchronous "await" pattern within a OperationContextScope block. When the continuation occurs, it may run on a different thread and OperationContextScope is thread specific. If you need to call "await" for an async call, use it outside of the OperationContextScope block.

Azure web service throwing HttpRequestException

i need help in solving below error, it was working since until 2 weeks and suddenly we are getting this error. We are not able to call the azure webservice in C#.NET code,
Webserice : https://ussouthcentral.services.azureml.net/workspaces/aca19128d0a54309a75f5be4052c34a9/services/aee04e32d13d435d8d53b518b8504c5b/execute?api-version=2.0&details=true
Exception:
Inner Exception Type: System.Net.Http.HttpRequestException
Inner Exception: An error occurred while sending the request.
Inner Source: mscorlib
Inner Stack Trace:
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at max_data.d__3.MoveNext() in d:HARDCASTLE_OFFICE_2019Hardcastle_Work_2019_VS2012mckinseyhandlermax_data.ashx:line 281
Exception Type: System.AggregateException
Exception: One or more errors occurred.
Source: max_data
Stack Trace:
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at max_data.get_r_Data(String uid) in d:HARDCASTLE_OFFICE_2019Hardcastle_Work_2019_VS2012mckinseyhandlermax_data.ashx:line 137
The Page Code I use to make this request is below:
<%# WebHandler Language="C#" Class="max_data" %>
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.VisualBasic;
using System.Xml;
using System.Security.Cryptography;
using System.IO;
using System.Collections.Generic;
using System.Net.Mail;
using System.Text;
using System.Data.OleDb;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Xml.XPath;
using System.Web.Configuration;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;
using MySql.Data;
using MySql.Data.MySqlClient;
public class max_data : IHttpHandler {
private MySqlConnection myAccessConn = null;
MysqlDBInteraction Interaction = new MysqlDBInteraction();
public static string arrayvalue = string.Empty;
public void ProcessRequest (HttpContext context) {
//View propery Details
string abc = context.Request["MAXDATA"];
if (abc != "" && abc != null)
{
context.Response.Write(get_r_Data(abc));
}
}
private string d_Data(string uid)
{
string response = string.Empty;
try
{
//Code for insert survey
string surveyid = string.Empty;
string[] str_surveyarray = uid.Split('*');
string[] sarray = str_surveyarray[1].Split('#');
string insert_surveyquery = "INSERT INTO `ADMIN_SURVEY_TBL`(`SURVEY_NAME`, `SURVEY_TYPE`, `ACTIVE`, `CREATED_BY_ID`,`QUESTION_TEXT`,`SHOW_FLAG`) VALUES ('" + sarray[0] + "','MaxDiff Survey','Y','" + sarray[2] + "','In each card given below, select the options MOST PREFERRED & LEAST PREFERRED by you.','N');SELECT MAX(`SURVEY_ID`) as `SURVEY_ID` FROM `ADMIN_SURVEY_TBL`";
string survey_res = InsertData(insert_surveyquery);
if (survey_res.Split('|')[0] == "SUCCESS")
{
surveyid = survey_res.Split('|')[1];
}
else
{
surveyid = "0";
}
//
//Code for Write the CSV file
StringBuilder sb = new StringBuilder();
string[] straary = str_surveyarray[0].Split('#');
for (int i = 0; i < straary.Length; i++)
{
sb.Append(FormatCSV(straary[i].ToString()));
sb.AppendLine();
}
string uriPath = "DATA/DATA.csv";//_IPHONE/MCKINSEY
//string uriPath = "http://hardcastlegis.co.in/_IPHONE/MCKINSEY/SAVE_SURVEY/amol28_132_LEVEL.csv";//_IPHONE/MCKINSEY
uriPath = HttpContext.Current.Server.MapPath(uriPath);
File.WriteAllText(uriPath, sb.ToString());
//code ends here
//File.WriteAllText("http://hardcastlegis.co.in/_IPHONE/MCKINSEY/final_data.csv", sb.ToString());
//InvokeRequestResponseService().Wait();
response = surveyid +"|"+ arrayvalue;
}
catch (Exception ex)
{
ExceptionUtility.LogException(ex, "max_data");
ExceptionUtility.NotifySystemOps(ex);
}
return response;
}
public static string FormatCSV(string input)
{
try
{
if (input == null)
return string.Empty;
bool containsQuote = false;
bool containsComma = false;
int len = input.Length;
for (int i = 0; i < len && (containsComma == false || containsQuote == false); i++)
{
char ch = input[i];
if (ch == '"')
containsQuote = true;
else if (ch == ',')
containsComma = true;
}
if (containsQuote && containsComma)
input = input.Replace("\"", "\"\"");
if (containsComma)
return "\"" + input + "\"";
else
return input;
}
catch
{
throw;
}
}
private string get_r_Data(string uid)
{
string response = string.Empty;
string[] strvar_aaray = uid.Split('*');
string surveyid = strvar_aaray[0].Trim();
string level_csv = strvar_aaray[1].Trim();
string data_csv = strvar_aaray[2].Trim();
string no_of_features = strvar_aaray[3].Trim();
string no_of_cards = strvar_aaray[4].Trim();
try
{
int no_featurs = Convert.ToInt32(no_of_features);
InvokeRequestResponseService(no_featurs,level_csv,data_csv).Wait();
response = surveyid + "|" + arrayvalue;
}
catch (Exception ex)
{
ExceptionUtility.LogException(ex, "max_data");
ExceptionUtility.NotifySystemOps(ex);
}
return response;
}
static async Task InvokeRequestResponseService(int no_features, string level_csv, string data_csv)
{
//code for no of features 3 or 4 or 5//test100_124_DATA//test100_124_LEVEL
string authenication_url = string.Empty;
int val = 1;
if (no_features == 3)
{
authenication_url = "https://ussouthcentral.services.azureml.net/workspaces/aca19128d0a54309a75f5be4052c34a9/services/aee04e32d13d435d8d53b518b8504c5b/execute?api-version=2.0&details=true";
//authenication_url = "https://services.azureml.net/workspaces/aca19128d0a54309a75f5be4052c34a9/webservices/20130f84ec3e43d9805fea5f98f1d423/endpoints/default?fromStudio=true";
//apikey_str = "Qn83z7Lq10SixRAYAWEjnwfnuxVTyDR3GQsYj1FehXPXvhGEGLNLVva/ldnodNJ3kSoxKxPQnBsvB84vIoHT8Q==";
using (var client = new HttpClient())
{
var scoreRequest = new
{
GlobalParameters = new Dictionary<string, string>() {
{ "Data source URL1", "http://103.224.247.79/mckinsey/PHP/_IPHONE/MCKINSEY/SAVE_SURVEY/"+data_csv+"" },
{ "Data source URL", "http://103.224.247.79/mckinsey/PHP/_IPHONE/MCKINSEY/SAVE_SURVEY/"+level_csv+"" },
}
};
const string apiKey = "Qn83z7Lq10SixRAYAWEjnwfnuxVTyDR3GQsYj1FehXPXvhGEGLNLVva/ldnodNJ3kSoxKxPQnBsvB84vIoHT8Q=="; // Replace this with the API key for the web service
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
client.BaseAddress = new Uri(authenication_url);
// WARNING: The 'await' statement below can result in a deadlock if you are calling this code from the UI thread of an ASP.Net application.
// One way to address this would be to call ConfigureAwait(false) so that the execution does not attempt to resume on the original context.
// For instance, replace code such as://http://hardcastlegis.in/mckinsey_new/handler/DATA/DATA.csv
// result = await DoSomeTask()
// with the following://http://hardcastlegis.co.in/_IPHONE/MCKINSEY/final_data.csv
// result = await DoSomeTask().ConfigureAwait(false)
//http://hardcastlegis.in/mckinsey_new/handler/DATA/DATA.csv
//http://hardcastlegis.in/mckinsey_new/handler/DATA/DATACSV.csv
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, authenication_url);
HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync();
arrayvalue = result;
Console.WriteLine("Result: {0}", result);
}
else
{
Console.WriteLine(string.Format("The request failed with status code: {0}", response.StatusCode));
// Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
Console.WriteLine(response.Headers.ToString());
string responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
}
}
else if (no_features == 4)
{
authenication_url = "https://ussouthcentral.services.azureml.net/workspaces/aca19128d0a54309a75f5be4052c34a9/services/a98fd224e6e44331989944b460112171/execute?api-version=2.0&details=true";
//apikey_str = "kPfZ4KCpo30bTFDn57U+T1gTY33bioA7dziEHp5xgLzbHtZmIOdeP6w0uRGZgEazR9/hXnygCI/MqlW7mtsrMw==";
using (var client = new HttpClient())
{
var scoreRequest = new
{
GlobalParameters = new Dictionary<string, string>() {
{ "Data source URL1", "http://103.224.247.79/mckinsey/PHP/_IPHONE/MCKINSEY/SAVE_SURVEY/"+data_csv+"" },
{ "Data source URL", "http://103.224.247.79/mckinsey/PHP/_IPHONE/MCKINSEY/SAVE_SURVEY/"+level_csv+"" },
}
};
const string apiKey = "kPfZ4KCpo30bTFDn57U+T1gTY33bioA7dziEHp5xgLzbHtZmIOdeP6w0uRGZgEazR9/hXnygCI/MqlW7mtsrMw=="; // Replace this with the API key for the web service
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
client.BaseAddress = new Uri(authenication_url);
// WARNING: The 'await' statement below can result in a deadlock if you are calling this code from the UI thread of an ASP.Net application.
// One way to address this would be to call ConfigureAwait(false) so that the execution does not attempt to resume on the original context.
// For instance, replace code such as://http://hardcastlegis.in/mckinsey_new/handler/DATA/DATA.csv
// result = await DoSomeTask()
// with the following://http://hardcastlegis.co.in/_IPHONE/MCKINSEY/final_data.csv
// result = await DoSomeTask().ConfigureAwait(false)
//http://hardcastlegis.in/mckinsey_new/handler/DATA/DATA.csv
//http://hardcastlegis.in/mckinsey_new/handler/DATA/DATACSV.csv
HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync();
arrayvalue = result;
Console.WriteLine("Result: {0}", result);
}
else
{
Console.WriteLine(string.Format("The request failed with status code: {0}", response.StatusCode));
// Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
Console.WriteLine(response.Headers.ToString());
string responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
}
}
else
{
try
{
//code for no of features is 5
//authenication_url = "https://ussouthcentral.services.azureml.net/workspaces/aca19128d0a54309a75f5be4052c34a9/services/72a80928c1564d75a89589c64fe865c3/execute?api-version=2.0&details=true";
authenication_url = "https://ussouthcentral.services.azureml.net/workspaces/aca19128d0a54309a75f5be4052c34a9/services/72a80928c1564d75a89589c64fe865c3/execute?api-version=2.0&details=true";
using (var client = new HttpClient())
{
var scoreRequest = new
{
GlobalParameters = new Dictionary<string, string>() {
{ "Data source URL", "http://103.224.247.79/mckinsey/PHP/_IPHONE/MCKINSEY/SAVE_SURVEY/"+level_csv+"" },
{ "Data source URL1", "http://103.224.247.79/mckinsey/PHP/_IPHONE/MCKINSEY/SAVE_SURVEY/"+data_csv+"" },
}
};
const string apiKey = "XUWQv5oMfFOKhwOJwWNXYw7Tfgu4r2hHhil4Clu6CBcoEPhCWaVNgT6qeMtFEt/pRfbhV5Z2jeRxV/1pKNTWbw=="; // Replace this with the API key for the web service
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
client.BaseAddress = new Uri("https://ussouthcentral.services.azureml.net/workspaces/aca19128d0a54309a75f5be4052c34a9/services/72a80928c1564d75a89589c64fe865c3/execute?api-version=2.0&details=true");
// WARNING: The 'await' statement below can result in a deadlock if you are calling this code from the UI thread of an ASP.Net application.
// One way to address this would be to call ConfigureAwait(false) so that the execution does not attempt to resume on the original context.
// For instance, replace code such as:
// result = await DoSomeTask()
// with the following:
// result = await DoSomeTask().ConfigureAwait(false)
HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine("Result: {0}", result);
}
else
{
Console.WriteLine(string.Format("The request failed with status code: {0}", response.StatusCode));
// Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
Console.WriteLine(response.Headers.ToString());
string responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
}
}
catch (HttpRequestException e)
{
Console.WriteLine(e.InnerException.Message);
}
return;
//apikey_str = "XUWQv5oMfFOKhwOJwWNXYw7Tfgu4r2hHhil4Clu6CBcoEPhCWaVNgT6qeMtFEt/pRfbhV5Z2jeRxV/1pKNTWbw==";
using (var client = new HttpClient())
{
var scoreRequest = new
{
GlobalParameters = new Dictionary<string, string>() {
{ "Data source URL1", "http://103.224.247.79/mckinsey/PHP/_IPHONE/MCKINSEY/SAVE_SURVEY/"+data_csv+"" },
{ "Data source URL", "http://103.224.247.79/mckinsey/PHP/_IPHONE/MCKINSEY/SAVE_SURVEY/"+level_csv+"" },
}
};
const string apiKey = "XUWQv5oMfFOKhwOJwWNXYw7Tfgu4r2hHhil4Clu6CBcoEPhCWaVNgT6qeMtFEt/pRfbhV5Z2jeRxV/1pKNTWbw=="; // Replace this with the API key for the web service
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
client.BaseAddress = new Uri(authenication_url);
/*http://hardcastlegis.co.in/_IPHONE/MCKINSEY/SAVE_SURVEY/CV Demo_17_DATA.csv
http://hardcastlegis.co.in/_IPHONE/MCKINSEY/SAVE_SURVEY/CV Demo_17_LEVEL.csv*/
// WARNING: The 'await' statement below can result in a deadlock if you are calling this code from the UI thread of an ASP.Net application.
// One way to address this would be to call ConfigureAwait(false) so that the execution does not attempt to resume on the original context.
// For instance, replace code such as://http://hardcastlegis.in/mckinsey_new/handler/DATA/DATA.csv
// result = await DoSomeTask()
// with the following://http://hardcastlegis.co.in/_IPHONE/MCKINSEY/final_data.csv
// result = await DoSomeTask().ConfigureAwait(false)
//http://hardcastlegis.in/mckinsey_new/handler/DATA/DATA.csv
//http://hardcastlegis.in/mckinsey_new/handler/DATA/DATACSV.csv
HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync();
arrayvalue = result;
Console.WriteLine("Result: {0}", result);
}
else
{
Console.WriteLine(string.Format("The request failed with status code: {0}", response.StatusCode));
// Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
Console.WriteLine(response.Headers.ToString());
string responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
}
}
//ends here
}
public class StringTable
{
public string[] ColumnNames { get; set; }
public string[,] Values { get; set; }
}
//database
public bool GetConnection(string connString)
{
string Error = string.Empty;
try
{
myAccessConn = new MySqlConnection(connString);
myAccessConn.Open();
return true;
}
catch (Exception ex)
{
Error = "ERRR|" + ex.Message;
//Write error information in ErrorLog.xml file
ExceptionUtility.LogException(ex, "MysqlDBInteraction");
ExceptionUtility.NotifySystemOps(ex);
return false;
}
}
public void CloseConnection()
{
try
{
if (myAccessConn == null)
return;
if (myAccessConn.State == ConnectionState.Open)
myAccessConn.Close();
}
catch (Exception ex)
{
//ex.Message;
ExceptionUtility.LogException(ex, "MysqlDBInteraction");
ExceptionUtility.NotifySystemOps(ex);
}
}
public string GetStringFomXML(string tagName)
{
string Response = string.Empty;
XmlDocument xmldoc = new XmlDocument();
try
{
//Load xml file.
xmldoc.Load(HttpContext.Current.Server.MapPath("HDCONNECT") + "\\Connectionpath.xml");
for (int _Count = 0; _Count < xmldoc.ChildNodes[1].ChildNodes.Count; _Count++)
{
if (xmldoc.ChildNodes[1].ChildNodes[_Count].Name == tagName)
{
Response = xmldoc.ChildNodes[1].ChildNodes[_Count].InnerText.ToString();
}
}
//Response = "Server=103.21.58.5;Port=3306;Database=test_mysql;Uid=testuser;Pwd=Testuser5#9960;";
//Response = "Server=103.21.58.5;Port=3306;Database=hardcast_PROPERTY_TAX;Uid=propertyuser;Pwd=Property#9960;";
return Response;
}
catch (Exception ex)
{
Response = "ERROR|" + ex.Message;
//Write error information in ErrorLog.xml file
ExceptionUtility.LogException(ex, "MysqlDBInteraction");
ExceptionUtility.NotifySystemOps(ex);
return Response;
}
}
public string InsertData(string insertQuery)
{
MySqlCommand comm = new MySqlCommand();
//OleDbCommand comm = new OleDbCommand();
try
{
string connString = GetStringFomXML("Connection");
bool CheckConn = GetConnection(connString);
if (CheckConn)
{
comm.CommandType = CommandType.Text;
comm.Connection = myAccessConn;
comm.CommandText = insertQuery;
comm.ExecuteNonQuery();
long lastid = comm.LastInsertedId;
return "SUCCESS| " + lastid.ToString() + "";
}
else
{ return "ERROR|Unable to connect database. Please try again."; }
}
catch (Exception ex)
{
ExceptionUtility.LogException(ex, "MysqlDBInteraction");
ExceptionUtility.NotifySystemOps(ex);
return "ERROR|" + ex.Message;
}
finally
{
comm.Cancel();
comm.Dispose();
CloseConnection();
}
}
//ends
public bool IsReusable {
get {
return false;
}
}
}
from above code I get InvokeRequestResponseService function use for call servcie

C# async method does not return to caller as expected

I have a series of asynchronous functions that are cascaded, but when it finishes executing the last, it does not return the values ​​to the previous ones.
This is where my first call is run. This is a WebAPI function and always comes to an end.
[HttpGet]
[Route("integracao/iniciar")]
public IHttpActionResult FazerIntegrar()
{
try
{
Integrar objIntegrar = new Integrar();
return Ok(objIntegrar.Integra());
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
so my function is in my library is called. Within my function I have a for executing only once. The flow is never resumed by it to continue the loop
public async Task<bool> Integra()
{
var files = Directory.GetFiles(#"C:\inetpub\wwwroot\Atendup\Arquivos\Backup\");
bool retorno = false;
if (files != null)
{
foreach (var item in files)
{
retorno = false;
using (StreamReader sr = new StreamReader(item))
{
if (sr != null)
{
while (sr.EndOfStream == false)
{
string line = await sr.ReadLineAsync();
string[] grupo = line.Split(new[] { "#*#" }, StringSplitOptions.None);
procData objProc = new procData();
objProc.proc = grupo[0];
objProc.name = JsonConvert.DeserializeObject<List<string>>(grupo[1]);
objProc.valor = JsonConvert.DeserializeObject<List<object>>(grupo[2]);
objProc.tipo = JsonConvert.DeserializeObject<List<Type>>(grupo[3]);
_context = new IntegrarRepository("online_pedidopizza");
retorno = await _context.IntegrarAsync(objProc);
//retorno = await _context.IntegrarAsync(objProc);
}
}
}
if (retorno == true)
{
await DeleteAsync(item);
}
}
}
return retorno;
}
I have a third function just to mediate with the repository
public async Task<bool> IntegrarAsync(procData objProc)
{
return await this.SendIntegrarAsync(objProc);
}
And finally, communication with the database, all code is executed correctly. Debugging you can get to the end of this fourth function but then the debug stop and does not go back to the beginning
protected async Task<bool> SendIntegrarAsync(procData parametro)
{
bool retorno = false;
using (SqlConnection conn = new SqlConnection(""))
{
using (SqlCommand cmd = new SqlCommand(parametro.proc, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
if (parametro != null)
{
for (int i = 0; i < parametro.name.Count; i++)
{
AdicionaParametro(cmd, parametro.name[i], parametro.valor[i], parametro.tipo[i]);
}
}
try
{
cmd.CommandTimeout = 300;
await conn.OpenAsync().ConfigureAwait(false);
var resultado = await cmd.ExecuteScalarAsync().ConfigureAwait(false);
if (resultado != null)
{
retorno = Convert.ToBoolean(resultado);
}
}
catch (Exception ex)
{
Logs objLog = new Logs()
{
metodo = MethodBase.GetCurrentMethod().Name,
classe = this.GetType().Name,
dados = parametro,
data = DateTime.Now,
mensagem = ex.Message,
exception = ex.InnerException == null ? "" : ex.InnerException.ToString()
};
objLog.Adiciona();
string name = DateTime.Now.ToBinary().ToString();
using (StreamWriter sw = new StreamWriter(#"C:\inetpub\wwwroot\Atendup\Arquivos\Backup\" + name + ".txt"))
{
string line = "";
line += parametro.proc + "#*#";
line += JsonConvert.SerializeObject(parametro.name) + "#*#";
line += JsonConvert.SerializeObject(parametro.valor) + "#*#";
line += JsonConvert.SerializeObject(parametro.tipo) + "#*#";
sw.WriteLine(line);
}
}
}
}
return retorno;
}
What should I have to do? Thanks
Your Web Api call is not async try changing it to:
[HttpGet]
[Route("integracao/iniciar")]
public async Task<IHttpActionResult> FazerIntegrar()
{
try
{
Integrar objIntegrar = new Integrar();
return Ok(await objIntegrar.Integra());
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}

How to Update campaign in Bing Ads?

For Update campaign I am using this Code
public async Task<List<long?>> updateCampaign(Campaign campaign,string status)
{
try
{
campaign.Status = (CampaignStatus)(int)Enum.Parse(typeof(CampaignStatus), status);
var request = new UpdateCampaignsRequest
{
Campaigns = new Campaign[] { campaign },
CustomerId = "xxxxxx",
UserName = "something#outlook.com",
Password = "something#123",
ApplicationToken = "myApplicationToken",
CustomerAccountId = "123456",
DeveloperToken = "1234567890"
};
CampaignService = new ServiceClient<ICampaignManagementService>(_authorizationData);
CampaignService.RefreshOAuthTokensAutomatically = false;
var result = (await CampaignService.CallAsync((s, r) => s.UpdateCampaignsAsync(r), request));
if (result.TrackingId != null)
{
return result.CampaignIds.ToList();
}
else
{
return new List<long?>();
}
}
catch (Exception ex)
{
ErrorLog.log(ex);
return new List<long?>();
}
}
When I run this code, I got this error "Invalid client data. Check the SOAP fault details for more information"
thanks.
For updating the Campaign we can use "BulkServiceManager" for bulk updating of the campaign,you can use this service single campaign update also.
public async Task<List<long?>> updateCampaign(List<Campaign> campaigns)
{
try
{
var listBulkCampaign = new List<BulkCampaign>();
foreach (var campaign in campaigns)
{
var _bulkCampaign = new BulkCampaign()
{
Campaign = campaign
};
listBulkCampaign.Add(_bulkCampaign);
}
BulkServiceManager bulkServiceManager = new BulkServiceManager(_authorizationData);
string fileName = bingCampaignUpdate.csv;
var campaigns = (await bulkServiceManager.UploadEntitiesAsync(new EntityUploadParameters
{
Entities = listBulkCampaign,
OverwriteResultFile = true,
ResultFileDirectory = FileDirectory,
ResultFileName = fileName,
ResponseMode = ResponseMode.ErrorsAndResults
})).OfType<BulkCampaign>().ToList();
return new List<long?>();
}
catch (Exception ex)
{
ErrorLog.log(ex);
return new List<long?>();
}
}
You have to download .csv report and update the Campaigns.
I hope it helps you

Categories

Resources