Out of Memory at line XXXX - c#

can anyone help me how to resolve the out of memory error on my asp page? im using linq to sql.. after adding data several data.. like more than 10 rows. in the grid. an out of memory error occurs.. attached herewith is my add function..
public ServiceDetail checkservicedetailid()
{
string ServiceName = ViewState["Tab"].ToString();
ServiceDetail checkservicedetailid = ServiceDetails_worker.get(a => a.ServiceName == ServiceName && a.MarginAnalysisID == checkmarginanalysisid().MarginAnalysisID).SingleOrDefault();
return checkservicedetailid;
}
public IEnumerable<ServiceDetail> get(Expression<Func<ServiceDetail, Boolean>> express)
{
return ServiceDetailsDB.ServiceDetails.Where(express);
}
protected void btnSaveEmptyOC_Click(object sender, EventArgs e)
{
try
{
if (checkservicedetailid() != null)
{
CashExpense tblCashExpenses = new CashExpense();
Guid CashExpensesID = Guid.NewGuid();
tblCashExpenses.CashExpensesID = CashExpensesID;
tblCashExpenses.ServiceDetailsID = checkservicedetailid().ServiceDetailsID;
tblCashExpenses.Description = txtDescriptionEmptyOC.Text;
tblCashExpenses.Quantity = Decimal.Parse(txtQTYEmptyOC.Text);
tblCashExpenses.UnitCost = Decimal.Parse(txtUnitCostEmptyOC.Text);
tblCashExpenses.CreatedBy = User.Identity.Name;
tblCashExpenses.DateCreated = DateTime.Now;
tblCashExpenses.CashExpensesTypeID = "OTHER";
CashExpenses_worker.insert(tblCashExpenses);
CashExpenses_worker.submit();
//Clear items after saving
txtDescriptionEmptyOC.Text = "";
txtQTYEmptyOC.Text = "";
txtUnitCostEmptyOC.Text = "";
ValidationMessage.ShowValidationMessage(MessageCenter.CashExpenseMaintenace.InsertOC2, "SaveEmptyOC", this.Page);
MyAuditProvider.Insert(this.GetType().ToString(), ViewState["MarginAnalysisID"].ToString(), MessageCenter.Mode.ADD, MessageCenter.CashExpenseMaintenace.InsertOC2, Page.Request, User);
divOtherCost.Visible = false;
grd_othercost.Visible = true;
btnaddothercost.Visible = true;
}
else
{
//Displays a Message on the Validation Summary (Service Id does not exist)
ValidationMessage.ShowValidationMessage(MessageCenter.CashExpenseMaintenace.SaveServiceDetailOC, "SaveEmptyOC", this.Page);
}
}
catch
{
//Displays a Message on the Validation Summary (Error on Saving)
ValidationMessage.ShowValidationMessage(MessageCenter.CashExpenseMaintenace.InsertOCError, "SaveEmptyOC", this.Page);
}
finally
{
//Rebinds the Grid
populategrd_othercost();
}
}

I'm guessing from your code here:
ServiceDetail checkservicedetailid = ServiceDetails_worker.get(
a => a.ServiceName == ServiceName &&
a.MarginAnalysisID == checkmarginanalysisid().MarginAnalysisID
).SingleOrDefault();
that .get() is taking a Func<SomeType, bool>, and you are doing something like:
var row = dbCtx.SomeTable.Where(predicate);
(please correct me here if I'm incorrect)
This, however, is using LINQ-to-Objects, meaning: it is loading every row from the table to the client and testing locally. That'll hurt memory, especially if a different db-context is created for each row. Additionally, the checkmarginanalysisid() call is being executed per row, when presumably it doesn't change between rows.
You should be testing this with an Expression<Func<SomeType, bool>> which would be translated to TSQL and executed at the server. You may also need to remove untranslatable methods, i.e.
var marginAnalysisId = checkmarginanalysisid().MarginAnalysisID;
ServiceDetail checkservicedetailid = ServiceDetails_worker.get(
a => a.ServiceName == ServiceName &&
a.MarginAnalysisID == marginAnalysisId
).SingleOrDefault();
where that is get(Expression<Func<SomeType, bool>>).

I tried all of the solution given to me both by my peers as well as the solution provided here, from GC.Collect, to disposing linq datacontext after use etc. however the error keeps on occurring, i then tried to remove the update panel, Ive read a site that showed how ridiculous update panel when it comes to handling data esp when a function is done repeatedly. And poof! the memory problem is gone!

Related

How to efficiently edit data in a database?

The method is supposed to receive data from a server, check if new tokens have been added, and if there are, add them to the database. If the token already exists, update its status but don't add a new row in the table. This is the code I've written so far.
IEnumerable<Token> serverTokens = JsonConvert.DeserializeObject<IEnumerable<Token>>
(server.GetTokens().Content);
IEnumerable<Token> dbTokens = _tokenService.GetAllTokens();
foreach (var token in serverTokens)
{
var dbToken = dbTokens.Where(x => x.Symbol == token.Symbol).FirstOrDefault();
if (dbToken != null)
{
Token editedToken = dbToken;
editedToken.UpdatedOn = DateTime.Now;
editedToken.Active = token.Active;
_tokenService.AddToken(editedToken);
}
else
{
token.UpdatedOn = DateTime.Now;
_tokenService.AddToken(token);
}
}
dbContext.SaveChanges();
The AddToken method is just a simple AddOrUpdate operation.
public void AddToken(Token token)
{
_dbContext.Tokens.AddOrUpdate(token);
//_dbContext.SaveChanges();
}
Now, this code does what it's supposed to, however it's extremely slow. How would I go about optimizing it?
dbTokens.Where(x => x.Symbol == token.Symbol) is IEnumerable
So he will load it each time you call it on the loop.
Store in in a list before the loop
List<Token> dbTokens = _tokenService.GetAllTokens().ToList()

ClrZmq returning messages always to first started client

We're creating a WPF app in which we execute python scripts from different Test Stations and show the output in its corresponding output panel, To run the scripts in parallel we are using Task but when we run the scripts in parallel from the stations, We are getting the output of other stations also into the station that is started first, we're using the following code,
private void ZmqStatusListener(string endPoint)
{
using (Context context = new Context())
{
StatusPort = string.Empty;
TestResultPort = string.Empty;
using (Socket server = context.Socket(SocketType.REP))
{
try
{
if (isStatusContextActive == false || isPortChanged == true)
{
server.Bind(endPoint);
isStatusContextActive = true;
}
}
catch (ZMQ.Exception ex)
{
if (ex.Errno != 100)
{
string IPCPort = _globalParameters.GlbParam.GlbParamIpcStartPort;
if (IPCPort == string.Empty)
{
IPCPort = "0";
}
if (endPoint == EditorConstants.PortAddress.PortPrefix + IPCPort)
{
StatusPort = endPoint;
TestReultError = EditorConstants.CommonMessageTypes.TestReultError + ex.Message + EditorConstants.CommonMessageTypes.StackTraceMessage + ex.StackTrace;
}
StopExecOfScript(default(object));
isCancelledtask = true;
ScriptStatusDesc = new ScriptStatusDesc()
{
Status = "Failed",
statusDescription = "Failed"
};
}
}
while (true)
{
string message = server.Recv(Encoding.UTF8);
UpdateTestResults(message);
server.Send(" ACK", Encoding.UTF8);
// if (message == "Test Passed")
//break;
}
}
}
}
and for testing purpose we're breaking the while loop in this code based on a test message we kept in the python script, then we are able to get the output in the respective station correctly but this way we can only run in a synchronous fashion which we don't want as we require to run the test stations in parallel and the while loop should not break as it should be listening for the response.
We were able to solve the issue by getting clues doing a sample app to reproduce the issue and to first know whether our ClrZmq pattern was correct for us or not and it is correct. The resolution we followed is that when we needed to bind that data to its corresponding View's Model object in its ViewModel so had to retrieve View's DataContext which is of Type ISomeXViewModel for the particular TestStation using an Id of that TestStation we did this cos all of our TestStations are dynamically added and we even store it to be accessed wherever necessary. This issue was caused to due multiple instances of UserControls so we explicitly needed to update the TestStation manually with a little more effort.
Sample Code Snippet
private void BindTestResult(string xmlPayLoad)
{
// converting xmlPalLoad to a class/model object
ITestStationViewModel viewModel = (ITestStationViewModel)((IView)DynamicTestStationsGrid.Children[StationNumber].Content).DataContext;
// IView class has DataContext property so I am type casting the Content which is ContentControl to IView type first and later to ITestStationViewModel
viewModel.TestStationModel = xmlPayLoadModel;
}
Thanks.

Error on loading user control

i want to load my own designed User Control to the form but when i drag and place the user Control it produces the Error. Please Kindly refer my Screen Shot and help me to solve this issue.
The error where in code is i mentioned as line no:
private void populateTransfers(bool all)
{
AccountTransfer[] accounts;
//List<ReferenceData._account> headers = ReferenceData.getIndentHeader_account();
if (all)
accounts = accountClient.getAllPendingTransfers();
else
accounts = accountClient.getPendingTransfers(Program.loggedInUser.account.id);//line no:47
if (accounts != null)
{
var query = from a in accounts
select new
{
Id = a.id,
Name=a.name,
Status = a.status,
Date = a.ludt.ToShortDateString()
};
this.gridPendingTransfers.DataSource = query.ToList();
this.gridPendingTransfers.RefreshDataSource();
}
else
{
CexAppUtil.ShowEmptyGrid("No pending transfers", this.gridPendingTransfers);
}
private void initializeData()
{
if (Program.loggedInUser != null && Program.loggedInUser.isAdmin())
{
pendingTransferOptionsPanel.Visible = true;
showAllPendingTransfers.Visible = true;
if (showAllPendingTransfers.Checked) populateTransfers(true);
else populateTransfers(false);
}
else
{
pendingTransferOptionsPanel.Visible = false;
showAllPendingTransfers.Visible = false;
populateTransfers(false);//line no:167
}
}
Please help me to solve this problem.
Thanks-in Advance.
You can debug and find the error in your custom control by starting a new instance of visual studio and attach the debugger to the process of the first instance.
After that you can add your new control and see which object is null.
Are doing some work in constructor? Delete all code from constructor instead of InitilizeComponents(). Then make a new Initilize Method where you copy the code from constructor. This method you call in form.load or sth. Try it out ;) – # Sebi
Thank to every-one.

Sys.WebForms.PageRequestManagerServerErrorException: An entity object cannot be referenced by multiple instances of IEntityChangeTracker

Story:
I have a strange error when I try to save something I got this error message
An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
I really don’t know what that is and why is it appear, it appears only when I try to save something my insert and update is working, only when I try to save something in db from my Telerik grid
if (this.annualVacationList != null)
{
List<AnnualVacation> vacationToSave = this.annualVacationList;
IEnumerable<AnnualVacation> existing = paramUser.AnnualVacations;
foreach (AnnualVacation toSave in vacationToSave)
{
AnnualVacation existingItem = existing.Where(x => x.AnnualVacationId == toSave.AnnualVacationId).SingleOrDefault();
if (existingItem == null)
{
ctx.AddToAnnualVacations(toSave);
}
else
{
existingItem.FromDate = toSave.FromDate;
existingItem.ToDate = toSave.ToDate;
existingItem.WorkingTime = toSave.WorkingTime;
existingItem.VacationDays = toSave.VacationDays;
}
}
}
ctx.SaveChanges();
}
After debugging I have seen that the code brake down in the Project.Name.Designer.cs
..... O.o
public void AddToAnnualVacations(AnnualVacation annualVacation)
{
base.AddObject("AnnualVacations", annualVacation);
}
Heey
I got it by myself somehow viewstates are not Detaching the context and that was the problem I have just created
var tmp = new AnnualVacation
{
FromDate = toSave.FromDate,
ToDate = toSave.ToDate,
WorkingTime = toSave.WorkingTime,
VacationDays = toSave.VacationDays,
UserId = toSave.UserId
};
in the same if query that is above (if(existing Item==null)) and it works
but still thanks for everyone that tried to help me ^^

Linq Include method not showing up in viewmodel

I have a Silverlight app using mvvm with ria services. I have a textbox on the view that the user puts in a Job Number and clicks find. This find button is using the ICommand in xaml to go here..
public ICommand FindJob
{
get
{
return new DelegateCommand(BeginFindJob, (o) => true);
}
}
public void BeginFindJob(object o)
{
if (!IsDesignTime)
{
IsLoading = true;
string jobnum = o.ToString();
OnPropertyChanged("IsLoading");
LoadOperation<Job> loadOp = _context.Load<Job>(_context.GetJobsByJobNumQuery(jobnum));
loadOp.Completed += new EventHandler(loadOp_Completed);
}
}
It uses the GetJobsByJobNumQuery in my ria service like so..
public IQueryable<Job> GetJobsByJobNum(string JobNum)
{
var query = ((from j in this.ObjectContext.Jobs
where j.JobNumber == JobNum
select j) as ObjectQuery<Job>).Include("JobHeadings").Include("JobContracts").Include("JobTags").Include("JobMarket");
return query;
}
Im wanting it to return all the information about the job, so i wrote the query above to include all those relationships. Putting a breakpoint on the linq query and looking at the results, it has exactly what I wont. All the fields, JobHeadings and Contracts are working and bringing back all the bindings to that job. So now I bring that query back in my viewmodel and populate the fields, like so..
void loadOp_Completed(object sender, EventArgs e)
{
try
{
LoadOperation<Job> loadOp = sender as LoadOperation<Job>;
if (!loadOp.HasError)
{
_job = loadOp.Entities.FirstOrDefault<Job>();
base.IsLoading = false;
base.ProgressBarVisibility = Visibility.Collapsed;
base.OnPropertyChanged("IsLoading");
base.OnPropertyChanged("ProgressBarVisibility");
base.OnPropertyChanged("CurrentJob");
}
}
catch (Exception ex)
{
}
}
My problem is, that no relationship data is coming back. All the basic Job info is coming back from the Job table in my db, but none of the info from the related tables is coming back in my viewmodel. Putting a bp in and looking at _job, which should contain everything, all the relationship tables JobHeading/JobContract say 'Enumeration yielded no results.'
So how is it not making its way back through to the viewmodel? What can i do to get the full query results put into the view/viewmodel so I can make changes?
Should the Includes not be higher up on the ObjectSet? like this:
public IQueryable<Job> GetJobsByJobNum(string JobNum)
{
var query = ((from j in this.ObjectContext.Jobs.Include("JobHeadings").Include("JobContracts").Include("JobTags").Include("JobMarket")
where j.JobNumber == JobNum
select j) as ObjectQuery<Job>);
return query;
}
This was a problem with the metadata service not picking up my latest table associations. After i went through that mess of regenerating the metadata, it was a simple matter of including and associating the correct keys. Thank you Quinton Bernhardt for your effort!

Categories

Resources