I want to calculate how much queries are executed when i request a page in asp.net mvc. Difficults in page logic: sum queries are executed in main controller action, but others - in widget controller actions, which are called by Html.ActionLink in master page.
I wrote base class for all controllers in which i'm encapsulate query called function to increase queries counter - static variable. On page loading it work nice, all queries are counted, but when i requested second page my static counter doesn't reset, what should i do?
If possible avoid using a static variable. An instance variable on the base controller would work just as easily if all the methods shared the same controller instance. I assume that you're not instantiating new controllers to execute the other actions.
EDIT: After thinking about it, a simple static variable won't work as it will be shared across all requests. You'll need to use some sort of dictionary keyed by some unique id identifying the request. Perhaps based on a combination of the HostAddress and a timestamp created when the request is initiated. Perhaps using the application cache would work so it's available from everywhere and automatically cleaned up when you are done. This is only going to get more complicated as you consider all the possible way that multiple threads may interact. Again, I'd say trying to use an instance variable may be the best way to handle this.
extend your MvcApplication Class (in your global.asax) with
public static int QueryCount { get; set; }
then create a handler for the MvcApplication.BeginRequest event or extend your existing handler with
this.QueryCount = 0;
and in your BaseController Class you can increment your counter with
MvcApplication.QueryCount++;
hth
Are you using SQL Server? If so you can use the SQL Server Profiler from the Tools menu to see how many queries are run for a specific page.
Related
In my ASP.NET MVC solution I have a number of services.
One of them, SessionService, is used to access the currently selected region and time span.
I want to display those in a layout used to decorate views. What is the best design approach to access those values which are stored in the SessionService?
Right now I'm thinking about using calling a ChildAction from the layout which in turn calls the session service:
_Layout -> aController.ChildAction() -> SessionService.GetRegion()
Is it a good approach or can you recommend anything better?
UPDATE 1:
Other options for passing the values that are possible:
via ViewBag
via ViewModels
However the drawback for these options is the fact that it would be necessary to populate them in each and every action method which would lead to duplication of code (which could be mitigated by means of a filter, but again this will require decorating controllers with the filter).
UPDATE 2 (born in the discussion with O:rvar below):
Another option is to create a base controller which will be populating ViewBag properties upon creation. All other controllers should derive from it.
You should be able to access you session data in the view with the following code:
var region = #Session["Region"].ToString();
Or you could call the controller method as you mentioned with an ajax call and get the session data that way. Using the childaction approach is also a fine way of accomplishing what you want.
Friends:
In the service class I am trying to query the DB and get result to populate my domain class. I am not sure if I thinking this correctly or I have to use the find methods approach to fill my domain classes ?
The understanding I have is:
Grails thru URLMappings will call my controller and inside that I can do a direct instantiation of Service class.
I am then using SQL directly there inside Service class to iterate thru the Resultset and populate the Domain class list and return that to controller class which will then return a list back to the REST call user.
Is this the right approach or I have to call Service from controller but using the find method and that will fill the list and that should be used to return the list ?
In all cases I am using the H2 db itself.
Regards and Thank you for your time.
-Narahari
As per the standards, Flow goes from controller > Service > DAO.
All the business logic should be written in the service class only.
As you are using DAO layer is hidden through GORM.
Grails is very powerful and productive language. You use GORM for database activity. For your scenario, you could use findAll, createCriteria, HQL or native SQL query approach, but the flow should not be broken. It means that if write database related code in the controller then in future it will be difficult to maintain debug code.
This is the first time I'm doing a web project using MVC and I'm trying to make it based on three layers : MVC, DAL (Data Access Layer) and BLL (Business Logic Layer).
I'm also trying to use repositories and I'm doing it code-first.
Anyway I've searched a lot on the web but yet if you've got a good reference for me I'll be glad to see it .
My current project looks like this:
And here are my questions:
Where are the Product and User classes that represent tables supposed to be? It seems that I need to use them in the BLL and I don't really need them in the DAL but for the PASContext.
Where do I initiate the PASContext? In all of the examples I've seen on the internet no one made a constructor in the repository that takes 0 argument, which means that the context is not created within the repository (and I've read some reasons why like so all repositories will use one context).
If I'm trying to initiate the PASContext in the ProductBLL the compiler says it doesn't recognize it and I'm missing a reference (although I've added the needed reference and the name PASContext is marked in a blue like vs did recognize it)
PASContext is the class that is inherited from DbContext.
Here is some code to demonstrate:
public class ProductsBLL
{
private EFRepository<Product> productsRepository;
private List<Product> products;
public ProductsBLL()
{
PASContext context = new PASContext();
productsRepository = new EFRepository<Product>(context);
//LoadData();
}
About the View models, if I want, for example, to present a list of products for the client, do I need to create a ProductViewModel, get the data from ProductsBLL which has a list of Product and convert it to a list of ProductViewModel and then send it to the controller?
In addition, in the ProductController, do I only initiate ProductsBLL? I don't initiate any repository or context, right?
If someone could show me some project that uses repository, three-tier architecture and takes data from the database, transfers it to the BLL and from there to the MVC layer and using a ViewModel show it to the client it will be great.
Question 1
Where are the Product and User classes that represent tables supposed to be?
I would have these in a project that can be referenced by all other projects. That is, all other projects can depend on the solution with the models. In the case of onion architecture the models belong in the core which is at the center of the solution.
In your case I'd put them in the BLL.
Question 2
Where do I initiate the PASContext?
The reason why you don't normally see this done directly is because it's very common to use Dependency Injection or DI (What is dependency injection?)
This means that you don't need to instantiate a DbContext directly; you let the DI container do it for you. In my MVC applications the context has a PerWebRequest lifestyle.
PerWebRequest Lifestyle:
Instance of a component will be shared in scope of a single web request. The instance will be created the first time it's requested in scope of the web request.
A context is created when the request is made, used throughout the request (so all repositories gain the benefits of the first-level caching) and then the context is disposed of when the request is completed. All of it is managed by the DI container.
Question 3
do I need to create a ProductViewModel [...] ?
You generally only have one view-model to give to a view. The view should be its own object that has all of the things that the view needs in order to display everything. You suggest that you create multiple view-model objects and pass that to the view. My concern with that approach is what happens if you want to display more information for that view? Say, you want to display a single DateTime object to the user. Now you want to display one of something but you're passing many objects to the view.
Instead, separate things up. Create a single view-model and pass that to the view. If you have a part of the view that needs to display many of something, have the view call it as a child action or partial so that the view isn't doing too much.
Your approach:
A different approach:
Conclusion
If someone could show me some project that uses [...] three-tier architecture
I'm not sure about three-tier architecture. Here are some example projects that use a variety of solution architectures:
MVCForum
EFMVC
Official MVC samples
There is no single correct approach - just good and bad approaches.
I would start here. You'll get a lot more information on broad topics like this from prepared resources sources.
http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/cs/intro-to-aspnet-mvc-3.
Update
In-depth tutorials
http://www.codeproject.com/Articles/70061/Architecture-Guide-ASP-NET-MVC-Framework-N-tier-En
http://www.asp.net/mvc/tutorials/hands-on-labs/aspnet-mvc-4-models-and-data-access
http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4
http://www.codedigest.com/Articles/ASPNET/187_How_to_create_a_website_using_3_tier_architecture.aspx
http://www.mvcsharp.org/Basics_of_MVC_and_MVP/Default.aspx
Example Projects
http://prodinner.codeplex.com/
http://www.nopcommerce.com/
http://www.mvcsharp.org/Getting_started_with_MVCSharp/Default.aspx
I'm quite new to Rails development and I came up with this question today. I have a method that returns some JSON data.
It is used to populate a select with a list of cities according to what was selected on a previous select (list of states). So, it's a simple method that loads a list based on some ajax parameter passed through and it is used all along my site.
I'm using Rails 4 and I placed this method on my HomeController. So everytime I need to fetch the list of cities, I call the HomeController to load the data.
Is this the correct approach or should I place this method on a more generic controller (like ApplicationController)? Is there a better way?
I think the best thing is to keep this modular. So you can create a separate controller for this, like StatesController - and possibly even a separate model if that makes sense for your application (I'm not sure where you're getting your data). There is no cost to having extra controllers, and this way your code is clean and organized, with each piece of functionality existing in its logical place.
In my view, if I have a situation where I need to use a dynamic method (such as Domain.findByName("name")) in multiple places, would it be better to define a variable with and refer to that, rather than have the dynamic method in multiple places? I know this seems like an obvious answer, but I just wanted to make sure Grails doesn't cache it or something, and indeed two DB calls are being made.
By default, grails will only cache "get" requests (i.e. Book.get(4)), if you don't set up any additional caching, you'll hit the database for each request (as you're seeing).
See the 'caching queries' section of the grails documentation for more detail.
If you only want the call to be made once (which makes sense in a view since you'd want it to be consistent), I'd either do the query in the action and pass it in the model, or else you could also use the g:set in your view to set it (though this sounds like it's more appropriate for a controller or service).
It would be better to send the domain object to the view as part of the model, rather than calling Domain.findByName("name") from your view.
So in your controller method you'd want
def myAction = {
def myObject = Domain.findByName("name")
// do other stuff
[myObject: myObject]
}
then in your view you can access it by
${myObject.property}