ASP.NET MVC and Listener/Event - asp.net-mvc

I would like to improve my knowledge, because I notice several time, I am convince I develop without to use the right practices, exemple to export a csv in ASP.NET MVC, I create in the controler 4 private methods, these methods do the necessary and return data.
I combine in 1 method, the 4 methods and call the parent method when the use click on export CSV.
These 4 methods are used in two places differents. So I can factorize the code in one for each or maybe it's possible to use delegate. Sure.
So I follow the tutorial from
http://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx about the event
and
http://msdn.microsoft.com/en-us/library/aa288459(v=vs.71).aspx about the delegate
And now, I think, it's not possible to create a listener to manager event in Web context.
My assumption is Web is not connected env, so you lost context each time.
Do you know a technical way to manage event+listener with webContext?
If you have any documentation/link about a pattern to implement it will be a plleasure to read.

You can make your API (Controller action/ WEB API) ‘context/session aware’ by using a session Id to refer to the same session. This way your server side logic will be able to ‘remember’ things for you, thus emulating a concept of a context.
This approach falls out of favour when you look at it from scalabilities’ point of view where your request would be served by one of many servers in a server cluster (unless you implement a dedicated session sharing mechanisms).
Best would be to implement a business service layer which would encapsulate all you atomic and repetitive logic and get the controller actions / web apis to call the service methods
hope this helps

Related

Using Web Services with EF Code First approach

I have developed some MVC applications by using Entity Framework code first approach and now I am developing a new application that will also use web services for mobile applications that we will create. So, I have trouble about the issues below. Could you clarify me please one by one regarding to the issues?
Which web service technology should I use i.e. Web API, WCF, etc? (I am using MVC5 and EF version 6 in my project)
Can I use the same CRUD methods for my web application and for web services? If so, which modifications should be made on the methods and on the other fields i.e. models, etc?
For a current MVC application where EF code first approach was used, is it better to create a new methods for web services or should the current methods be updated by adding ability to support also web services?
Thanks in advance...
I highly recommend to use Commands and Queries. It's covered in this and this articles.
The Command is simple DTO object, and it could be easily sent over the network. In this case you have control over the fields and behaviour you want to make public.
Because commands are simple data containers without behavior, it is
very easy to serialize them (using the XmlSerializer for instance) or
send them over the wire (using WCF for instance), which makes it not
only easy to queue them for later processing, but ot also makes it
very easy to log them in an audit trail- yet another reason to
separate data and behavior. All these features can be added, without
changing a single line of code in the application (except perhaps a
line at the start-up of the application).

Create a View against an API controller?

I need to create a website where some of it's pages should be accessible from external clients via an API, but I still want to make regular MVC Razor views to retrieve, display and manipulate the same data.
What's the best way to achieve this?
Update
What the API will have to expose is just data manipulation.
For the web pages, I still want to benefit from the razor chtml views, I prefer not polluting my views with redundant jQ or JS nor data- attributes that consume the data.
Just create an MVC project with the pages you want, and then create ApiControllers (from the Web API framework) to serve as RESTful endpoints. You can program your views to retrieve data from the API actions as JSON objects, and consume them with javascript. Other people can hit the same API actions and use the data in some other way.
If you want to start with a WebApi, and build basic views based on the same data that someone else could access via that API, you could inject your WebApi controllers into your normal MVC controllers, and invoke their methods to get the data that you need to build your ViewModels. This should work all right as long as your API controllers don't need to do anything "outside the box" like inspecting the Request object directly.
A more robust method would be to create a "Manager" layer that handles all the business logic of your application, and then have your ApiControllers be nothing but thin wrappers around calls to their respective Manager classes. This would add a little maintenance cost, but it would adhere to the Single Responsibility Principle a little better.
The easiet way is to use just MVC.
You can also combine MVC + WebAPI in one site.
The reasons to go with the first option is simplicity, and learning maintaining one framework and one set of abstractions.
However if you have any of the following requirements, adding Web API becomes interesting:
1. You want to do content negotiation for response types (say XML vs. Json for the same action).
2. You want to support CORS
3. You want a help page for your API.
4. You want to structure your Url space for your API with rest and resource centric approach (basically GET /resource rather than /resource/GetData).
5. Easier to unit test controllers and actions.
Both frameworks are built by the same team, they both support attribute routing and many similar concepts, and both work well together with one another. I've seen folks take both approaches successfully. Also note that visual studio has templates that combines both of them from the get go.

Is it a good practice to use an MVC application's own Web API for Ajax bindings?

I'm writting an application that has many Ajax widgets (Kendo-UI to be percise). It's starting to get messy to have all those Ajax responses without the standard controllers so I was starting to consider making each entities their own controller. If I'm taking the time to do this, I figured I might as well go foward and do those as WebAPIs since I was planning to do this in a not so close future, but hey, it would be done already...
So my question is: Is it a good practice to use an MVC application's own Web API as a Ajax Widget feeds or is there any reason to stick with standard Controllers?
I've seen some arguments about performance, but I don't think this applies to this situation. I believe it was more of a "Controller calling WebAPI" situation which has obvious performance hits. But since it's already a client side Ajax call, weither it goes into a standard MVC Controller or a WebAPI controller shouldn't change a thing, would it?
Edit
Additional information regarding the project:
I am using Entity Framework for the data access.
I have a repository pattern going on with UnitOfWork.
I am using proper a MVC structure (EF POCOs AutoMapped to DTO POCOs in the repository and fed into View Models by the controllers)
This is a MVC 4 project on .NET 4.0
There is a lot of database relationships (specially for the object I'm working with at the moment)
I don't know about "good practice", but it's certainly not "bad practice". I see no difference whether you do it in the app or a different one.
I think its a good thing but only if what you are doing in the API is kept as generic as possible to other applications and services can reuse the API.
Both the applications I have written and continue to maintain use pretty much the exact same stack as your app.
I have recently re-factored one of the applications to use the API for all the common things like lists that I'm binding to Kendo ComboBoxes etc. in my views. Its a fairly large application that re-uses a lot of the same lists such as states, priorities, complexities across various Entities and views so it makes sense to put those in the API.
I haven't gone as far as going the whole hog through. I draw the line with things like this:
public ActionResult GetAjaxProjectsList([DataSourceRequest]DataSourceRequest request)
{
return Json((DataSourceResult)GetProjectsList().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
That is very specific to how the Kendo Grid wants the data back. Nothing else I have connecting to this app will use this data in this format so I keep it in the controller.
In short... I use the API for common things within the same MVC app and things that I allow to be used by other applications or services, like Excel.

When should I consider implementing a Service in Grails?

I'm new to Grails and web development. I started doing a project on Schedule management website stuff. I came across the Service concept that is provided by Grails. I understood the concept, but still I have confusion on when to use services.
For example, I need to implement a search module, where the manager can search for a user to find his schedules. In this case it will be good to implement it as a controller or as a service?
So,
When and where should I use Service?
To add to Grooveek's answer;
It is also nice to use Services to keep your Controllers nice and clean.
So Views just render data to the screen, Domain objects store state, Controllers route the user around the application, and Services perform the work.
I don't have enough reputation to comment on an answer or vote up so I have to provide an answer that really should be a comment. Anyways...
+1 on #tim_yates answer. Gotta love thin controllers. 2 things that I would add to the description of a controller:
Would be to translate parameters from the browser before hitting a service (e.g. Date, number, etc.)
Would be to translate data returned from services into something consumable for the views.
For me, ideally, services would never deal with translating a String parameter to it's inherent type. Or deal with building a model to be displayed on a view.
What and where I should use Service?
When you want your controller do to something that may be reused by other controllers
In our application we're doing a functional separation of service. We have a CorePersistanceService, which provides method to create, delete, update and manipulate Core Domain Classes (core for us).
I think persistance services are a good way to reuse GORM code throughout Grails code. You can create method in domain classes, but I don't like that, it's way less maintanable I think
We have a PDFService class for our PDF creation, a SolrService which connect to Solr, a Statisticservice that gather all our methods which collects statictics on our datas
Services in Grails are a manner to gather methods around a particular functional theme, in order to give possibility to reuse them in controllers (I forgot to mention our SecurityService, which is a pretty good Cross-Applications Example)

MVC Best practices when all methods come from a web service

Hi we have a third party application that exposes a web service for use in building websites. It handles createing sessions , getting product data, shopping cart, and check out calls to the database. I am new to MVC and my question is how do I work this webservice into my mvc site i am building, I want to take advantage of testing as well. I can not change the access to the database, I have to use the web service.
Thanks!
Jon
I usually deal with the data access using a services pattern. In your case I'd have an interface like IProductsService with the usual methods GetProducts(), GetProduct(id) ... and so on. By coding against that interface your controller will not care about where the data is coming from, so you would declare and use your dependency as
private IProductsService _productsService
...
IEnumerable<Products> products = _productService.GetProducts();
This comes quite handy for testing purposes too, as with IoC you can inject a different service (one that returns a hardcoded list for example) depending on your test cases. Eventually if you guys switch to a different strategy and access the data store directly you only need to create a new service, implement the interface and inject that one instead.

Resources