Is the PreApplicationStartMethod in ASP.NET 4 a good thing? - asp.net

Disclaimer:
This is the first time I am asking a question that might be classified as subjective. As English is not my first language, it is hard to phrase this right. So please feel free to edit the question in order to make it clearer, or to point me at other ways for asking this.
Intro:
David Ebbo (architect on the ASP.NET team) just posted on Register your HTTP modules at runtime without config using the seemingly undocumented PreApplicationStartMethod assembly level attribute
I have mixed feelings about it.
On the one hand it is good to be able to do things as early in the application startup phase as possible.
On the other hand: Does it suffice? Do we need a PrePreApplicationStartMethod allowing to fiddle with the PreApplicationStartMethod behaviour? What about expansion to non-assembly use (for instance, NuGet already works around the single-use-per-assembly restriction of PreApplicationStartMethod)?
Question: Besides using it for config-less startup, what do you think of the PreApplicationStartMethod attribute?

I think one of the good usages for this is that it allows someone who is writing a 3rd party assembly, or a team that is working on an assembly that will be used in many projects, to be able to use this attribute to initialize stuff w/o requiring the end user/developer to create anything in the global.asax in the application startup events.
There are lots of app specific stuff that people like to/need to configure in global.asax, but if you are creating a DLL, you no longer have to make the user configure your classes in the global.asax, you can just put all your logic in your own init/bootstrap function and rely on asp.net to call your init logic when the app starts.

Related

ASP.NET infrastructure in MediatR handlers

I prefer to keep my handlers free from ASP.NET infrastructure that is very hard to test (yes, even in ASP.NET Core). But sometimes it happens and you have a dependency like UserManager (I'd like to know one day why it's not an interface), HttpContext, etc. and unit-tests are turned into a mocking-hell.
I tried using integration testing to deal with it by creating a TestServer and having all the ASP.NET infrastructure initialized for every api call. It works quite well but sometimes seems like an overkill if I want to test simple logic of my handler. And while it solves technical problem of mocking ASP.NET infrastructure, it keeps architectural problem (if you consider it so) of having ASP.NET infrastructure into your handlers.
I'd like to know what are the recommended approaches to deal with it?
I feel your pain. I stumbled across a fantastic blog post from Jimmy Bogard that handles this problem by using what Martin Fowler calls Subcutaneous Tests. I will leave the deep explanation to those experts but in a nutshell subcutaneous tests simply avoid all the difficult to test aspects of the UI.
Shameless plug: I am currently in the process of writing up a wiki that demonstrates these patterns in a sample end-to-end project on github. It's not difficult to follow but is probably too much code to post for a SO answer.
To Summarize:
If you are using MediatR correctly your controllers should be very thin which makes testing them pointless.
What you want to test are your handlers.
However, you want to test your handlers as part of your real world pipeline.
To Solve:
Wrap the http request in a transaction.
Build a test fixture that mimics the applications Startup.cs
Setup a test db server to execute queries and commands against but also is reset after each test.
That's basically it. Everytime you run an integration test against one of your handlers:
The hosting environment is mocked but your application is started up in a real world test.
Your query or command is wrapped in a transaction mimicking your DbContext.
The handler is executed against a real database and then reset.
I would add more code examples to my answer but between the blog post and the wiki I provided, it is much easier to follow the code examples there.
Edit 8/2021:
Stick with the source. Jimmy Bogard keeps the contoso university project current on his github page. Another great and a little more advanced example is the modular monolith project by Kamil Grzybek. That also is updated regularly on his github page.
Mediatr or no, you should always try to have only very basic pass this along logic in your controllers and call injected business logic classes from there to do the actual work. As you inject them with interfaces to this business logic, your controllers' dependencies are easily mocked in your unit tests, and your tests can focus on if they implement those interfaces properly and do only the basic work of routing input/output. And your actual business logic can be tested even easier.
For those classes that are static, for instance for reading the web.config settings, one strategy that I like a lot is make an interfaced wrapper class around them. While ConfigurationManager is static, I can still just write a regular class with an interface that I put methods or properties on to read a specific setting (preferably semantically named) from the Configuration Manager. Now I can easily mock any configured setting (or absence of it) in my test by just mocking the interface and setting up different return values.
I'd say it depends on the level of confidence you want to get in the end. If you want to make sure the whole system works as expected, then integration tests using a TestServer are probably the way to go.
One advantage of MediatR, though, is it allows you to decouple your business logic from the application using it, which is why at the very top level, let's say in controllers, there's no logic but just a delegation to the mediator.
That being said, you're right that sometimes your logic needs information from the hosting application. An example would be the user making the request, which is accessible in the HTTP context.
In that case, if you want to avoid having to set up a test HTTP server to test your logic works, you could represent that information in an abstraction and your handler would then take a dependency on that abstraction. Your tests could then mock that dependency while using the real system for everything else.
Does that make sense?

How important are modules and handlers?

Well, I'm just learning ASP.Net, and after reading some books I found that there are this things called Modules which tweak a Request and Handlers that (I think) tweak a response. The problem is that I can't understand how they really work, so I prefer just skip this part and come back to them when I get a bit more comfortable with the ASP.Net framework.
My question is, are they a big part of this framework? Am I going to use them a lot?
ASP.NET modules and handlers are definitely important, but typically they are secondary to pages and services: so it is reasonable to focus on pages and/or services first.
As your understanding grows, modules and handlers will probably start to make more sense when you revisit them.
Having said this, a related SO question explains ASP.NET modules & handlers about as simply as one could hope for.

Implementation of a ASP.NET based portal-like application

There is the requirement, to write a portal like ASP.NET based web application.
There should be a lightweigted central application, which implements the primary navigation and the authentication. The design is achieved by masterpages.
Then there are several more or less independent applications(old and new ones!!), which should easily and independent be integrated into this central application (which should be the entry point of these applications).
Which ways, architectures, patterns, techniques and possibilities can help and support to achieve these aims? For example makes it sense to run the (sub)applications in an iframe?
Are there (lightweighted and easy to learn) portal frameworks, which can be used (not big things like "DOTNETNUKE")?
Many thanks in advance for you hints, tips and help!
DON'T REINVENT THE WHEEL! The thing about DotNetNuke is that it can be as big or as small as you make it. If you use it properly, you will find that you can limit it to what you need. Don't put yourself through the same pain that others have already put themselves through. Unless of course you are only interested in learning from your pain.
I'm not saying that DNN is the right one for you. It may not be, but do spend the time to investigate a number of open source portals before you decide to write your own one. The features that you describe will take 1000s of hours to develop and test if you write them all from scratch.
#Michael Shimmins makes some good suggests about what to use to implement a portal app with some of the newer technology and best practice patterns. I would say, yes these are very good recommendations, but I would encourage you to either find someone who has already done it this way or start a new open source project on codeplex and get other to help you.
Daniel Dyson makes a fine point, but if you really want to implement it your self (there may be a reason), I would consider the following components:
MVC 2.0
Inversion of Control/Dependency Injection (StructureMap for instance)
Managed Extensibility Framework
NHibernate (either directly or through a library such as Sh#rp or Spring.NET
A service bus (NServiceBus for instance).
This combination gives you flexible user interface through MVC, which can be easily be added to via plugins (exposed and consumed via MEF), a standard data access library (NHibernate) which can be easily configured by the individual plugins to connect to specific databases, an ability to publish events and 'pick them up' by components composed at runtime (NServiceBus).
Using IoC and DI you can pass around interfaces which are resolved at runtime based on your required configuration. MEF gives you the flexibility of defining 'what' each plugin can do, and then leave it up to the plugins to do so, whilst your central application controls cross cutting concerns such as authentication, logging etc.

best practices for logging in ASP.net MVC?

What's the best way to log in ASP.net MVC? I mean any event, I'm currently using NLog but I know there are a lot of possible ways to do it.
I use log4net, its quite good. There are some issues to be aware of, you can learn more about them here. I also recommend Elmah, for me I use it on every project I do, its a prerequisite.
I don't think there is a best framework/tool or standard way in ASP.net MVC. Just do it the way you would in any other framework. When I set up logging, I usually think of it as a resource available to the rest of the application, rather than being tied to a particular tier. This is common, and in fact logging is the standard example given when introducing Aspect Oriented Programming. See:
Logging mentioned in the wikipedia entry on AOP
Another AOP into that uses logging as the example
Depending on what exactly you're trying to log, consider using action filters; a great way to log what page requests are made and for error handling coverage. Non-MVC asp.net apps usually do something in the global.asax, as mentioned here. In fact, even if you use the action filters, which I would suggest, also include some basic error handling in the global.asax 's application_error event; it will fire a little more dependably than the action filters if something really crazy happens.
Other than that, call your logging resource at the point where the stuff happens that's interesting to you. DB or File? Either works, and as long as it's encapsulated in a good method or two, you can always switch that later.

Code reusability - App_Code or BIN or UserControls?

I recently had a discussion on another forum with another developer and the topic was Code Reuse in ASP.NET. The stated scenario was that he needs to update code frequently on Production servers during server uptimes, and this results in Session getting reset for all users. He is avoiding putting shared code or classes into the App_Code folder or precompiled DLL's into the Bin folder because any updates will also refresh the Session.
The solution he has come up with is to put his shared code into UserControls and reference them wherever required. This enables him to update only the UserControl files which would be recompiled dynamically on next request without forcing a Session restart. Note that the Usercontrols are not intended to have any UI, they probably only house some business logic.
I tried to convince him against this because it felt intrinsically wrong to me - but I could not provide any hard facts to support my claim that this was a very bad way of doing things. The only thing I could think of is that it violates the principle of separation of business logic from UI. Am I grossly mistaken or are there concrete reasons why this should not be done? Links or examples would be helpful.
Note: Using out-of-process Session state is not an option at present, nor have they been able to decide on scheduled downtimes. Also, since this is a site under active development, they don't seem to be using any sort of professional deployment model yet.
Thanks in advance.
Edit: Additionally, it would be helpful if someone could clarify exactly why the Session restarts in the above mentioned cases.
It does seem like an unusual approach, and persistent session is the obvious answer. Assuming that reasons not to use persistent session are legitimate, sometime you just have to go with whatever works. I'd make a point of clearly documenting in the source files the unusual use of usercontrols and live with it.
To answer the why does session get reset edit. With in process session all the session data is in memory as part of your application. Various changes to the web site (e.g. web.config and others I don't recall off the top of my head) cause the application to restart wiping out all current state in your application. Persisting to SQL or the out of process session state server would allow the application to reset and lose any state without affecting the session data.
It sounds like the main problem is that he's updating production code too frequently. Other than that, UserControls seem like a perfectly reasonable place to put business logic, especially if you have a good naming convention for them or can put them in a common folder.
May i ask, why isn't out-of-process session state an option, really?
Since this guy seems to put in so much effort to get around this "problem", wouldn't he be better off looking at better solutions? out-of-process session state is the only good solution.
I'll agree with Dennis, there are really no issues moving from inproc to the state server. Not sure what your dev/deployment platforms are, but they should include a session state service - start that up, change your web.config, and the problem is solved.
it's a clever (and ugly) solution to a common problem
The main problem is the architecture of such system; the code that needs to be updated can be put on a different service outside his web app, his code behind can then call these services, and the services can be updated when needed without affecting the web app
Every base has been covered already, but I really hate bad practices like this. If the guy can't simply change to a state server to fix the problem that he has, then he doesn't really deserve the help. What would happen if he put his class in the root folder of the project and compiled it independently? Either way, I would think this guy is a bad developer for not thinking about scalability, and not planning for downtime. What I'm guessing is he doesn't have a development environment available. Tsk tsk tsk.
As an answer to your question, as stated by everyone else, put the code in a user control, and document well.

Resources