The purpose of Include() in ASP.NET MVC + Entity Framework - asp.net

In the controllers generated by Visual Studio, as well as the sample application (ContosoUniversity), the Index action always has something like
var departments = db.Departments.Include(d => d.Administrator);
What's the difference between that and
var departments = db.Departments;
First I suspected that the first one (with Include) enables the view to retrieve department.Administrator. But the second one (without Include) seems to be able to do that as well.

The Include tells Entity Framework work to eagerly load the Administrator for each Department in the results. In this case, Entity Framework can use a SQL join to grab the data from both tables in a single request.
The code will still work without the Include, but the first time you access a Department's Administrator, EF will need to hit the database to load it (since it wasn't pre-loaded). Loading data on demand (lazily) is a nice feature but it can be a serious performance problem (known as an N+1 problem). Especially if you are accessing the Administrator for each Department (for example, in a loop) - instead of one database call, you will end up with many!

In first case (with Include) when you write department.Administrator servers the object from memory that has been eagerly loaded due to Include method. In the second case, an sql statement will be executed to fetch the Administrator record from the db for each department object.

See the "Lazy, Eager, and Explicit Loading of Related Data" section in this tutorial:
http://www.asp.net/entity-framework/tutorials/reading-related-data-with-the-entity-framework-in-an-asp-net-mvc-application

var departments = db.Departments;
This will retrieves the aggregate domains only if LazyLoadingEnabled is enabled & MultipleActiveResultSets is set to true in connection string.

Related

PerformanceCounters updated in HttpModule are not updating in PerfMon

I am trying to add PerformanceCounter logging as part of our WebForms application. I am attempting to port an MVC implementation that uses ActionFilters to write request durations per controller action to custom performance counter instances here.
My implementation is to write an HttpModule that logs the OnBeginRequest and OnEndRequest to write to these custom performance counters. However, when I view in PerfMon, I can see the instances of my counters show up in PerfMon, but the values are all empty ("------").
I am initializing the performance counter using the following code:
var counter = new PerformanceCounter {
CategoryName = categoryName,
CounterName = counterName,
InstanceName = instanceName,
ReadOnly = false,
InstanceLifetime = PerformanceCounterInstanceLifetime.Process,
RawValue = 0,
};
Even if I didn't update the value, I would assume that the Last value would be 0, but instead it is '-------'.
The code in the sample associated with the article does work and uses the same syntax. I did notice that the counters written by the MVC attribute have no 'Parent' but the ones created by the WebForms module have a parent specified. I don't know if this has anything to do with it.
I have checked to ensure that no errors are being recorded in the Event log. I would appreciate guidance on why my performance counters are not updating.
Thanks
UPDATE 6/5/2014
I discovered that the issue was a '/' in the instance name, which gets turned into parent/instance which cannot be found once created. Make sure that you clean up your instance name to ensure that no forward slashes exist, or you won't be able to update the values.
I discovered that the issue was a forward slash ('/') in the instance name I was assigning, which gets split into parent/instance which cannot be found once created. Make sure that you clean up your instance name to ensure that no forward slashes exist, or you won't be able to update the performance counter's values.

ASP.NET nHibernate per request cache

It is possible to enable a cache that start ad the beginning of the request and ends at the end of the request ??
For some tables it will useful to enable a cache that not select the same record more that one time.
For example when I render a a partial more that one time the SELECT inside the partial are unnecessary.
Assume this snippet:
#foreach(var row in orders)
{
#{Html.RenderPartial("Order");}
}
And the partial Order is:
<div>
#session.Query<Langs>.SingleOrDefault(el => el.Id == "EN').Description
</div>
<div>
#Model.OrderID
</div>
It is possible to enable a cache that cache the "Langs" table only in the current session ?
Without cache I have N (Count of Orders) SELECT per request, otherwise with request cache I will have 1 SELECT per request.
Thank You!
You should not be executing any database queries from within any view such as the partial you mentioned. This will almost always lead to a SELECT N+1 scenario.
Follow an MVC pattern and do not mix the concerns. Any database queries should be initiated from a repository layer, then populate a model object that represents what data that the view needs, then pass that model to the view.
With programming, anything is possible and there are always a million ways to do the same thing but following best practices and separation of concerns will save you from yourself and help you to build efficient, extendable and maintainable applications.
To reiterate, whatever data your view needs access to, do all of that querying on the Controller-side of the MVC pattern. Doing it any other way is mixing concerns and leads to situations such as the one you are encountering.
You have at least 2 posiblities:
cache your query
enable caching on the object Langs mapping
Query:
#session.Query<Langs>.SetCacheable(true).SingleOrDefault(el => el.Id == "EN').Description
And add the key hibernate.cache.use_query_cache = true to the configuration

Grid (View) with paging, sorting & searching: How to use Ressource Provider

we have an architectual problem with our data grid. The grid supports searching, paging and sorting using a linq2entity query, that contains all of the above parameters.
At some pages, the grid should not display the content from the database (e.g. column 'name'), but the translated ressource, loaded by the Resource Provider.
Our Resource Provider gets the translations from the database and caches them to the application cache to avoid unneccessary trips to the database.
At this point, we have the following possibilities:
No searching, sorting and paging on the databse, so loading all rows, then load the translations from the Resource Provider, then do the searching, sorting and paging at the application.
Bad performance, because the database is very big
Searching, sorting and paging on the database, then load the ressources for the results.The Displayed Values will not match to the search and sort configuration
Get the Resources directly from the database, within the linq query.
The Ressource Provider Caching cannot be used. The Join with the Resource Provider Texts will be very bad and slow
Every possibility is very bad, but I can't think of another solution. Any good suggestions? How are these problems solved in other software?
You can do it by bring the associated filtered records from the database and keep it in ViewState.
How can you improve the Performance?
You can make use of JSON / Page Methods for Database Callings. I will explain it to you with the help
of an example.
Click here to check the code for GridView Bindings using JSON
Mark Up With JSON
I am calling the Code Behind methof from Client side
Code Behind
Output
Click here to check the output in case of Update Panels
Is application is holding too much memory then you need a Doctor like Red Gate Ants Memory Profiler. Click here to see more details about it
Make sure to use the Using Statements to avoid Memory Out of Exceptions
using (SqlConnection connection = new SqlConnection())
{
connection.Open();
//Also for SqlCommand... Sample code...
using (SqlCommand cmd = new SqlCommand())
{
}
using (SqlTransaction transaction = connection.BeginTransaction())
{
transaction.Commit();
}
}
Are you aware about the Teleric Grid? It loads all the records first from the database and keeps in Cache. In order to go for this you must use Paging and Disposing the objects is mandatory. Teleric Grid shows these records in Paging. Thus you can avoid the rendering issue to get rid of displaying all records in once.
i don't understand your question properly but if you want to all operations on translated resource you have to store translated resource in database then get them in to session object and apply filter on it if it is either in form of table or list then give source to grid which has to configured as work with translated resource which is filtered from session object.

Security Issue with ASP.NET and SQL Server

A problem appears when two users are logged on to our service system at the same time and looking at the service list gridview. If user1 does a search to filter the gridview and user2 happens to click to another page user2 sees the results from the search performed by user1. That means one company can see another company's data.
It's an ASP.NET application that was developed in house with C#/ASP.NET 3.5. The data is stored in a SQL 2000 database and relies very heavily on stored procedures to update, select, and delete data. There are multiple user types that are restricted to what data they can see. For example, we have a company use that can only see data relavant to that company.
From what I've seen, the security is handled through If statements in the front end. Example, if userlevel = 1 then do this, if userlevel = 2 do this. These statments are used to show or hide columns in a grid, run queries to return data, and any other restrictions needed. For a company user the code behind gets the companyid assigned to the user and uses that in a query to return the results of all the data associated with that companyid (services, ships, etc).
Any recommendations for fixing this will be highly appreciated.
It's hard to say without seeing any implementation details, but on the surface it appears that there maybe some company level caching. Check for OutputCache settings, DataSource caching, explicit caching with Page.Cache, etc.
This article is a little dated, but at a glance it looks like most information is still relevant in ASP.NET 4.0.
ASP.NET Caching: Techniques and Best Practices
In addition to jrummerll's answer, check the Data Acces Layer of our app and make sure that you don't have any static variables defined. Having a static variable defined could cause this sort of issue too, since 2 contending requests may overwrite the value of the CompanyID, for example.
You basic model should work. What you've told us is not enough to diagnose the problem. But, I've got a few guesses. Most likely your code is confusing UserID or CompanyID values.
Are you mistakenly storing the CompanyID in the Cache, rather than the session?
Is the CompanyID stored in a static variable? A common (and disastrous!) pitfall in web applications is that a value stored in a static variable will remain the same for all users! In general, don't use static variables in asp.net apps.
Maybe your db caching or output caching doesn't vary properly by session or other variables. So, a 2nd user will see what was created for the previous user. Stop any caching that's happening and see if that fixes it, but debug from there.
Other variations on the above themes: maybe the query is stored in a static variable. Maybe these user-related values are stored in the cache or db, but the key for that record (UserID?) is stored in a static variable?
You can put that if statements in a thread. Threading provides you the option that only 1 user can access the application or gridview in your case.
See this link: http://msdn.microsoft.com/en-us/library/ms173179.aspx
Here is some sample code that is throughout the entire application that is used for filtering results. What is the best way to fix this so that when one user logs on, the other user doesn't see those results?
protected void PopulategvServiceRequestListing(string _whereclause)
{
_dsGlobalDatasource = new TelemarServiceRequestListing().GetServiceRequestListingDatasource(_whereclause);
if(_dsGlobalDatasource.Tables[0].Rows.Count!=0)
{
gv_ServiceRequest.DataSource = _dsGlobalDatasource;
gv_ServiceRequest.DataBind();
}
else
{
gv_ServiceRequest.DataSource=new TelemarServiceRequestListing().DummyDataset();
gv_ServiceRequest.DataBind();
gv_ServiceRequest.Rows[0].Visible = false;
gv_ServiceRequest.HeaderStyle.Font.Bold = true;
}
}

ASP.NET DataView - problem with RowFilter and application cache

Good afternoon ladies and gents --
I've been tasked with finding and fixing a bug in an unfamiliar legacy application that had some recent changes made to it, but I don't have an easy way (that I know of) to test my theory. I'm hoping your collective knowledge will verify the test for me.
This application lazy loads lookup lists (tongue-twister?) into DataTables from a database and stores them as an object in HttpContext.Current.Application (an HttpApplicationState).
Before the changes were made, one of the lookup tables was bound to a DropDownList in the following manner (contrived):
Me._lookupList = TheSession.LookupCache.SomeLookupListName.DefaultView
...
ddl.DataSource = Me._lookupList
where 'SomeLookupListName' is a read-only property that returns a DataTable from HttpContext.Current.Application. The changes added some code that filters the private Me._lookupList (DataView) before being bound to the DropDownList:
Me._lookupList.RowFilter = "SomeTableIDColumn <> " & ...
What's happening, if you haven't guessed it already, is that that DataView is now filtered for every user of the application. I looked around the code and found that most other lookup lists are copied to local members in this fashion:
Me._lookupList = New DataView(TheSession.LookupCache.SomeLookupListName)
Since I don't know how to attack my local debug session pretending to be multiple users, will changing the code to use the latter method actually be any different than the former? Does filtering the result of DataTable.DefaultView actually apply the filter to the underlying DataTable differently than if wrapping the table with a New DataView(...)?
Would it make sense to simply clear the row filter after the DropDownList is bound (seems like a bad solution)? I'd like to stick to the ugly conventions this application uses so that I don't surprise another developer down the road who gets a similar task, otherwise I'd just bypass the application state and grab the items right out of the data repository.
I appreciate your feedback.
Does filtering the result of
DataTable.DefaultView actually apply
the filter to the underlying DataTable
differently than if wrapping the table
with a New DataView(...)?
Yes. It creates a new view which the filter is applied to. The filter is not applied to the table directly. Following the pattern to use the new view will work.
BTW, easy to test multiple sessions against your debugger. Just open up two different browsers (IE and FF) and point to the same app. User login might be the same, but the sessions will be unique.

Resources