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.
Related
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");
}
}
Hi I am using Entity Framework Code First, I have a collection of Entities that need to be saved, but I have my EF Repository created as below
public T Create(T item)
{
try
{
if (ufb != null && ufb.CurrentUser != null)
{
SetValue("CreatedByUserId", item, ufb.CurrentUser.Id);
SetValue("UpdatedByUserId", item, ufb.CurrentUser.Id);
}
SetValue("DateCreated", item, DateTime.Now);
SetValue("DateUpdated", item, DateTime.Now);
var newEntry = this.DbSet.Add(item);
this.Context.Database.Log = message => LogHandler.LogInfo(1111, message);
try
{
this.Context.SaveChanges();
}
catch (Exception ex)
{
LogHandler.LogInfo(2501, ex.Message);
}
BuildMetaData(item, true, true);
return newEntry;
}
catch (DbEntityValidationException dbEx)
{
// http://forums.asp.net/t/2014382.aspx?Validation+failed+for+one+or+more+entities+See+EntityValidationErrors+property+for+more+details+
string msg = string.Empty;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
msg += validationError.PropertyName;
msg += "---";
msg += validationError.ErrorMessage;
msg += "||";
}
}
throw new Exception("7777 CREATE EntityValidationErrors: " + msg);
}
}
My calling method is as below:
public List<VehicleInfo> Create(List<VehicleInfo> vehicleInfos, string Entity, int EntityId)
{
bool vehicleExists = false; List<VehicleInfo> newVehicleInfos = null;
if ((vehicleInfos != null) && (vehicleInfos.Count > 0))
{
newVehicleInfos = new List<VehicleInfo>();
foreach (VehicleInfo vehicleInfo in vehicleInfos)
{
vehicleExists = false;
if (vehicleInfo != null)
{
vehicleExists = this.VehicleExists(vehicleInfo.VehicleId, Entity, EntityId);
vehicleInfo.Entity = Entity;
vehicleInfo.EntityId = EntityId;
VehicleInfo v = this.UnitOfWork.VehicleInfoRepository.Create(vehicleInfo);
newVehicleInfos.Add(v);
}
}
}
return newVehicleInfos;
}
Hence when I am calling repositories create method for multiple times, its throwing me the above error, any help or suggestion would be very helpful, please thank you.
void BuildMetaDataNoThread(object item, bool active, bool isNew = false)
{
if (item.GetType() != typeof(JsonObject))
{
var dm = new DataAccessUnitOfWork(Constants.DefaultConnection);
var qtype = item.GetType();
if (qtype.BaseType.BaseType != null)
{
if ((isNew && qtype.BaseType.Name == typeof(ModelBase).Name) | qtype.BaseType.BaseType.Name == typeof(ModelBase).Name)
{
Thread.Sleep(500);
//collect data
var element = (ModelBase)item;
element.BuildMetaData(DataRequestType.CurrentItem);
var records = ModelBase.MetaData;
ModelBase.MetaData = new List<ModelRecord> { };
if (records == null) return;
foreach (ModelRecord r in records)
{
if (r!=null)
{
var jsr = new JavaScriptSerializer();
//object meta = r;
object rdata = r.Data;
var type = rdata.GetType();
var token = type.BaseType.Name;
List<string> include = r.Include;
// Cycle-through clieanup of models to be encoded into Json Data.
// this helper eliminates infinate relations by including records specified
// by a list of strings
if (include.Where(x => x.Contains("CreatedByUser")).Count() == 0)
include.Add("CreatedByUser");
if (include.Where(x => x.Contains("UpdatedByUser")).Count() == 0)
include.Add("UpdatedByUser");
var data = ClassCloner.CollectData(rdata, include);
List<string> tags = ClassCloner.CollectTags(data);
string _tags = "";
tags.ForEach((xtm) =>
{
_tags += xtm + ',';
});
var json = jsr.Serialize(data);
int id = 0;
//get identity
foreach (var prop in type.GetProperties())
{
if (id == 0)
{
foreach (var cp in prop.CustomAttributes)
{
if (cp.AttributeType.Name == "KeyAttribute")
{
var _id = ((Dictionary<string, object>)data)[prop.Name];
id = (int)_id;
break;
}
}
}
else { break; }
}
var query = dm.JsonObjectRepository.GetAll();
var key = "_" + token;
var _data = (Dictionary<string, object>)data;
var ExistingMetaData = (from x in query where x.SourceKey == key && x.SourceId == id select x).FirstOrDefault();
if (ExistingMetaData != null)
{
if (_data.ContainsKey("DateUpdated")) ExistingMetaData.Date = (DateTime)_data["DateUpdated"];
ExistingMetaData.SourceData = data;
ExistingMetaData.Encode();
ExistingMetaData.Active = active;
ExistingMetaData.SearchTags = _tags;
dm.JsonObjectRepository.Update(ExistingMetaData);
}
else
{
var newData = new JsonObject
{
Active = true,
Date = (DateTime)_data["DateUpdated"],
SourceData = data,
SourceId = id,
SourceKey = key,
SearchTags = _tags,
TargetKey = "GlobalSearchMetaData"
};
newData.Encode();
dm.JsonObjectRepository.Create(newData);
}
}
}
}
}
}
}
void BuildMetaData(object dataRecord, bool active, bool isNew)
{
new Thread((item) => { BuildMetaDataNoThread(item, active, isNew); }).Start(dataRecord);
}
I am trying to convert a controller to async operation or run it as a background worker.
Solution 1:
I tried below method but it give me an error saying DBContext has been disposed.
public IHttpActionResult ChargebackAllOpenAR(int clientId)
{
HostingEnvironment.QueueBackgroundWorkItem(clt => _clientService.ChargebackAllOpenAR(clientId));
//_clientService.ChargebackAllOpenAR(clientId);
return Ok();
}
Solution 2: But it runs as a normal synchronous process
[HttpPost]
public async Task<IHttpActionResult> ChargebackAllOpenAR(int clientId)
{
await Task.Run(() => _clientService.ChargebackAllOpenAR(clientId));
//_clientService.ChargebackAllOpenAR(clientId);
return Ok();
}
Solution 3: I tried this but give same error DBContext has been disposed.
https://github.com/StephenCleary/AspNetBackgroundTasks
Main Code:
public class ClientService : IClientService
{
private IRepository<Client> _clientRepository;
private IRepository<Invoice> _invoiceRepository;
private IRepository<Advance> _advanceRepository;
private IRepository<FinancialAccount> _financialAccountRepository;
private IClientTableRepository _clientTableRepository;
private IRepository<Transaction> _transactionRepository;
private IRepository<AppCredit> _appCreditRepository;
private IInvoiceService _invoiceService;
private IUserProfileRepository _userProfileRepository;
private IRepository<Domain.Payment> _paymentRepository;
private ARUnitOfWork _unitOfWork;
public ClientService(IRepository<Client> clientRepository,
IRepository<Invoice> invoiceRepository,
IRepository<Advance> advanceRepository,
IRepository<FinancialAccount> financialAccountRepository,
IClientTableRepository clientTableRepository,
IRepository<Transaction> transactionRepository,
IRepository<AppCredit> appCreditRepository,
IInvoiceService invoiceService,
IUserProfileRepository userProfileRepository,
IRepository<Domain.Payment> paymentRepository,
ARUnitOfWork unitOfWork)
{
_clientRepository = clientRepository;
_invoiceRepository = invoiceRepository;
_advanceRepository = advanceRepository;
_financialAccountRepository = financialAccountRepository;
_clientTableRepository = clientTableRepository;
_transactionRepository = transactionRepository;
_appCreditRepository = appCreditRepository;
_invoiceService = invoiceService;
_userProfileRepository = userProfileRepository;
_paymentRepository = paymentRepository;
_unitOfWork = unitOfWork;
}
public void ChargebackAllOpenAR(int clientId)
{
var client = _clientRepository.Find(c => c.Id == clientId, i => i.FinancialAccounts).First();
var transaction = new Transaction(clientId, TransactionType.Buyout);
ChargebackInvoices(client, transaction);
ChargebackOpenCredits(client, transaction);
ChargebackAdvances(client, transaction);
transaction.LineItems = transaction.LineItems.Where(li => li != null).ToList();
_transactionRepository.Insert(transaction);
_unitOfWork.SaveChanges();
}
private void ChargebackInvoices(Client client, Transaction transaction)
{
var openARAccount = client.FinancialAccounts.First(fa => fa.AccountType == ClientAccountType.OpenAR);
var escrowReservesAccount = client.FinancialAccounts.First(fa => fa.AccountType == ClientAccountType.EscrowReserve);
var cashReservesAccount = client.FinancialAccounts.First(fa => fa.AccountType == ClientAccountType.CashReserve);
var factoringFeeRevenueAccount = _financialAccountRepository.GetSingle(fa => fa.Division_Id == openARAccount.Division_Id && fa.AccountType == (int)SystemAccountType.FactoringFeeRevenue);
IEnumerable<Invoice> invoices = _invoiceRepository.Find(i => i.Client_Id == client.Id
&& i.Asset_Type == AssetType.Invoice
&& i.IsDeleted == false
&& i.Status == InvoiceStatus.Purchased,
i => i.InvoicePurchase.Terms.CollectionsFees,
i => i.TransactionLineItems)
.Where(i => i.AmountOutstanding.Value != 0)
.ToList();
foreach (Invoice invoice in invoices)
{
invoice.StatusReason = InvoiceStatusReason.Buyout;
invoice.DateClosed = DateUtil.GetSystemNow();
//Credit Open A/R for amount outstanding
transaction.LineItems.Add(openARAccount.CreateTransaction(invoice.AmountOutstanding, AccountingTransactionType.CREDIT, TransactionLineItemType.Buyout, invoice));
//Credit Fee Revenue for collections fees
CollectionsFeeCharge collectionsFee = _invoiceService.CalculateCollectionsFeeForInvoiceBuyout(invoice);
transaction.LineItems.Add(factoringFeeRevenueAccount.CreateTransaction(collectionsFee.Amount, AccountingTransactionType.CREDIT, TransactionLineItemType.Buyout, invoice));
//Debit Escrow Reserves for remaining invoice escrow
IEnumerable<TransactionLineItem> transactionLineItems = invoice.TransactionLineItems.Where(tli => tli.FinancialAccount.AccountType == (int)ClientAccountType.EscrowReserve);
var escrowAmount = transactionLineItems.Sum(tli => tli.AccountingTransactionType == AccountingTransactionType.CREDIT ? tli.Amount : -tli.Amount);
transaction.LineItems.Add(escrowReservesAccount.CreateTransaction(escrowAmount, AccountingTransactionType.DEBIT, TransactionLineItemType.Buyout, invoice));
//Debit Cash Reserves for (Open AR - invoice escrow + collections fees)
transaction.LineItems.Add(cashReservesAccount.CreateTransaction(invoice.AmountOutstanding - escrowAmount + collectionsFee.Amount, AccountingTransactionType.DEBIT, TransactionLineItemType.Buyout, invoice));
_invoiceRepository.Update(invoice);
}
}
private void ChargebackOpenCredits(Client client, Transaction transaction)
{
var cashReservesAccount = client.FinancialAccounts.First(fa => fa.AccountType == ClientAccountType.CashReserve);
var openCreditsAccount = client.FinancialAccounts.FirstOrDefault(fa => fa.AccountType == ClientAccountType.OpenCredits);
int loggedInUserId = _userProfileRepository.GetLoggedInUserId();
IEnumerable<AppCredit> appCredits = _appCreditRepository.Find(ac => (ac.Status == AppCreditStatus.Posted || ac.Status == AppCreditStatus.Ready)
&& ac.Client_Id == client.Id
&& ac.Type == AppCreditType.OpenCredit);
var ids = appCredits.Select(ac => ac.Payment_Id).Distinct().Where(id => id != null).Cast<int>();
var payments = _paymentRepository.Find(p => ids.Contains(p.Id), p => p.AppCredits)
.ToDictionary(p => p.Id);
foreach (AppCredit appCredit in appCredits)
{
DateTime now = DateUtil.GetSystemNow();
// mark open credit as removed
appCredit.Status = AppCreditStatus.Removed;
appCredit.RemovedBy_Id = loggedInUserId;
appCredit.DateRemoved = now;
// add posted reserve app credit to the payment with same amount
AppCredit reserveAppCredit = new AppCredit()
{
Type = AppCreditType.Reserve,
Status = AppCreditStatus.Posted,
Amount = appCredit.Amount,
Client_Id = appCredit.Client_Id,
Payment_Id = appCredit.Payment_Id,
PostedBy_Id = loggedInUserId,
DatePosted = now
};
Domain.Payment payment = payments[appCredit.Payment_Id];
payment.AppCredits.Add(reserveAppCredit);
if (payment.Status == Payment.Domain.PaymentStatus.Reopened
&& payment.AmountRemaining.IsZero()
&& !payment.AppCredits.Any(ac => ac.Status == AppCreditStatus.Ready))
{
payment.Status = Payment.Domain.PaymentStatus.Posted;
}
// Debit Open Credits
transaction.LineItems.Add(openCreditsAccount.CreateTransaction(appCredit.Amount, AccountingTransactionType.DEBIT, TransactionLineItemType.Buyout));
// Credit Cash Reserves
transaction.LineItems.Add(cashReservesAccount.CreateTransaction(appCredit.Amount, AccountingTransactionType.CREDIT, TransactionLineItemType.Buyout));
payment?.Transactions.Add(transaction);
}
}
private void ChargebackAdvances(Client client, Transaction transaction)
{
var cashReservesAccount = client.FinancialAccounts.First(fa => fa.AccountType == ClientAccountType.CashReserve);
var fuelAdvancceARAccount = client.FinancialAccounts.FirstOrDefault(fa => fa.AccountType == ClientAccountType.FuelAdvanceAR);
IEnumerable<Advance> advances = _advanceRepository.Find(a => a.Client_Id == client.Id
&& a.Asset_Type == AssetType.Advance
&& a.IsDeleted == false
&& a.Status == InvoiceStatus.Purchased)
.Where(a => a.AmountOutstanding.Value != 0)
.ToList();
foreach (Advance advance in advances)
{
advance.StatusReason = InvoiceStatusReason.Buyout;
advance.DateClosed = DateUtil.GetSystemNow();
//Debit Cash Reserves
transaction.LineItems.Add(cashReservesAccount.CreateTransaction(advance.AmountOutstanding, AccountingTransactionType.DEBIT, TransactionLineItemType.Buyout, advance));
//Credit Fuel Advance A/R
transaction.LineItems.Add(fuelAdvancceARAccount.CreateTransaction(advance.AmountOutstanding, AccountingTransactionType.CREDIT, TransactionLineItemType.Buyout, advance));
}
}
Finally working..
[Route("chargeback-all-open-ar-async")]
[DeltaAuthorize(Roles.OPS_MANAGER + "," + RoleGroups.TREASURY)]
[HttpPost]
public IHttpActionResult ChargebackAllOpenARAsync(int clientId)
{
_clientService.ChargebackAllOpenAR(clientId);
return Ok();
}
[Route("chargeback-all-open-ar")]
[DeltaAuthorize(Roles.OPS_MANAGER + "," + RoleGroups.TREASURY)]
[HttpPost]
public IHttpActionResult ChargebackAllOpenAR(int clientId)
{
HostingEnvironment.QueueBackgroundWorkItem(clt => ChargebackAllOpenARTask(Request, clientId));
return Ok();
}
private async Task ChargebackAllOpenARTask(HttpRequestMessage request, int clientId)
{
//Calls ChargebackAllOpenARAsync method
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = request.Headers.Authorization;
var url = new Uri(request.RequestUri.AbsoluteUri + "-async", UriKind.Absolute);
await client.PostAsync(url, new StringContent(string.Empty));
}
}
[Route("chargeback-all-open-ar")]
[DeltaAuthorize(Roles.OPS_MANAGER + "," + RoleGroups.TREASURY)]
[FireAndForget]
[HttpPost]
public IHttpActionResult ChargebackAllOpenAR(int clientId, [FromBody]bool isFireAndForget)
{
_clientService.ChargebackAllOpenAR(clientId);
return Ok();
}
public class FireAndForgetAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var request = actionContext.Request;
bool isfireAndForget = (bool)actionContext.ActionArguments["isFireAndForget"];
if (isfireAndForget)
{
QueueBackgroundWorker(request);
actionContext.Response = new HttpResponseMessage(HttpStatusCode.OK);
return;
}
}
private void QueueBackgroundWorker(HttpRequestMessage request)
{
HostingEnvironment.QueueBackgroundWorkItem(clt => GetTask(request));
}
private async Task GetTask(HttpRequestMessage request)
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = request.Headers.Authorization;
var url = new Uri(request.RequestUri.AbsoluteUri, UriKind.Absolute);
var param = new Dictionary<string, string>
{
{ "isFireAndForget", "false" }
};
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(param) };
await client.SendAsync(req);
}
}
}
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;
}
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();
}