After couple days (like 3 days or so) my windows service just stops executing the system.timer events don't fire anymore but the service shows as running. Also my log files don't even get created so no errors are thrown and logged. I have try catches on the highest level as well as on the second highest level and also in the constructor, OnStart and OnStop. Please see my code below.
Any idea what could be causing this?
public partial class BetGamesFeedService : ServiceBase
{
private Timer _gamesTimer;
private Timer _nextDrawTimer;
private Timer _drawResultsTimer;
private Timer _plannedScheduleTimer;
private static readonly log4net.ILog log =
log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public BetGamesFeedService()
{
try
{
log4net.Config.XmlConfigurator.Configure();
//Games Timer
_gamesTimer = new Timer(Convert.ToInt32(ConfigurationManager.AppSettings["GamesInterval"]));
_gamesTimer.Elapsed += GamesTimerOnElapsed;
_gamesTimer.Enabled = true;
//Next Draw Timer
_nextDrawTimer = new Timer(Convert.ToInt32(ConfigurationManager.AppSettings["NextDrawInterval"]));
_nextDrawTimer.Elapsed += NextDrawTimerOnElapsed;
_nextDrawTimer.Enabled = true;
//Draw Results Timer
_drawResultsTimer = new Timer(Convert.ToInt32(ConfigurationManager.AppSettings["DrawResultsInterval"]));
_drawResultsTimer.Elapsed += DrawResultsTimerOnElapsed;
_drawResultsTimer.Enabled = true;
//Planned Schedule Timer
_plannedScheduleTimer = new Timer(Convert.ToInt32(ConfigurationManager.AppSettings["PlannedScheduleInterval"]));
_plannedScheduleTimer.Elapsed += PlannedScheduleTimerOnElapsed;
_plannedScheduleTimer.Enabled = true;
InitializeComponent();
#if DEBUG
OnStart(null);
#endif
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
protected override void OnStart(string[] args)
{
try
{
_gamesTimer.Start();
_nextDrawTimer.Start();
_drawResultsTimer.Start();
_plannedScheduleTimer.Start();
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
protected override void OnStop()
{
try
{
_gamesTimer.Stop();
_nextDrawTimer.Stop();
_drawResultsTimer.Stop();
_plannedScheduleTimer.Stop();
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
private async void GamesTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
{
try
{
var GamesOn = Convert.ToBoolean(ConfigurationManager.AppSettings["GamesIntervalOn"]);
if (!GamesOn) return;
var betGames = new Bl.WindowsService.BetGames();
await betGames.GetGamesAndAddToDatabase();
}
catch(Exception ex)
{
log.Error(ex.ToString());
}
}
private async void NextDrawTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
{
try
{
var betGames = new Bl.WindowsService.BetGames();
await betGames.GetNextDrawAndAddToDatabase(Game.Lucky5);
await betGames.GetNextDrawAndAddToDatabase(Game.Lucky7);
await betGames.GetNextDrawAndAddToDatabase(Game.Lucky6);
await betGames.GetNextDrawAndAddToDatabase(Game.WheelOfFortune);
}
catch(Exception ex)
{
log.Error(ex.ToString());
}
}
private async void DrawResultsTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
{
try
{
var betGames = new Bl.WindowsService.BetGames();
await betGames.GetDrawResultsAndAddToDatabase(Game.Lucky5);
await betGames.GetDrawResultsAndAddToDatabase(Game.Lucky7);
await betGames.GetDrawResultsAndAddToDatabase(Game.Lucky6);
await betGames.GetDrawResultsAndAddToDatabase(Game.WheelOfFortune);
}
catch(Exception ex)
{
log.Error(ex.ToString());
}
}
private async void PlannedScheduleTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
{
try
{
var betGames = new Bl.WindowsService.BetGames();
await betGames.GetScheduledDrawsAndAddToDatabase(Game.Lucky5);
await betGames.GetScheduledDrawsAndAddToDatabase(Game.Lucky7);
await betGames.GetScheduledDrawsAndAddToDatabase(Game.Lucky6);
await betGames.GetScheduledDrawsAndAddToDatabase(Game.WheelOfFortune);
}
catch(Exception ex)
{
log.Error(ex.ToString());
}
}
}
public class BetGames
{
private readonly int _partnerId =
Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PartnerId"]);
private readonly string _secretKey = System.Configuration.ConfigurationManager.AppSettings["SecretKey"];
private readonly int _shopId = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["ShopId"]);
private readonly string[] _method =
{
"get_screen_urls", "get_games", "ticket_buy", "ticket_check",
"ticket_payout", "ticket_return"
};
private const string Language = "en";
private const string Currency = "eur";
private static readonly log4net.ILog log =
log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public async Task GetGamesAndAddToDatabase()
{
try
{
const int methodIndex = 1;
var request = new GetGamesRequest
{
partner_id = _partnerId,
method = _method[methodIndex],
language = Language,
timestamp = GetTimestamp(),
#params = new BaseParams
{
currency = Currency,
shop_id = _shopId
}
};
request.signature = GetSignature(methodIndex, request.timestamp, request.#params);
var api = new BetGamesAPI();
var response = await api.GetGames(request);
if (response == null)
{
log.Info("GetGamesAndAddToDatabase(): No Data Returned.");
return;
}
if (response.response_code != 200)
{
throw new Exception("response.response_code does not indicate success." + Environment.NewLine +
"Response Code: " + response.response_code + Environment.NewLine +
"Response Error: " + response.error_message);
}
var games =
new JavaScriptSerializer().Deserialize(response.response.ToString(), typeof(List<Bo.Models.Game>))
as List<Bo.Models.Game>;
//Add data to database
foreach (var game in games)
{
//#Id
var pId = new SqlParameter("#Id", SqlDbType.Int);
pId.Value = game.id;
//#Name
var pName = new SqlParameter("#Name", SqlDbType.VarChar);
pName.Value = game.name;
//#Type
var pType = new SqlParameter("#Type", SqlDbType.VarChar);
pType.Value = game.type;
//#Items
var dtItems = new DataTable();
dtItems.Columns.Add("Id", typeof(int));
dtItems.Columns.Add("Number", typeof(int));
dtItems.Columns.Add("Color", typeof(string));
foreach (var item in game.items)
{
dtItems.Rows.Add(item.id, item.number, item.color);
}
var pItems = new SqlParameter("#Items", SqlDbType.Structured);
pItems.Value = dtItems;
pItems.TypeName = "bg.ttItem";
//#Odds
var dtOdds = new DataTable();
dtOdds.Columns.Add("Code", typeof(int));
dtOdds.Columns.Add("ItemsCount", typeof(int));
dtOdds.Columns.Add("Name", typeof(string));
dtOdds.Columns.Add("Value", typeof(decimal));
foreach (var odd in game.odds)
{
dtOdds.Rows.Add(odd.code, odd.items_count, odd.name, odd.value);
}
var pOdds = new SqlParameter("#Odds", SqlDbType.Structured);
pOdds.Value = dtOdds;
pOdds.TypeName = "bg.ttOdd";
using (var db = new BetGamesEntities())
{
var cmd = db.Database.Connection.CreateCommand();
cmd.CommandText = "bg.InsertGameOddsAndItems";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(pId);
cmd.Parameters.Add(pName);
cmd.Parameters.Add(pType);
cmd.Parameters.Add(pItems);
cmd.Parameters.Add(pOdds);
db.Database.Connection.Open();
await cmd.ExecuteScalarAsync();
db.Database.Connection.Close();
}
}
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
private string GetSignature(int methodIndex, int timestamp, object _params)
{
var jsonEncodedObject = new JavaScriptSerializer().Serialize(_params);
var signatureBase = _partnerId + _method[methodIndex] + Language + timestamp + jsonEncodedObject;
//Perform hashing
using (var hmac = new HMACSHA256(Encoding.ASCII.GetBytes(_secretKey)))
{
var hash = hmac.ComputeHash(Encoding.ASCII.GetBytes(signatureBase));
return string.Concat(hash.Select(x => x.ToString("x2")));
}
}
private static int GetTimestamp()
{
return (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
}
public async Task GetNextDrawAndAddToDatabase(Game game)
{
try
{
var api = new BetGamesAPI();
var response = await api.GetNextDraw(game);
if (response == null)
{
log.Info("GetNextDrawAndAddToDatabase(" + game + "): No data returned. Draw Probably currently running.");
return;
}
var data =
new JavaScriptSerializer().Deserialize(response.draws.ToString(), typeof(List<Bo.Models.Draw>)) as List<Bo.Models.Draw>;
using (var db = new BetGamesEntities())
{
db.InsertOrUpdateDraw(data[0].code, data[0].time.AddHours(2), Convert.ToBoolean(data[0].is_returned),
data[0].video_url);
}
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
public async Task GetDrawResultsAndAddToDatabase(Game game)
{
try
{
var api = new BetGamesAPI();
using (var db = new BetGamesEntities())
{
var drawCode = db.GetDrawCode((int)game).FirstOrDefault();
if (drawCode == null) return;
var response = await api.GetDraws(game, drawCode.Value);
if (response == null)
{
log.Info("GetDrawResultsAndAddToDatabase(" + game + "): No Data Returned");
return;
}
//Insert Data
var data =
new JavaScriptSerializer().Deserialize(response.draws.ToString(), typeof(List<Bo.Models.Draw>)) as
List<Bo.Models.Draw>;
foreach (var draw in data)
{
//If this draw is Cancelled update the draw status to cancelled
if (draw.is_returned == 1)
{
db.InsertOrUpdateDraw(data[0].code, data[0].time.AddHours(2), Convert.ToBoolean(data[0].is_returned),
data[0].video_url);
}
//if we have results for this draw
if (draw.results_entered == 1)
{
//#DrawCode
var pDrawCode = new SqlParameter("#DrawCode", SqlDbType.BigInt) { Value = draw.code };
//#Results
var dtResults = new DataTable();
dtResults.Columns.Add("BallNumber");
dtResults.Columns.Add("BallColor");
foreach (var result in draw.results)
{
dtResults.Rows.Add(result.Number, result.Color);
}
var pResults = new SqlParameter("#Results", SqlDbType.Structured)
{
Value = dtResults,
TypeName = "bg.ttDrawResult"
};
var cmd = db.Database.Connection.CreateCommand();
cmd.CommandText = "bg.InsertDrawResults";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(pDrawCode);
cmd.Parameters.Add(pResults);
db.Database.Connection.Open();
cmd.ExecuteScalar();
db.Database.Connection.Close();
}
}
}
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
public async Task GetScheduledDrawsAndAddToDatabase(Game game)
{
try
{
var api = new BetGamesAPI();
var response = await api.GetScheduledDraws(game);
if (response == null)
{
log.Info("GetScheduledDrawsAndAddToDatabase(" + game + "): No data returned. Draw Probably currently running.");
return;
}
var data =
new JavaScriptSerializer().Deserialize(response, typeof(List<Bo.Models.ScheduledDraw>)) as List<Bo.Models.ScheduledDraw>;
using (var db = new BetGamesEntities())
{
var scheduledDrawTable = new DataTable();
scheduledDrawTable.Columns.Add("Code", typeof(long));
scheduledDrawTable.Columns.Add("Time", typeof(DateTime));
foreach (var draw in data)
{
scheduledDrawTable.Rows.Add(draw.number, draw.time.AddHours(2));
}
var Draws = new SqlParameter("#Draws", SqlDbType.Structured);
Draws.Value = scheduledDrawTable;
Draws.TypeName = "bg.ttDraw";
var cmd = db.Database.Connection.CreateCommand();
cmd.CommandText = "bg.InsertOrUpdateScheduledDraws";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(Draws);
db.Database.Connection.Open();
cmd.ExecuteScalar();
db.Database.Connection.Close();
}
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
}
Related
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;".
I am scanning QR CODE but the problem is ReceiveDetections method is calling multiple times even after a successful scan.How can I prevent calling the api multiple times after a successful call.
here is the code snippet
public void ReceiveDetections(Detections detections)
{
SparseArray qrcodes = detections.DetectedItems;
if (qrcodes.Size() != 0)
{
txtscankanbancloseResult.Post(async () =>
{
Vibrator vibrator = (Vibrator)GetSystemService(Context.VibratorService);
vibrator.Vibrate(1000);
txtscankanbancloseResult.Text = ((Barcode)qrcodes.ValueAt(0)).RawValue;
try
{
var client = new HttpClient();
var uri = new Uri(string.Format(AppStatics.clsStatic.url + "//Kanban/SaveKanbanStatus"));
List<string> lstskanban = new List<string>();
String myDate = DateTime.Now.ToString("dd-MMM-yyyy");
string adateddate = DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss");
JsonScankanbanclose objjscan = new JsonScankanbanclose();
lstskanban.Add(txtscankanbancloseResult.Text);
objjscan.UpdateBy = SingletonSession.Instance().getUsername();
objjscan.KANBANNOList = lstskanban;
objjscan.IsKANBANClosed = true;
string jsonData = JsonConvert.SerializeObject(objjscan);
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
var result = await response.Content.ReadAsStringAsync();
if (response.ReasonPhrase == "OK")
{
JArray scanresult = JArray.Parse(result);
Scanlist objscan = new Scanlist();
if (ScanSucessfull.Count == 0)
{
objscan.KanbanID = "Kanban NO";
objscan.KanbanQty = "Kanban Qty";
ScanSucessfull.Add(objscan);
objscan = new Scanlist();
}
// Scanlist item = ScanSucessfull.Find(c => c.KanbanID == scanresult[0]["KANBANID"].ToString());
//int itemPosition = ScanSucessfull.BinarySearch(scanresult[0]["KANBANID"].ToString());
//if (itemPosition.cou=="")
//{
objscan.KanbanID = scanresult[0]["KANBANNumber"].ToString();
objscan.KanbanQty = scanresult[0]["Qty"].ToString();
ScanSucessfull.Add(objscan);
//}
var adapter = new CustomAdapterScan(this, ScanSucessfull);
lstviewscankanbanclose.SetAdapter(adapter);
lstviewscankanbanclose.Clickable = false;
//lstview.Enabled = false;
lstviewscankanbanclose.ItemSelected += null;
mPlayer = Android.Media.MediaPlayer.Create(this, Resource.Raw.successful);
currentSong = Resource.Raw.successful;
mPlayer.SeekTo(1);
mPlayer.Start();
//Toast.MakeText(this, , ToastLength.Short).Show();
Helper.ShowToastMessage(this, Color.DarkGreen, "Data Save Sucessfully..", ToastLength.Short);
_kanbancount++;
txtscankanbanclosekanbancount.Text = "Kanban Count:" + " " + _kanbancount;
txtscankanbanclosekanbancount.Visibility = ViewStates.Visible;
}
else
{
string[] result1 = result.Split(':');
string[] result2 = result1[1].Split('"');
string[] result3 = result2[1].Split('"');
mPlayer = Android.Media.MediaPlayer.Create(this, Resource.Raw.fail);
// mPlayer.SeekTo(2);
currentSong = Resource.Raw.fail;
mPlayer.Start();
//Toast.MakeText(this, result3[0].ToString(), ToastLength.Short).Show();
Helper.ShowToastMessage(this, Color.DarkRed, result3[0].ToString(), ToastLength.Short);
}
// dialog.Hide();
cameraSource.Start(surfaceView.Holder);
//txtResult.Text = "";
}
catch (System.Exception ex)
{
Helper.ShowToastMessage(this, Color.DarkRed, ex.Message, ToastLength.Short);
//Toast.MakeText(this, ex.Message.ToString(), ToastLength.Short).Show();
// txtResult.Text = "";
txtscankanbancloseResult.Visibility = ViewStates.Invisible;
//cameraSource.Start(surfaceView.Holder);
}
});
using (var h = new Handler(Looper.MainLooper))
h.Post(() =>
{
cameraSource.Stop();
// Toast.MakeText(this, "This Kanban Already Scanned....", ToastLength.Short).Show();
});
}
}
Here is the code where I crate and open the camera source to scan the QR code
private void btnkanbanscan_Click(object sender, EventArgs e)
{
try
{
#region validation
if (spnSiteID.SelectedItemPosition < 0)
{
throw new Exception("Please Select Site...");
}
if (spnLocation.SelectedItemPosition < 0)
{
throw new Exception("Please Select Location..");
}
if (spnInspactionType.SelectedItemPosition < 0)
{
throw new Exception("Please Select Inspection Type..");
}
#endregion
LayoutInflater layoutInflater = LayoutInflater.From(this);
View scanview = LayoutInflater.Inflate(Resource.Layout.scan_popup, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.SetView(scanview);
surfaceView = scanview.FindViewById<SurfaceView>(Resource.Id.spvscan);
dialog = alertDialogBuilder.Create();
dialog.SetCanceledOnTouchOutside(false);
dialog.Show();
barcodeDetector = new BarcodeDetector.Builder(this)
.SetBarcodeFormats(BarcodeFormat.Code128 | BarcodeFormat.QrCode)
.Build();
cameraSource = new CameraSource.Builder(this, barcodeDetector)
.SetRequestedPreviewSize(480, 480)
.SetAutoFocusEnabled(true)
.Build();
surfaceView.Holder.AddCallback(this);
barcodeDetector.SetProcessor(this);
surfaceView.Visibility = ViewStates.Visible;
_definemethod = "KANBAN";
}
catch (Exception ex)
{
Helper.ShowToastMessage(this, Color.DarkRed, ex.Message, ToastLength.Short);
//Toast.MakeText(this, ex.Message.ToString(), ToastLength.Short).Show();
}
}
NCTB: I noticed that after opening the dialog to scan the QR CODE the ReceiveDetections method get called frequently and the scanned value comes in detections parameter .which is normal and it supposed to do so.But the problem is after a successful scan it should not call anymore.
Is there a way for me to link my module in all of my form i'm using c# app and this is my code. This is actually a notification bell that will notify users if he/she has/have notifications. I already linked it on homepage how am i able to do that in all other pages
private void systemNotificationREXS(HomePage module)
{
TextBox Username = (TextBox)module.FindControl("Hide_user");
Label Fullname = (Label)module.FindControl("userfullname");
Label notifLabel = (Label)module.FindControl("notifLabel");
using (con = new SqlConnection(EXCUSESLPCON))
{
using (cmd = new SqlCommand("SYSTEMNOTIFICATIONEXSLIP", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#userfullname", Fullname.Text);
con.Open();
using(adp = new SqlDataAdapter(cmd))
{
using(dt = new DataTable())
{
adp.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++ )
{
int notifcount = int.Parse(dt.Rows[i]["notifcount"].ToString());
string modulename = dt.Rows[i]["modulename"].ToString();
string modulebody = modulename + "Body";
string moduleLabel = modulename + "Label";
Label namebox = (Label)module.FindControl(modulename);
if (notifcount > 0)
{
namebox.Visible = true;
namebox.Text = notifcount.ToString();
module.FindControl(modulebody).Visible = true;
try
{
module.FindControl(moduleLabel).Visible = true;
}
catch
{
notifLabel.Visible = false;
}
}
else
{
namebox.Visible = false;
module.FindControl(modulebody).Visible = false;
try
{
module.FindControl(moduleLabel).Visible = false;
}
catch
{
notifLabel.Visible = false;
}
}
}
}
}
con.Close();
}
}
}
internal void notificationSystemREXS(string fullname, string hide_user, HomePage modulename)
{
systemNotificationREXS(modulename);
}
Code to linked on homepage:
private void systemNotificationREXS()
{
Notification moduleacc = new Notification();
moduleacc.notificationSystemREXS(userfullname.Text, Hide_user.Text, this);
}
Your method does very simple job, but you have made it complicated and over dependent on the module and other stuff.
The method should return only the notification data for the user and let the caller of the method to decide what to do with the data.
Consider doing following.
public class NotificationData
{
public int NotificationCount {get;set;}
public int ModuleName {get;set;}
}
public class NotificationService
{
public static List<NotificationData> GetNotificationData(string username)
{
var notificationList = new List<NotificationData>();
using (con = new SqlConnection(EXCUSESLPCON))
{
using (cmd = new SqlCommand("SYSTEMNOTIFICATIONEXSLIP", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#userfullname", Fullname.Text);
con.Open();
using(adp = new SqlDataAdapter(cmd))
{
using(dt = new DataTable())
{
for (int i = 0; i < dt.Rows.Count; i++ )
{
var notification = new NotificationData();
notification.NotificationCount = int.Parse(dt.Rows[i]["notifcount"].ToString());
notification.ModuleName = dt.Rows[i]["modulename"].ToString();
}
}
}
}
}
return notificationList
}
}
Now you should use this method from whichever page you want as following.
Let say you want to use it from HomePage. So you may write following code in Page_Load event of HomePage. (I am assuming here that HomePage is a web page and it has all the controls loaded before this code gets executed).
Label userNameLabel = (Label)this.FindControl("userfullname");
var userName = userNameLabelText;
var notificationList = NotificationService.GetNotificationData(userName);
foreach(var notification in notificationList)
{
var modulename = notification.ModuleName;
var notifcount = notification.Count;
string modulebody = modulename + "Body";
string moduleLabel = modulename + "Label";
Label namebox = (Label)this.FindControl(modulename);
if (notifcount > 0)
{
namebox.Visible = true;
namebox.Text = notifcount.ToString();
this.FindControl(modulebody).Visible = true;
try
{
this.FindControl(moduleLabel).Visible = true;
}
catch
{
notifLabel.Visible = false;
}
}
else
{
namebox.Visible = false;
this.FindControl(modulebody).Visible = false;
try
{
this.FindControl(moduleLabel).Visible = false;
}
catch
{
notifLabel.Visible = false;
}
}
}
I hope this should help you resolve your issue.
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);
}
}
I have now solved this issue. I have left the original question / code in place for comparison.
* SOLUTION *
public static void saveUserData(string emailAddress) {
ParseObject userData = new ParseObject("userData");
ParseObject userLevelData = new ParseObject("levelData");
userData["playerName"] = emailAddress;
try {
ParseQuery<ParseObject> parseData = ParseObject.GetQuery("userData").WhereEqualTo("playerName", userData["playerName"]);
parseData.FirstAsync().ContinueWith(t => {
if(t.IsFaulted) {
userData["level"] = GameStatus.currentUser.level;
userData["highestLevel"] = GameStatus.currentUser.highestLevel;
userData["currentLevelTime"] = GameStatus.currentUser.currentLevelTime;
userData["version"] = UserData.currentUserDataVersion;
userLevelData["level"] = GameStatus.currentUser.level;
userLevelData["playerName"] = emailAddress;
userLevelData["date"] = DateTime.Now;
userLevelData["time"] = -1;
userData.SaveAsync();
userLevelData.SaveAsync();
} else if(!t.IsCanceled) {
userData = t.Result;
try {
userData.SaveAsync().ContinueWith(t2 => {
userData["level"] = GameStatus.currentUser.level;
userData["highestLevel"] = GameStatus.currentUser.highestLevel;
userData["currentLevelTime"] = GameStatus.currentUser.currentLevelTime;
userData["version"] = UserData.currentUserDataVersion;
ParseQuery<ParseObject> levelData = ParseObject.GetQuery("levelData").WhereEqualTo("playerName", userData["playerName"]).WhereEqualTo("level", GameStatus.currentUser.level);
levelData.FirstAsync().ContinueWith(t3 => {
if(t3.IsFaulted) {
userLevelData["level"] = userData["level"];
userLevelData["playerName"] = emailAddress;
userLevelData["date"] = DateTime.Now;
userLevelData["time"] = GameStatus.currentUser.currentLevelData.time;
userLevelData.SaveAsync();
} else if(!t3.IsCanceled) {
userLevelData = t3.Result;
int timeVal = Convert.ToInt32(userLevelData["time"]);
if(timeVal == -1 || GameStatus.currentUser.currentLevelData.time < timeVal) {
try {
userLevelData.SaveAsync().ContinueWith(t4 => {
userLevelData["date"] = DateTime.Now;
userLevelData["time"] = DateTime.Now.Ticks;
userLevelData.SaveAsync();
});
} catch(Exception e) {
Debug.LogException(e);
}
}
}
});
userData.SaveAsync();
});
} catch(Exception e) {
Debug.LogException(e);
}
}
});
} catch(Exception e) {
Debug.LogException(e);
}
}
I am trying to update data on an existing ParseObject using C# in Unity3D. My code is as follows:
Original code:
public static void saveUserData(string emailAddress) {
ParseObject userData = new ParseObject("userData");
ParseObject userLevelData = new ParseObject("levelData");
userData["playerName"] = emailAddress;
try {
ParseQuery<ParseObject> parseData = ParseObject.GetQuery("userData").WhereEqualTo("playerName", userData["playerName"]);
parseData.FirstAsync().ContinueWith(t => {
if(t.IsFaulted) {
userData["level"] = GameStatus.currentUser.level;
userData["highestLevel"] = GameStatus.currentUser.highestLevel;
userData["currentLevelTime"] = GameStatus.currentUser.currentLevelTime;
userData["version"] = UserData.currentUserDataVersion;
userLevelData["level"] = GameStatus.currentUser.level;
userLevelData["playerName"] = emailAddress;
userLevelData["date"] = DateTime.Now;
userLevelData["time"] = -1;
userData.SaveAsync();
userLevelData.SaveAsync();
} else if(!t.IsCanceled) {
userData = t.Result;
try {
userData.SaveAsync().ContinueWith(t2 => {
userData["level"] = GameStatus.currentUser.level;
userData["highestLevel"] = GameStatus.currentUser.highestLevel;
userData["currentLevelTime"] = GameStatus.currentUser.currentLevelTime;
userData["version"] = UserData.currentUserDataVersion;
ParseQuery<ParseObject> levelData = ParseObject.GetQuery("levelData").WhereEqualTo("playerName", userData["playerName"]).WhereEqualTo("level", GameStatus.currentUser.level);
levelData.FirstAsync().ContinueWith(t3 => {
if(t3.IsFaulted) {
userLevelData["level"] = userData["level"];
userLevelData["playerName"] = emailAddress;
userLevelData["date"] = DateTime.Now;
userLevelData["time"] = GameStatus.currentUser.currentLevelData.time;
userLevelData.SaveAsync();
} else if(!t3.IsCanceled) {
userLevelData = t3.Result;
int timeVal = Convert.ToInt32(userLevelData["time"]);
if(timeVal == -1 || GameStatus.currentUser.currentLevelData.time < timeVal) {
try {
userLevelData.SaveAsync().ContinueWith(t4 => {
userLevelData["date"] = DateTime.Now;
userLevelData["time"] = DateTime.Now.Ticks;
userLevelData.SaveAsync();
});
} catch(Exception e) {
Debug.LogException(e);
}
}
}
});
userData.SaveAsync();
});
} catch(Exception e) {
Debug.LogException(e);
}
}
});
} catch(Exception e) {
Debug.LogException(e);
}
}
Now, I get an output stating the user is found, and creating a user if it's not found works OK. The issue I have is that, although I've specified a userFound bool, the if(userFound) nest is never called.
Can anyone see what I've done (or haven;t done) or am I totally going about this the wrong way?
Any help appreciated.