savechanges() saving one entity and not other - c#

A weird situation has struck me this code was running successfully two days back, but i dont know why its not running as before now :
public static void ChangeStatus(int sessionID, int? participantID, Guid? temporaryParticipantID, int statustypeID)
{
using (EMSEntities entities = new EMSEntities())
using (TransactionScope ts = new TransactionScope())
{
try
{
SessionParticipant sessionParticipant = null;
CurrentSessionSeatsStatu sessionCurrentStatus = null;
if (participantID != null)
{
sessionParticipant = entities.SessionParticipants
.Where(a => a.SessionID == sessionID && a.ParticipantID == participantID)
.FirstOrDefault();
}
else if (temporaryParticipantID != null)
{
sessionParticipant = entities.SessionParticipants
.Where(a => a.SessionID == sessionID && a.TemporaryParticipantID == temporaryParticipantID)
.FirstOrDefault();
}
if (sessionParticipant != null)
{
sessionParticipant.StatusTypeID = statustypeID; // Status Changed here
}
**if (sessionParticipant.StatusTypeID == 2) // verified status
{
sessionCurrentStatus = entities.CurrentSessionSeatsStatus
.Where(a => a.SessionID == sessionID)
.FirstOrDefault();
if (sessionCurrentStatus.SeatsLeft > 0)
{
sessionCurrentStatus.SeatsLeft = sessionCurrentStatus.SeatsLeft - 1;
}
}**
entities.SaveChanges();
ts.Complete();
}
catch (Exception ex)
{
ts.Dispose();
}
}
}
The problem is that changes(in StatusTypeID) for sessionParticipant are not saved in database but sessionCurrentStatus changes are !
no error thrown nothing !
Edit: I have discovered that the change in sessionparticipant is happening in all cases except when the status is changed to verified.
ie. when the other table viz. sessioncurrentstatus is updated in the if block.
That is whenever it goes in this if block(bold in code) the problem takes place.
Finally i found the problem and i think its because of the below code however it would be good if someone can explain the exact reason:
EMS.DAL.DALHelper.AttachAndSaveChanges(sessionParticipant, System.Data.EntityState.Modified); // the position of this code line can be found in the below code
below is the code which called the ChangesStatus method:
protected void ddlStatuses_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < gridViewEvents.VisibleRowCount; i++)
{
if (gridViewEvents.Selection.IsRowSelected(i))
{
EMS.DAL.SessionParticipant sessionParticipant = (EMS.DAL.SessionParticipant)gridViewEvents.GetRow(i);
EMS.DAL.Session session = EMS.DAL.DALHelper.GetSessionById(sessionParticipant.SessionID);
EMS.DAL.DALHelper.ChangeStatus(sessionParticipant.SessionID, sessionParticipant.ParticipantID, sessionParticipant.TemporaryParticipantID, Convert.ToInt32(ddlStatuses.SelectedItem.Value));
if (ddlStatuses.SelectedItem.Value == "2" || ddlStatuses.SelectedItem.Value == "3") // if accepted or rejected
{
if (ddlStatuses.SelectedItem.Value == "2") // verified/accepted
{
EMS.DAL.DALHelper.SendMail("Congratulations! your participation for " + session.Name + " event has been confirmed.", "", sessionParticipant.Email, "");
// AT THIS POINT THE 'sessionParticipant' did not have the changed status which was set in the ChangeStatus method
sessionParticipant.IsNotified = true;
EMS.DAL.DALHelper.AttachAndSaveChanges(sessionParticipant, System.Data.EntityState.Modified); // culprit as per me
List<EMS.DAL.SessionAttendanceList> attendanceList = EMS.DAL.DALHelper.GetSessionAttendanceList(session.ID);
attendanceList.ForEach(a =>
{
EMS.DAL.AttendanceListDetail attendanceListDetail = a.AttendanceListDetails.Where(p => p.ParticipantID == sessionParticipant.ParticipantID).FirstOrDefault();
if (attendanceListDetail == null)
{
attendanceListDetail.AttendanceListID = a.ID;
attendanceListDetail.ParticipantID = sessionParticipant.ParticipantID.Value;
attendanceListDetail.IsPresent = false;
EMS.DAL.DALHelper.AttachAndSaveChanges(attendanceListDetail, System.Data.EntityState.Added);
}
});
}
else if (ddlStatuses.SelectedItem.Value == "3") // denied/rejected
{
EMS.DAL.DALHelper.SendMail("Your participation for " + session.Name + " event has been denied.", "", sessionParticipant.Email, "");
sessionParticipant.IsNotified = true;
EMS.DAL.DALHelper.AttachAndSaveChanges(sessionParticipant, System.Data.EntityState.Modified);
List<EMS.DAL.SessionAttendanceList> attendanceList = EMS.DAL.DALHelper.GetSessionAttendanceList(session.ID);
attendanceList.ForEach(a =>
{
EMS.DAL.AttendanceListDetail attendanceListDetail = a.AttendanceListDetails.Where(p => p.ParticipantID == sessionParticipant.ParticipantID).FirstOrDefault();
if (attendanceListDetail != null)
{
EMS.DAL.DALHelper.AttachAndSaveChanges(attendanceListDetail, System.Data.EntityState.Deleted);
}
});
}
}
else
{
List<EMS.DAL.SessionAttendanceList> attendanceList = EMS.DAL.DALHelper.GetSessionAttendanceList(session.ID);
attendanceList.ForEach(a =>
{
EMS.DAL.AttendanceListDetail attendanceListDetail = a.AttendanceListDetails.Where(p => p.ParticipantID == sessionParticipant.ParticipantID).FirstOrDefault();
if (attendanceListDetail != null)
{
EMS.DAL.DALHelper.DeleteAttendanceListDetail(attendanceListDetail);
}
});
attendanceList.ForEach(a =>
{
EMS.DAL.DALHelper.DeleteSessionAttendanceList(a);
});
}
}
}
gridViewEvents.DataBind();
RefreshSeats();
}

Related

A second operation started on this context before a previous asynchronous

hai im new on c# actually i have an issue with my code which i couldnt find the error. I making a controller which i can see the details that user sumbit. When im debug it say that " Use 'await' to ensure that any asynchronous operations". i try to put await every each of line but doesnt working.
plus in my cases i dont use for each method
here is my code :-
public async Task<ActionResult> Details(int id, string currentFilter)
{
try
{
BizRepMaster bizRepmaster = _bizRepMasterService.Find(id);
if (bizRepmaster.RepCountry != null)
ViewBag.BizCountry = _countryMasterService.Find(bizRepmaster.RepCountry).tCountry;
else
ViewBag.BizCountry = "";
if (bizRepmaster.RepState == null)
{
ViewBag.State = "";
}
else
{
if (bizRepmaster.RepState == "Oth")
{
ViewBag.State = "Others";
}
else
{
ViewBag.State = GetStateName(bizRepmaster.RepCountry, bizRepmaster.RepState);
}
}
if (bizRepmaster.MailState == null)
{
ViewBag.MailState = "";
}
else
{
if (bizRepmaster.RepState == "Oth")
{
ViewBag.MailState = "Others";
}
else
{
ViewBag.MailState = GetBizStateName(bizRepmaster.RepCountry, bizRepmaster.MailState);
}
}
ViewBag.AMNationality = _countryMasterService.GetCountryMaster()
.Where(a => a.tISO == bizRepmaster.RepNationality).Single().tCountry;
ViewBag.AMIdType = _idTypeService.GetIdTypes()
.Where(a => a.TypeID == bizRepmaster.RepIdType).Single().LabelName;
if (bizRepmaster.DialCode != null)
{
ViewBag.DialCode = _unitOfWorkAsync.Repository<Country>().Find(bizRepmaster.DialCode).tDialCode;
}
if (bizRepmaster.NatureOfBusiness != null)
{
}
ViewBag.AMResType = _unitOfWorkAsync.Repository<ResidencyType>().Find(bizRepmaster.RepResidencyType).LabelName;
ViewBag.AMJobType = _unitOfWorkAsync.Repository<SenderJobType>().Find(bizRepmaster.RepJobType).LabelName;
ViewBag.StateList = new SelectList(_stateService.GetStates(), "nId", "tStateDesc");
if (bizRepmaster.IdType != null)
ViewBag.IdTypeList = _idTypeService.Find(Convert.ToInt32(bizRepmaster.RepIdType)).LabelName;
ViewBag.CreatedUserName = _userProfileService.GetUserProfile().Where(a => a.UserID == Convert.ToInt32(bizRepmaster.CreatedBy)).Single().LoginId;
if (bizRepmaster.ApprovedBy != null)
{
ViewBag.ApprovedUserName = _userProfileService.GetUserProfile().Where(a => a.UserID == Convert.ToInt32(bizRepmaster.ApprovedBy)).Single().LoginId;
}
if (bizRepmaster.LastUpdatedBy != null)
{
ViewBag.LastUpdatedName = _userProfileService.GetUserProfile().Where(a => a.UserID == Convert.ToInt32(bizRepmaster.LastUpdatedBy)).Single().LoginId;
}
if (bizRepmaster.LastApprovedBy != null)
{
ViewBag.LastApprovedName = _userProfileService.GetUserProfile().Where(a => a.UserID == Convert.ToInt32(bizRepmaster.LastApprovedBy)).Single().LoginId;
}
ViewBag.SenderId1 = bizRepmaster.SenderId;
return View("_BizRepDetails", bizRepmaster);
}
catch (Exception ex)
{
return PartialView("_ErrorMessageView");
}
}

How to fill entry with missing when nothing was writte in in xamarin app?

I am doing Import page and if user leave some entry blank and click on import button I want to fill blank entries with Missing. I have tried that like this:
if (liveryEntry.Text == null)
{
liveryEntry.Text = "Missing";
}
if (registrationEntry.Text == null)
{
registrationEntry.Text = "Missing";
}
if (airportEntry == null)
{
airportEntry.Text = "Missing";
}
if (commentEntry == null)
{
commentEntry.Text = "Missing";
}
But sometimes it works and fill it with Missing, sometimes it doesnt work. What is wrong or is there another way to do that?
Here is full code of method:
private async void buttonImport_Clicked(object sender, EventArgs e)
{
var db = new SQLiteConnection(_dbPath);
db.CreateTable<Airplane>();
collectionPlane.IsVisible = false;
collectionAirline.IsVisible = false;
collectionLivery.IsVisible = false;
collectionRegistration.IsVisible = false;
collectionAirport.IsVisible = false;
try
{
if (liveryEntry.Text == null)
{
liveryEntry.Text = "Missing";
}
if (registrationEntry.Text == null)
{
registrationEntry.Text = "Missing";
}
if (airportEntry == null)
{
airportEntry.Text = "Missing";
}
if (commentEntry == null)
{
commentEntry.Text = "Missing";
}
if (planeEntry.Text != null && airlineEntry.Text != null)
{
var url = PhotoPick();
int i = 1;
int same = 0;
string fileName = registrationEntry.Text;
for (int b = 1; b <= GetNumberPhotos(); b++)
{
if (db.Table<Airplane>().FirstOrDefault(d => d.Id == b) != null)
{
var rowData = db.Table<Airplane>().FirstOrDefault(d => d.Id == b);
string match = rowData.Registration;
if (fileName == match)
{
same++;
}
}
}
i = 1 + same;
fileName = registrationEntry.Text + "-" + i;
var thumbUrl = CreateThumbnail(await url, fileName);
var maxPK = db.Table<Airplane>().OrderByDescending(c => c.Id).FirstOrDefault();
Airplane airplane = new Airplane()
{
Id = (maxPK == null ? 1 : maxPK.Id + 1),
SearchId = planeEntry.Text + airlineEntry.Text + liveryEntry.Text + registrationEntry.Text + airportEntry.Text + datePicker.Date.ToString() + commentEntry.Text,
Plane = planeEntry.Text.ToUpper(),
Airline = airlineEntry.Text,
Livery = liveryEntry.Text,
Registration = registrationEntry.Text.ToUpper(),
Airport = airportEntry.Text.ToUpper(),
Date = datePicker.Date,
Comment = commentEntry.Text,
Url = await url,
ThumbnailUrl = thumbUrl
};
db.Insert(airplane);
await DisplayAlert("Saved", planeEntry.Text + " of " + airlineEntry.Text + " is saved.", "OK");
planeEntry.Text = "";
airlineEntry.Text = "";
liveryEntry.Text = "";
registrationEntry.Text = "";
airportEntry.Text = "";
commentEntry.Text = "";
}
else
await DisplayAlert("Fill all needed fields", "You have to fill all fields except livery and comment", "OK");
}
catch
{
await DisplayAlert("Error", "Something went wrong", "Try again");
}
}
It is probably some kind of bug or missunderstanding #Cfun have solved with if ( string.IsNullOrEmpty(liveryEntry.Text)) and it works as expected.

WPF, C# TPL AggregateException never fired

I am trying to develop a small application with WPF, C#. I encountered a problem when trying to use the library TPL, especially exception handling. The problem is that AggregateException is never captured, and the program displays an exception in the method I passed as a task. here's my code. I removed unnecessary code :
private void RefreshOldDossierFinancementCommandExecute(KeyEventArgs e)
{
bool processIt = false;
if (e != null && e.Key == Key.Enter)
processIt = true;
if (e == null || processIt == true)
{
TaskInProgress = true;
SBMessage = "Query In progress...";
var uischeduler = TaskScheduler.FromCurrentSynchronizationContext();
var refreshold = Task.Factory.StartNew(() =>
RefreshOldDossierFinancement(DossierFinancementEnteredKey));
refreshold.ContinueWith(task => { TaskInProgress = false; },
CancellationToken.None,
TaskContinuationOptions.NotOnFaulted, uischeduler);
try
{
refreshold.Wait();
}
catch (AggregateException aex) //This Exception is never fired
{
Messenger.Default.Send(new ExceptionMessageRefresh(aex), "DossierFinancement");
}
}
}
private void RefreshOldDossierFinancement(long dfId)
{
TotalContrats = 0.000M;
TotalMefs = 0.000M;
TotalCommandes = 0.000M;
decimal phb = 0.000M;
decimal pctr = 0.000M;
decimal pmef = 0.000M;
PercentageHorsBilan = "(0%)";
PercentageContrats = "(0%)";
PercentageMef = "(0%)";
DossierNumber = "";
using (UnitOfWork cx = new UnitOfWork(_currentLog))
{
// try
{
IDossierFinancementRepository sr = new DossierFinancementRepository(cx, _currentLog);
IDossierFinancementManagementService dfms = new DossierFinancementManagementService(_currentLog, sr);
IDataTraceRepository dtr = new DataTraceRepository(cx, _currentLog);
IDataTraceManagementService dtms = new DataTraceManagementService(_currentLog, dtr);
CurrentDossierFinancement = dfms.FindById(dfId);
//I put this code in comment to force a nullReferenceException exception
/*if (CurrentDossierFinancement == null) //Not Found
Messenger.Default.Send<NotificationMessage>(new NotificationMessage("Dossier Financement n° " + dfId.ToString() + " introuvable."),"DossierFinancementError");
else*/
{
//The debugger stops here with NullRefrenceException Exception
// I want this exception to be captured in AggregateException
DossierFinancementEnteredKey = CurrentDossierFinancement.DossierId;
DossierNumber = "N° " + DossierFinancementEnteredKey.ToString();
RequestNature = (CurrentDossierFinancement.InvestmentGoal == 0) ? "Création" : (CurrentDossierFinancement.InvestmentGoal == 1) ? "Renouvellement" : "Extension";
EtatDossier = (CurrentDossierFinancement.Status == 1) ? "En cours" : (CurrentDossierFinancement.Status == 2) ? "Approuvé" : "Rejeté";
if (CurrentDossierFinancement.ClientId != null)
{
CustomerCode = (long)CurrentDossierFinancement.ClientId;
CustomerName = CurrentDossierFinancement.Client.NomCli;
}
else
{
CustomerCode = 0;
if (CurrentDossierFinancement.ClientType == 1)
CustomerName = CurrentDossierFinancement.Name + " " + CurrentDossierFinancement.FirstName;
else
CustomerName = CurrentDossierFinancement.CompanyName;
}
if (CurrentDossierFinancement.Contrat != null)
{
TotalContrats = CurrentDossierFinancement.Contrat.Montant;
TotalHorsBilan = CurrentDossierFinancement.Contrat.Montant;
pctr = Math.Round((TotalContrats / CurrentDossierFinancement.Montant) * 100, 0);
PercentageContrats = "(" + pctr.ToString() + "%)";
if (CurrentDossierFinancement.Contrat.Mefs != null)
{
TotalMefs = CurrentDossierFinancement.Contrat.Mefs.Sum(x => x.Montant);
pmef = Math.Round((TotalMefs / CurrentDossierFinancement.Montant) * 100, 0);
PercentageMef = "(" + pmef.ToString() + "%)";
}
TotalHorsBilan = TotalContrats - TotalMefs;
phb = Math.Round((TotalHorsBilan / CurrentDossierFinancement.Montant) * 100, 0);
PercentageHorsBilan = "(" + phb.ToString() + "%)";
}
//Extraire la trace
List<DataTrace> traceList = dtms.GetTrace(DossierFinancementEnteredKey, "DossierFinancement").ToList();
DataTrace newRecord = traceList.Where(xx => string.Equals(xx.ActionLib, "New", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
if (newRecord != null)
{
CreatedBy = newRecord.Coduser;
CreatedAt = newRecord.ActionDate.ToString();
}
}
}
/*
catch (Exception ex)
{
throw ex;
}*/
}
}
I tested the following code and it still doesn't work :
Task.Run(() =>
{
RefreshOldDossierFinancement(DossierFinancementEnteredKey);
}
catch (AggregateException aex)
{
Messenger.Default.Send(new ExceptionMessageRefresh(aex), "DossierFinancement");
}}).ContinueWith(task => { TaskInProgress = false; },
CancellationToken.None,
TaskContinuationOptions.NotOnFaulted, uischeduler
);
A simpler approach to using continuations is to use async-await. When we execute a delegate using Task.Run, and want to asynchronously wait for it's completion, we can await it:
private async void RefreshOldDossierFinancementCommandExecute(KeyEventArgs e)
{
bool processIt = false;
if (e != null && e.Key == Key.Enter)
processIt = true;
if (!processIt)
return;
TaskInProgress = true;
SBMessage = "Query In progress...";
try
{
await Task.Run(() => RefreshOldDossierFinancement(DossierFinancementEnteredKey));
}
catch (Exception e)
{
// Do stuff
}
finally
{
TaskInProgress = false;
}
}
This way, you don't need to explicitly capture the SynchronizationContext, and you don't block the UI thread while the operation is on-going.
Finally i found a solution, I dont know if it is the best.
I modified my code as follows :
private void RefreshOldDossierFinancementCommandExecute(KeyEventArgs e)
{
bool processIt = false;
if (e != null && e.Key == Key.Enter)
processIt = true;
if (e == null || processIt == true)
{
TaskInProgress = true;
SBMessage = "Query in progress...";
var uischeduler = TaskScheduler.FromCurrentSynchronizationContext();
Task.Run(() =>
{
RefreshOldDossierFinancement(DossierFinancementEnteredKey);
}).ContinueWith(task => { TaskInProgress = false; },
CancellationToken.None,
TaskContinuationOptions.NotOnFaulted, uischeduler);
}
}
and i capture the exception in RefreshOldDossierFinancement Method. The trick lies to add a Dispatch.BeginInvoke in code behind of the window.
Here The code of RefreshOldDossierFinancement Method :
private void RefreshOldDossierFinancement(long dfId)
{
TotalContrats = 0.000M;
TotalMefs = 0.000M;
TotalCommandes = 0.000M;
decimal phb = 0.000M;
decimal pctr = 0.000M;
decimal pmef = 0.000M;
PercentageHorsBilan = "(0%)";
PercentageContrats = "(0%)";
PercentageMef = "(0%)";
DossierNumber = "";
using (UnitOfWork cx = new UnitOfWork(_currentLog))
{
try
{
IDossierFinancementRepository sr = new DossierFinancementRepository(cx, _currentLog);
IDossierFinancementManagementService dfms = new DossierFinancementManagementService(_currentLog, sr);
IDataTraceRepository dtr = new DataTraceRepository(cx, _currentLog);
IDataTraceManagementService dtms = new DataTraceManagementService(_currentLog, dtr);
CurrentDossierFinancement = dfms.FindById(dfId);
/*if (CurrentDossierFinancement == null) //Not Found
Messenger.Default.Send<NotificationMessage>(new NotificationMessage("Dossier Financement n° " + dfId.ToString() + " introuvable."),"DossierFinancementError");
else*/
{
DossierFinancementEnteredKey = CurrentDossierFinancement.DossierId;
DossierNumber = "N° " + DossierFinancementEnteredKey.ToString();
RequestNature = (CurrentDossierFinancement.InvestmentGoal == 0) ? "Création" : (CurrentDossierFinancement.InvestmentGoal == 1) ? "Renouvellement" : "Extension";
EtatDossier = (CurrentDossierFinancement.Status == 1) ? "En cours" : (CurrentDossierFinancement.Status == 2) ? "Approuvé" : "Rejeté";
if (CurrentDossierFinancement.ClientId != null)
{
CustomerCode = (long)CurrentDossierFinancement.ClientId;
CustomerName = CurrentDossierFinancement.Client.NomCli;
}
else
{
CustomerCode = 0;
if (CurrentDossierFinancement.ClientType == 1)
CustomerName = CurrentDossierFinancement.Name + " " + CurrentDossierFinancement.FirstName;
else
CustomerName = CurrentDossierFinancement.CompanyName;
}
if (CurrentDossierFinancement.Contrat != null)
{
TotalContrats = CurrentDossierFinancement.Contrat.Montant;
TotalHorsBilan = CurrentDossierFinancement.Contrat.Montant;
pctr = Math.Round((TotalContrats / CurrentDossierFinancement.Montant) * 100, 0);
PercentageContrats = "(" + pctr.ToString() + "%)";
if (CurrentDossierFinancement.Contrat.Mefs != null)
{
TotalMefs = CurrentDossierFinancement.Contrat.Mefs.Sum(x => x.Montant);
pmef = Math.Round((TotalMefs / CurrentDossierFinancement.Montant) * 100, 0);
PercentageMef = "(" + pmef.ToString() + "%)";
}
TotalHorsBilan = TotalContrats - TotalMefs;
phb = Math.Round((TotalHorsBilan / CurrentDossierFinancement.Montant) * 100, 0);
PercentageHorsBilan = "(" + phb.ToString() + "%)";
}
//Extraire la trace
List<DataTrace> traceList = dtms.GetTrace(DossierFinancementEnteredKey, "DossierFinancement").ToList();
DataTrace newRecord = traceList.Where(xx => string.Equals(xx.ActionLib, "New", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
if (newRecord != null)
{
CreatedBy = newRecord.Coduser;
CreatedAt = newRecord.ActionDate.ToString();
}
}
}
catch (Exception ex)
{
//Here i send a message to Window to display The Exception Message in a custom Dialog
Messenger.Default.Send(new ExceptionMessageRefresh(ex), "DossierFinancement");
}
}
}
And finally here The code Behind of The window :
public partial class Dossier : Window
{
public Dossier()
{
InitializeComponent();
Messenger.Default.Register<ExitMessage>(this, "DossierFinancement", (action) => CloseWindow(action));
Messenger.Default.Register<ExceptionMessageRefresh>(this, "DossierFinancement", (action) => ShowExceptionMessage(action));
Messenger.Default.Register<NotificationMessage>(this, "DossierFinancementInfo", (action) => ProcessNotification(action));
Messenger.Default.Register<NotificationMessage>(this, "DossierFinancementError", (action) => ProcessErrorDialogNotification(action));
}
private void ProcessNotification(NotificationMessage action)
{
MessageBox.Show(action.Notification.ToString(), "Information", MessageBoxButton.OK,MessageBoxImage.Information);
}
private void ProcessErrorDialogNotification(NotificationMessage action)
{
MessageBox.Show(action.Notification.ToString(), "Erreur", MessageBoxButton.OK, MessageBoxImage.Error);
}
private void CloseWindow(ExitMessage action)
{
this.Close();
Messenger.Default.Unregister<ExitMessage>(this, "DossierFinancement");
}
private void ShowExceptionMessage(ExceptionMessageRefresh obj)
{
//Without the following Call of Dispatcher, An exception "Thread must be STA... will be fired
Dispatcher.BeginInvoke(new Action(() =>
{
UICommon.ShowErrorMessage(obj.ExceptionToRefresh);
}));
}
}
and that's all.
Thanks.

OutOfMemory Exception for Parallel.ForEach

I have a console application which runs as 32 bit process(we cant change it to 64 bit) and is throwing Out of memory Exception. We traced minor Memory leak(related to Entity Framework repository) in a downstream process but with that too application should not cross 2 GB memory.
One thing i want to understand is sometimes application processes 2500 records while other times it fails at 100.(Server memory utilization is under 60% when this application is running
I am using Parallel.forEach and controlling number of threads to 4 using ParallelOptions. Can anybody suggest making the application on a single thread may by any chance resolve the problem.
(The application didn't fail in any lower environment but only in production and giving us a very hard time).
Below is the code snippet.
Thanks In Advance,
Rohit
protected override void Execute(IEnumerable<PlanPremiumDetails> argument)
{
if (argument.Any())
{
var EnrollmentRequests = argument.GroupBy(c => c.CaseNumber).ToList();
SelectedPlanPremiumDetails request;
EnrollmentResponse enrollmentResponse;
bool taskStatus;
Common.Status.TotalAutoEnrollRecords = EnrollmentRequests.Count;
Common.StartTimer();
Action<IGrouping<int,PlanPremiumDetails>> processRequest = eRequest =>
{
int caseNumber;
List<EnrolledIndividual> enrolledIndividuals;
try
{
string errorMessage;
caseNumber = eRequest.Key;
if (eRequest.Any(f => f.FailedMCOEnrollmentId > 0))
{
request = FailedMcoRequest(eRequest, caseNumber);
enrollmentResponse = InvokeEnrollment(request);
if (enrollmentResponse.OverallStatus == false && enrollmentResponse.ErrorInformationMA != null)
{
StringBuilder messages = new StringBuilder();
if (enrollmentResponse.ErrorInformationMA.ErrorInformationPostMcaps != null)
{
messages.Append(enrollmentResponse.ErrorInformationMA.ErrorInformationPostMcaps.Message);
Exception innerExp = enrollmentResponse.ErrorInformationMA.ErrorInformationPostMcaps.InnerException;
if (innerExp != null)
{
// messages.Append(enrollmentResponse.ErrorInformationMA.ErrorInformationPostMcaps.InnerException.Message);
do
{
messages.Append(innerExp.Message);
innerExp = innerExp.InnerException;
}
while (innerExp != null);
}
}
else
{
if (enrollmentResponse.ErrorInformationMA != null && enrollmentResponse.ErrorInformationMA.InnerErrorInfo != null)
{
foreach (var msg in enrollmentResponse.ErrorInformationMA.InnerErrorInfo)
{
messages.Append( string.Format(#"ErrorCode: {0}, ErrorMessage: {1} ",msg.ErrorCode,msg.ErrorMessage));
}
}
}
errorMessage = Convert.ToString(messages);
Common.Errors.Add(new Exception(String.Format(ConfigurationManager.AppSettings["FailedEnrollErrorText"], caseNumber, errorMessage), enrollmentResponse.ErrorInformationMA.ErrorInformationPostMcaps));
taskStatus = GenerateTask(eRequest, caseNumber, false, errorMessage);
if (taskStatus)
{
UpdateTriggerStatus(caseNumber, "Y");
}
else
{
UpdateTriggerStatus(caseNumber, "N");
Common.Errors.Add(new Exception(String.Format(ConfigurationManager.AppSettings["FailedEnrollErrorText"], caseNumber, "Task Creation")));
}
}
else
{
Common.Status.Success = (Common.Status.Success + 1);
UpdateTriggerStatus(caseNumber, "Y");
}
}
else
{
enrolledIndividuals = eRequest.Select(p => new EnrolledIndividual
{
IndividualId = p.IndividualId,
EdgTraceId = p.EdgTraceId,
EDGNumber = p.EDGNumber
}).ToList();
request = new SelectedPlanPremiumDetails()
{
EmployerId = 0,
CaseNumber = caseNumber,
CallBackId = Common.ApplicationName,
SourceSystem = EnrollmentLibrary.SourceSystem.MAAUTOASSIGN,
AutoAssignMCOIndividuals = enrolledIndividuals
};
enrollmentResponse = InvokeEnrollment(request);
if (enrollmentResponse.OverallStatus == false && enrollmentResponse.ErrorInformationMA != null)
{
StringBuilder messages = new StringBuilder();
if (enrollmentResponse.ErrorInformationMA.ErrorInformationPostMcaps != null)
{
messages.Append(enrollmentResponse.ErrorInformationMA.ErrorInformationPostMcaps.Message);
Exception innerExp = enrollmentResponse.ErrorInformationMA.ErrorInformationPostMcaps.InnerException;
if (innerExp != null)
{
// messages.Append(enrollmentResponse.ErrorInformationMA.ErrorInformationPostMcaps.InnerException.Message);
do
{
messages.Append(innerExp.Message);
innerExp = innerExp.InnerException;
}
while (innerExp != null);
}
}
else
{
if (enrollmentResponse.ErrorInformationMA != null && enrollmentResponse.ErrorInformationMA.InnerErrorInfo.Count != null)
{
foreach (var msg in enrollmentResponse.ErrorInformationMA.InnerErrorInfo)
{
messages.Append(string.Format(#"ErrorCode: {0}, ErrorMessage: {1} ", msg.ErrorCode, msg.ErrorMessage));
}
}
}
errorMessage = Convert.ToString(messages);
Common.Errors.Add(new Exception(String.Format(ConfigurationManager.AppSettings["AutoEnrollErrorText"], caseNumber, errorMessage), enrollmentResponse.ErrorInformationMA.ErrorInformationPostMcaps));
}
else
{
// Update status to be saved in InterfaceSummary table.
Common.Status.Success = (Common.Status.Success + 1);
}
}
}
catch(Exception ex)
{
Common.Errors.Add(new Exception(String.Format(ConfigurationManager.AppSettings["AutoEnrollErrorText"], eRequest.Key, ex.Message), ex));
}
};
}
int dParallelism = Convert.ToInt32(ConfigurationManager.AppSettings["DegreeofParallelism"]);
Parallel.ForEach(EnrollmentRequests,
new ParallelOptions() { MaxDegreeOfParallelism = dParallelism > 0 ? dParallelism : 1 },
processRequest);

LinQ datasource showing this error "LinqDataSource 'AirAsiaDC' has no values to insert. Check that the 'values' dictionary contains values"

here is what i am trying to do, i am using LinQ data context to insert new record to database,
for some reason, my linq showing this error "LinqDataSource 'AirAsiaDC' has no values to insert. Check that the 'values' dictionary contains values." weird part, when i check the record which i tried to insert before, it is there. what i do wrong here?
by the way, here is my code :
protected void DetailsView1_ItemCommand(object sender,
DetailsViewCommandEventArgs e)
{
AirAsiaDCDataContext Linq = new AirAsiaDCDataContext();
try
{
if (e.CommandName == "Edit")
{
TextBox tbname = (TextBox)DetailsView1.FindControl("DeptName");
department dpt;
if ((tbname.Text != null) && (tbname.Text != ""))
{
dpt = Linq.departments.Single(d => d.departmentcode == code);
dpt.departmentname = tbname.Text;
dpt.updateby = "hendra";
dpt.lastupdate = DateTime.Now;
Linq.SubmitChanges();
Response.Redirect("Department.aspx");
}
else
{
divError.Visible = true;
lblError.Text = "Department name can not be empty";
}
}
else if (e.CommandName == "Insert")
{
TextBox tbcode = (TextBox)DetailsView1.FindControl("DeptCode");
TextBox tbname = (TextBox)DetailsView1.FindControl("DeptName");
department dpt = new department();
if (((tbcode.Text != null) && (tbcode.Text != ""))
&& ((tbname.Text != null) && (tbname.Text != "")))
{
dpt.departmentcode = tbcode.Text;
dpt.departmentname = tbname.Text;
dpt.createby = "hendra";
dpt.createdate = DateTime.Now;
dpt.updateby = "hendra";
dpt.lastupdate = DateTime.Now;
Linq.departments.InsertOnSubmit(dpt);
Linq.SubmitChanges();
}
else if ((tbcode.Text == null) || (tbcode.Text == ""))
{
divError.Visible = true;
lblError.Text = "Department code can not be empty";
}
else if ((tbname.Text == null) || (tbname.Text == ""))
{
divError.Visible = true;
lblError.Text = "Department name can not be empty";
}
}
}
catch (Exception ex)
{
divError.Visible = true;
lblError.Text = ex.Message.ToString();
}
}
i even try to use try and catch but get nothing, and my linq keep on showing that error and throw me to error screen.

Categories

Resources