Getting Stackoverflow exception when executing LINQ IQueryable method - c#

When running this code it's getting stackoverflow exception like this
An unhandled exception of type 'System.StackOverflowException'
occurred in mscorlib.dll
private IQueryable<KontratMasraflari> SKontratMasraflari()
{
var _kontratlar = SKontrat().ToList();//IQueryable Method
List<KontratMasraflari> _tumMasraflar = new List<KontratMasraflari>();
foreach (var kontrat in _kontratlar)
{
var _masraf = db.KontratMasraflaris.Where(x => x.KontratID == kontrat.ID).SingleOrDefault();
if (_masraf == null)
_tumMasraflar.Add(new KontratMasraflari()
{
KontratID = kontrat.ID
});
else
_tumMasraflar.Add(_masraf);
}
var _result = PredicateBuilder.True<KontratMasraflari>();
_result = _result.And(x => x.Silindi == 0);
if (txtFirmaTuru.Text != string.Empty)
_result = _result.And(x => x.FirmaTuru == txtFirmaTuru.Text);
if (txtBelgeNo.Text != string.Empty)
_result = _result.And(x => x.BelgeNumarasi == txtBelgeNo.Text);
if (txtMasraf.Text != string.Empty)
_result = _result.And(x => x.Masraf == txtMasraf.Text);
if (txtGelirGider.Text != string.Empty)
_result = _result.And(x => x.GelirGider == txtGelirGider.Text);
//var _return = db.KontratMasraflaris.Where(_result);
return _tumMasraflar.AsQueryable().Where(_result);;
}

I would use LINQ to create the List and then just use regular IQueryable Where:
private IQueryable<KontratMasraflari> SKontratMasraflari() {
var _kontratlar = SKontrat().ToList();//IQueryable Method
var _tumMasraflar = SKontrat.GroupJoin(db.KontratMasraflaris, sk => sk.ID, km => km.KontratID, (sk, kmg) => kmg.Any() ? kmg.Single() : new KontratMasraflari { KontratID = sk.ID }).ToList();
var _result = _tumMasraflar.Where(x => x.Silindi == 0);
if (txtFirmaTuru.Text != string.Empty)
_result = _result.Where(x => x.FirmaTuru == txtFirmaTuru.Text);
if (txtBelgeNo.Text != string.Empty)
_result = _result.Where(x => x.BelgeNumarasi == txtBelgeNo.Text);
if (txtMasraf.Text != string.Empty)
_result = _result.Where(x => x.Masraf == txtMasraf.Text);
if (txtGelirGider.Text != string.Empty)
_result = _result.Where(x => x.GelirGider == txtGelirGider.Text);
//var _return = db.KontratMasraflaris.Where(_result);
return _result;
}

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 can we stream through multiple files

In my case after checking one XML file the method will go in to if or else condition where it will check another XML file
so How we can stream through multiple files? below is the code of class file.
public override void Execute(IParserContext context)
{
_context = context;
foreach (var file in context.Files)
{
try
{
IParserFile childFile;
String clusterName;
Cluster cluster = null;
List<string> devices = GetDeviceNames(file);
foreach (string device in devices)
{
childFile = file.Children.Where(x => x.FileName.StartsWith("GetSplitterStates", StringComparison.InvariantCultureIgnoreCase) && x.FullPath.Contains("RECOVERPOINT\\" + device)).FirstOrDefault();
var isRp4vm = CheckIfRP4VM(childFile);
if (!isRp4vm.HasValue)
{
file.Log.Message((int)ErrorCodes.FailClusterIdentification);
continue;
}
if (isRp4vm.HasValue && isRp4vm.Value == true)
{
clusterName = "RP4VM";
childFile = file.Children.Where(x => x.FileName.StartsWith("GetSystemSettings", StringComparison.InvariantCultureIgnoreCase) && x.FullPath.Contains("RECOVERPOINT\\" + device)).FirstOrDefault();
cluster = ParseSystemSettingsByDevice(childFile, device);
if (cluster == null)
{
file.Log.Message((int)ErrorCodes.FailClusterName);
continue;
}
childFile = file.Children.Where(x => x.FileName.StartsWith("GetMonitoredParameters", StringComparison.InvariantCultureIgnoreCase) && x.FullPath.Contains("RECOVERPOINT\\" + device)).FirstOrDefault();
ParseMonitoredParameters(childFile);
}
else
{
childFile = file.Children.Where(x => x.FileName.StartsWith("GetLocalCluster", StringComparison.InvariantCultureIgnoreCase)
&& x.FullPath.Contains("RECOVERPOINT\\" + device, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
clusterName = ParseLocalCluster(childFile);
if (clusterName == null)
{
file.Log.Message((int)ErrorCodes.FailClusterName);
continue; //Skip the device of we can't get the cluster name.
}
childFile = file.Children.Where(x => x.FileName.StartsWith("GetSystemSettings", StringComparison.InvariantCultureIgnoreCase) && x.FullPath.Contains("RECOVERPOINT\\" + device)).FirstOrDefault();
cluster = ParseSystemSettingsByClusterName(childFile, clusterName);
if (cluster == null)
{
file.Log.Message((int)ErrorCodes.FailClusterParsing);
continue; //Skip the device of we can't get the cluster info.
}
childFile = file.Children.Where(x => x.FileName.StartsWith("GetGroupVolumes", StringComparison.InvariantCultureIgnoreCase) && x.FullPath.Contains("RECOVERPOINT\\" + device)).FirstOrDefault();
ParseGroupVolumes(childFile, cluster);
childFile = file.Children.Where(x => x.FileName.StartsWith("GetSANVolumes", StringComparison.InvariantCultureIgnoreCase) && x.FullPath.Contains("RECOVERPOINT\\" + device)).FirstOrDefault();
ParseSANVolumes(childFile, cluster);
}
childFile = file.Children.Where(x => x.FileName.StartsWith("GetSystemReport", StringComparison.InvariantCultureIgnoreCase) && x.FullPath.Contains("RECOVERPOINT\\" + device)).FirstOrDefault();
ParseSystemReport(childFile, cluster);
}
}
catch (Exception ex)
{
file.Log.Message((int)ErrorCodes.ExecuteErrorMessage);
file.Log.Error(file.FileName, ex);
}
}
}
i am able to execute only one method
CheckIfRP4VM. after this method i want to go in to any of the condition to check other files.
how we can achieve that? below is my test class
[Test]
public void Processfile_GetSplitterStatesXML()
{
Mock<IParserContext> mockIParserContext = new Mock<IParserContext>();
Mock<IParserFile> mockIParserChildFile = new Mock<IParserFile>();
Mock<IDictionary<string, string>> mockIDictionary = new Mock<IDictionary<string, string>>();
Mock<IParserLog> mockIParserChildLog = new Mock<IParserLog>();
TestUtility utility = new TestUtility();
string serverFileName = "GetSplitterStates";
string serverFileExtension = ".xml";
string serverFileNameWithExtension = serverFileName + serverFileExtension;
string relativeFilePath = #"\SampleTestFiles\XML\RecoverPointParser\STORAGE\RECOVERPOINT\splitters\" + serverFileNameWithExtension;
string absoluteFilePath = utility.getExecutionAssemblyLocation() + relativeFilePath;
Stream stream = utility.getFileStream(relativeFilePath);
IList<IParserFile> parserFiles = new List<IParserFile>() { };
mockIParserChildFile.Setup(x => x.Guid).Returns(new Guid());
mockIParserChildFile.Setup(x => x.FullPath).Returns(absoluteFilePath);
mockIParserChildFile.Setup(x => x.FileName).Returns(serverFileNameWithExtension);
mockIParserChildFile.Setup(x => x.Extension).Returns(serverFileExtension);
mockIParserChildFile.Setup(x => x.SizeInBytes).Returns(2);
mockIParserChildFile.Setup(x => x.Name).Returns(serverFileName);
mockIParserChildFile.Setup(x => x.ModifiedDateTime).Returns(DateTime.Now);
mockIParserChildFile.Setup(x => x.Children).Returns(parserFiles);
mockIParserChildFile.Setup(x => x.Properties).Returns(mockIDictionary.Object);
mockIParserChildFile.Setup(x => x.Log).Returns(mockIParserChildLog.Object);
mockIParserChildFile.Setup(x => x.RequestFileId).Returns(1);
mockIParserChildFile.Setup(x => x.Open()).Returns(stream);
parserFiles.Add(mockIParserChildFile.Object);
mockIParserContext.Setup(x => x.Files).Returns(parserFiles);
RecoverPointParser RecoverPointParser = new RecoverPointParser();
RecoverPointParser.Execute(mockIParserContext.Object);
mockIParserChildLog.Verify(x => x.Error(It.IsAny<string>(), It.IsAny<Exception>()), Times.AtLeastOnce);
}
so far i am able to check with one file only. as it has if condition i am unable to do it.

FakeItEasy: How check if param is changed when method is calling?

I have following service method
public async Task<IResultList<IEnrichedContentEntity>> QueryAsync(Context context, string schemaIdOrName, Q q)
{
Guard.NotNull(context, nameof(context));
if (q == null)
{
return EmptyContents;
}
var schema = await GetSchemaOrThrowAsync(context, schemaIdOrName);
var permissionReadOwn = Permissions.ForApp(Permissions.AppContentReadOwn, context.App.Name, schemaIdOrName);
if (context.Permissions.Allows(permissionReadOwn))
{
q.CreatedBy = context.User.Token();
}
using (Profiler.TraceMethod<ContentQueryService>())
{
q = await queryParser.ParseAsync(context, q, schema);
var contents = await contentRepository.QueryAsync(context.App, schema, q, context.Scope());
if (q.Ids != null && q.Ids.Count > 0)
{
contents = contents.SortSet(x => x.Id, q.Ids);
}
return await TransformAsync(context, contents);
}
}
q.CreatedBy must set value if permission is correct.
How can I test if q.CreatedBy is not empty and has correct value.
I implemented following test, but no idea how check this params?
public async Task QueryAll_should_return_own_user_contents(int isFrontend, int unpublished, SearchScope scope)
{
var ctx = CreateContextWithOwnReadPermission(isFrontend: isFrontend == 1, allowSchema: true)
.WithUnpublished(unpublished == 1);
var content = CreateContent(contentId);
var q = Q.Empty.WithReference(DomainId.NewGuid());
A.CallTo(() => contentRepository.QueryAsync(ctx.App, schema, q, scope))
.Returns(ResultList.CreateFrom(5, content));
//A.CallTo(() => contentRepository.QueryAsync(ctx.App, schema, A<Q>.That.Matches(x => x.CreatedBy == null), scope))
// .MustHaveHappened();
//A.CallTo(() => contentRepository.QueryAsync(ctx.App, schema, A<Q>.That.Matches(x => x.CreatedBy == ctx.User.Token()), scope))
// .MustHaveHappened();
//q.CreatedBy = ctx.User.Token();
var result = await sut.QueryAsync(ctx, schemaId.Name, q);
Assert.Equal(contentData, result[0].Data);
Assert.Equal(contentId, result[0].Id);
Assert.Equal(5, result.Total);
}

C# ef second operation started before previous asynchronous operation completed

Just trying to do normal query on ef but getting below error message
"A second operation started on this context before a previous asynchronous operation completed"
I am using await for all aync call but not sure what could be causing this issue.
here' code
var sids = await context.Sites.Where(s => slist.Contains(s.JVSiteID)).ToListAsync();
var header = await context.GenericCsvHeaders.FirstOrDefaultAsync(x => x.Header == csvh) ?? new GenericCsvHeader { Header = csvh };
context.Entry<GenericCsvHeader>(header).State = (header.GenericCsvHeaderID == 0) ? EntityState.Added : EntityState.Unchanged;
var sa = await context.SAs.Where(x => x.StatusID == Data.Enum.Status.Active && mapkeys.Contains(x.SAName)).Select(x => new { x.SAName, x.SACode, x.SAID }).ToListAsync();
if (sa.Count > 0)
sasitelist = await context.Site_SA.Where(x => x.StatusID == Data.Enum.Status.Active && siteids.Contains(x.SiteID ?? 0)).ToListAsync();
var az = await context.Azimuths.Where(x => x.StatusID == Data.Enum.Status.Active && mapkeys.Contains(x.AzimuthName)).Select(x => new { x.AzimuthName, x.AzimuthID }).ToListAsync();
if (az.Count > 0)
azsitelist = await context.Site_Azimuth.Where(x => x.StatusID == Data.Enum.Status.Active && siteids.Contains(x.SiteID ?? 0)).ToListAsync();
var rows = new List<dynamic>(); //getting this list from csv file via csvHelper
foreach (var r in rows)
{
var s = sids.FirstOrDefault(x => x.JVSiteID == (((IDictionary<String, Object>)r)[siteid]).ToString()) ?? new Site();
UpdateSite(s, r, map);
}
private async void UpdateSite(Site site, dynamic csvSite, IDictionary<string, string> map)
{
context.Entry(site).State = (site.StateID == 0) ? EntityState.Added : EntityState.Modified;
site.SiteForAuditTrail = site;
if (map.ContainsKey("SiteName") && !String.IsNullOrWhiteSpace(GetStringOfDynamic(map,csvSite,"SiteName")))
site.SiteName = GetStringOfDynamic(map,csvSite, "SiteName");
if (map.ContainsKey("State") && !String.IsNullOrWhiteSpace(GetStringOfDynamic(map,csvSite, "State")))
{
//getting exception at below line
var state = (await GetRefTypeList<State>(x => x.StateCode == GetStringOfDynamic(map,csvSite, "State"))) ?? new State { StateCode = GetStringOfDynamic(map,csvSite, "State") };
context.Entry(state).State = (state.StateID == 0) ? EntityState.Added : EntityState.Unchanged;
site.State = state;
state.SiteForAuditTrail = site;
}
}
private async Task<T> GetRefTypeList<T>(Func<T, bool> expression) where T : EntityBase
{
if (!refTypes.ContainsKey(typeof(T).Name))
refTypes[typeof(T).Name] = (await context.Set<T>().Where(x => x.StatusID == Data.Enum.Status.Active).ToListAsync());
return (refTypes[typeof(T).Name] as List<T>)?.FirstOrDefault(expression);
}
private string GetStringOfDynamic(IDictionary<string, string> map,dynamic obj, string propertyName)
{
if (((IDictionary<String, Object>)obj).ContainsKey(map[propertyName]))
return (((IDictionary<String, Object>)obj)[map[propertyName]]??"").ToString();
return "";
}
found problem, was missing await when calling UpdateSite
foreach (var r in rows)
{
var s = sids.FirstOrDefault(x => x.JVSiteID == (((IDictionary<String, Object>)r)[siteid]).ToString()) ?? new Site();
**await** UpdateSite(s, r, map);
}
You are having a race condition here. While you are using await you have other code executing potentially before the variable sids, header, sa and az, have been returned.
You should refactor your code so that the remaining code is not executed until these variables are returned. You can do this by using a task and then using the extension WhenAll which will ensure each await has been completed before proceeding. Here is a link to MS docs on Task and WhenAll implementation

savechanges() saving one entity and not other

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

Categories

Resources