ASP.NET with Unity 2.0 - asp.net

Can anyone help point me to some good resources for working with Unity 2.0 in an ASP.NET that doesn't talk about ASP.NET MVC?!?
We are not using MVC and I am struggling to get Unity to inject dependencies into my pages following the couple of examples I've read (which are all based on David Hayden's work so they are all presenting the same examples and code).
UPDATE
I tried to go the PageHandlerFactory route but the example (here) is incomplete and no source code is available to accompany the article.
So, I decided to try the custom HttpModule approach described here and here. Again, no source code is available beyond what is shown so it is difficult to troubleshoot issues.
The problem I have now is that all of the plumbing appears to be wiring up correctly but the Buildup method does nothing to my page. I can see all of the types are registered in the container when I set a break-point in the module code and the code is executing as expected. But a break-point in the Page_Load event handler shows that the dependencies are all null.
The property in question is public, with a setter and getter, and is marked with the Dependency attribute. I've tried with and without the attribute, with and without a mapping name, ... every combination I could think of and nothing works.
What am I missing???

It depends what you expect. Most exemples targeting MVC present custom controller factory which allows creating controllers with dependency injection. This is indeed also possible with web forms but instead of controller you must inject dependencies into pages. To do this you must replace PageHandlerFactory with custom implementation.
You can create your own implementation of PageHandlerFactory which will be able to resolve pages directly and inject dependencies defined in constructor or you can use one of these (here, here and here) which instead uses stantandard PageHandlerFactory and builds page instance (resolve property dependencies).

Related

MvvmCross MvxApplication class overriding for different platforms. (Plus, encryption)

I've got two questions here. The first one is just specific and another one is more general, but is a source of the first one.
So, my specific problem: I want to use Encryption (actually, Hashing) algorithms with using System.Security.Cryptography namespace (for instance, SHA256Managed class).
I found out that (happily) Xamarin has implemented those in System.dll.
But it is not portable and obviously can not be used from Core application directly.
But I've also found another great project -- PclContrib -- which allows you to do that. But, unfortunately, they don't have the implementation for Touch and Android. (However, that still works great for Desktop (Web) and Windows Phone, plus, still can be included into Core (as it uses portable project)).
Anyway, to solve that nicely, I've decided to create some base class for the encryption methods and then override core methods which require the custom dll (for any custom system).
The way I did it (at least, trying to do) was:
Defining virtual method in Core App base class:
public virtual IEncryptionProvider CreateEncryptionProvider()
Overriding Core App class in Touch project with overriding CreateEncryptionProvider (which creates an instance of TouchEncryptionProvider class instance).
Core:
public class App : MvxApplication
Touch:
public class AppTouch : App
Launching it in Touch setup.cs:
protected override Cirrious.MvvmCross.ViewModels.IMvxApplication CreateApp (
{
return new AppTouch();
}
But, that does not work for me. On startup I've got this exception message in log:
"Exception masked KeyNotFoundException: Could not find view for Mynamespace.Etc.LoginViewModel", which works fine when I do new App() instead. I am not sure if that message shows actual problem (as before it was saying the same even that was a problem with some third-party dll, unrelated to views at all). But speaking shortly, that's just a primitive inheritance of App : MvxApplication, but placed not in Core but Touch project.
So, does it requeire some more custom initialization for such situations or do I miss something else?
And, actually, more general question is how should I build such Multiplatform approaches? Actually, now I've got similar problem with HttpUtility.UrlEncode, which I would want to use in my Core project.
What is the MvvmCross "philosophy" to handle such situations?
Thank you.
For the 'viewmodel not found' problem, this is caused because mvvmcross by default only looks for viewmodels in the Assembly containing your app.
If you want it to look in other assemblies, override ViewModelAssemblies in Setup.cs - see how this done in, for example, MvvmCross - structuring shared View Models and Views
For general multplatform approach, please read questions and answers like:
Platform-specific IoC in MVVMCross
Instantiation of ViewModels and Service classes
Please also remember you don't have to use PCLs - if you prefer to use file-linking between multiple platform-specific core projects, then you can of course use this approach.
Finally, please also try to ask one question per question - I find it makes stackoverflow work better for users and with search engines too. If you need to link questions, then you can just add a hyperlink reference - stackoverflow then marks them as related.

MVC4: List of all urls available on the site?

We have quite a large MVC4 application and we would like to have Selenium go through every page and make sure it loads - some sort of smoke test.
I can use reflection to go through the assembly, find all controllers and all actions, check if actions are not post, come up with parameters for actions that require parameters.
Then I'll feed this list to Selenium and check that everything I need on the pages is done appropriately.
But before I start playing with reflection, I'd like to check if this has already been done, so I don't reinvent the bicycle. I have googled for such thing, but could not find anything.
p.s. Writing the reflection code is not an issue. Selenium is covered as well. Just checking if this has already been done.
The AttributeRouting project has a route debugger in place, which does work even if you don't use attribute routing inside your project.
You can see the class that handles displaying the routes over on Github but I'm not sure it will display the routing information when the project isn't run locally. You may need to adapt that code so you can access it safely from your Selenium instance (and make it machine readable using JSON or something).

How does Spring portlet MVC 3.1 determine which annotated method to render with multiple controllers?

We have encountered a problem using Spring Portlet MVC 3.1 when using multiple controller classes and the DefaultAnnotationHandlerMapping.
Background
We are using Spring Portlet MVC 3.1 with annotations for the Render & Action phases
We are using JBoss EPP 5.1.1
Issue
For a Portlet render request with params, an incorrect page is rendered in the portlet
Cause
Spring Portlet MVC is using a different method for #RenderMapping than the expected method with the correct annotations
Technical Analysis
All our controllers contain #RenderMapping and #ActionMapping annotations, and all have “params” arguments to ensure that the expected method is invoked based on a parameter set in our portlet URLs. For default rendering, we have a method that has a #RenderMapping annotation with no “params” argument, which we use to render a blank JSP when the request contains no parameters.
Based on the reading of Chapter 7 and 8 in your book, we learnt that the Dispatcher Portlet tries to get the appropriate handler mapping for the incoming request and send it to the appropriate method in the controller bean configured. Our assumption was that our default #RenderMapping annotation (with no params) would only be invoked after it has checked that there are no other methods in the Controllers with an annotation that matches the specific request parameters.
However, we have debugged to realise that this assumption is incorrect. The DefaultAnnotationHandlerMapping appears to traverse through the available list of annotations in the Controller beans in some pre-defined order. This means that if the controller bean with the default #RenderMapping annotation (with no params)appears before in the list, the method with the default #RenderMapping annotation (with no params) will be invoked rather than the correct which is further down the list.
Manifested Error
We are developing in a Windows environment and deploying to a Linux environment. In Windows we see that the handler cycles through the controller beans in alphabetical order, so we initially solved our problem by adding the #RenderMapping annotated method with no params in the controller with the bean name closest to ‘Z’.
In Linux, however, it appears that the controller beans are detected in a different order. I have attached the Spring logs below to highlight the issue. The no params #RenderMapping annotation is in the YourDetailsController, and as you can see in the Windows log it appears last in the list, whereas in Linux it doesn’t. This means that if we try to access one of the controllers that appears after the YourDetailsController in the list we instead always end up hitting the no params annotation in the YourDetailsController instead.
Questions
Is our assumption incorrect?
Does our diagnosis reflect expected behaviour? Or is it a bug with Spring Portlet MVC?
Is there a different way to get the annotations scanned to form the handlermapping bean list?
Would using xml configuration (instead of annotations) remove our problem?
Would we able to define multiple handler mapping and order so that the default handler mapping is the last handler mapping used by the dispatcher portlet?
Any thoughts or advice you have on this problem would be greatly appreciated.
Mike. I'm experiencing the exact same problem. I'm using JDK 7, Spring 3.1.1.RELEASE and Hibernate 4.1.3.Final. I'm developing on Linux (Fedora) and deploying on Linux (Fedora and SL).
I was stuck because I was sure the pieces (controllers) were working one at a time but together the call to a render request was randomly ignored. Sometimes changing something would make things work again on a render request but they never worked all together.
As Walter suggested, when I isolated the controller containing only the default render request in its own package, left only the default render request in it (before I had the delete/view requests) and separated the scan of controllers in the portlet's XML configuration in two with the scanning of the default controller after the others, suddenly everything works like a charm.
It would be interesting to see if this bug is in the Spring tracker...
I'd been bitten by this problem recently, so thought I'd add some additional information based on what I found.
In my case, my default controller (with empty #Controller and #ActionMapping annotations) was always getting invoked, even though there were more specifically annotated controllers/actions (such as #Controller(XXXX) or #ActionMapping(YYYY)). What made my case weirder was that it worked OK in Tomcat/Pluto, but not in WAS/WebSphere Portal Server.
As it turns out, there is a bug introduced in 3.1.x of Spring that means the annotation handlers aren't sorted properly. See https://jira.springsource.org/browse/SPR-9303 and https://jira.springsource.org/browse/SPR-9605. Apparently, this is fixed in 3.1.3.
The big mystery to me was why it was working in Tomcat but not WebSphere? The underlying cause is that Pluto (2.0.3) uses Sun JRE 1.6.0 whereas WebSphere uses IBM JRE 1.5.0. The two JREs have a different implementation of Collections.sort() that results in a different output order when ordering array elements that are reporting they are equal (that is, the result of the compareTo() function). Because of the above Spring bug (which reports some handlers as being equal when it shouldn't) it means that the ordering of the handlers was non-deterministic across the two JREs.
So, in my case, the IBM JRE just happened to put the default controller as the very first element, and so it would be picked up every time. One way that we can affect the ordering of "equal" handlers (where "equal" is a dodgy definition due to the Spring bug) is to change the order that they are found by Spring - which affects the order of the input into the sort routine. That is why, per the above posts, moving the controller from the component scan to being explicitly listed in the XML config works. In my case, it was sufficient to make my default controller's package the last entry in my component scan. I didn't need to move it to the XML config.
Anyway, hope this helps shed a little more light on what is happening.
Response received from Ashish Sarin:
Hi Mike,
Though I haven't tested the exact same scenario that you are following
in your project, but I can say that it doesn't look like the right
approach to define your controllers. If your controllers only make use
of #RenderMapping and #ActionMapping annotations, then it might be
difficult for the developers to find out the exact controller
responsible for handling an incoming portlet request. I would
recommend that you make use of #RequestMapping at the type-level to
map portlet request to a particular controller, and use request
parameters to further narrow down the request to a particular method
in the controller.
Let me know if you still face any issue with this approach.
Mike, Your description is exactly the same issue we are running into. In Windows, we implemented the same workaround (prefixed the controller with the default rendering with a Z) and that solved it. That same code in a Linux environment has the same issues as yours. It looked like it was a times stamp issue ordering as the methods that weren't getting picked, but no luck going that route.
I assumed this was a spring bug.
I think the approach here is ok - we want different controllers handling different functions, but we want a default controller.
I just found one workaround for now. I moved the controller with the default rendering method to a different package so it is not included in the component-scan.
I add that controller manually (in the portletname-portlet.xml file) after the component-scan line, so it adds that as the last controller.
We use context:component-scan (in nnn-portlet.xml) to divide controllers default render mappings between portlet.

How Orchard CMS does the logging?

I'm working with Orchard CMS and it is better CMS for me. I want to understand how it does the logging and whether I can add my own logging or not. I saw that Orchard uses NullLogger class and it does no work. I've opened the App_Data.Logs folder and have seen that there are the log files. But how? I searched in code where is the trick that replaces NullLogger with log4net (I guess this is log4net, because the log format and the formatting for log4net.config are very similar) but I haven't found this.
Can somebody answer me:
How Orchard does the logging?
Whether I can add my own logger and if yes what best practices exist to do this?
Thanks, Andrey.
An Autofac module (Orchard.Logging.LoggerModule to be precise) handles that. Basically - it scans each dependency and fills all properties of type ILogger with a reference to appropriate logger instance. Each dependency gets its own logger with name equal to full type name (including namespace) of a containing class.
The NullLogger is just a placeholder so accessing the property would not throw NullReferenceExceptions before the property is being set by Autofac.
Extending the default logging is a rather complicated task as it would involve doing three things:
create a custom implementation of ILoggerFactory (just like the default Orchard.Logging.CastleLoggerFactory) and
create an Autofac module that registers that implementation in the container (like the mentioned LoggerModule does)
suppress the current default logging module by decorating your new one with [OrchardSuppressDependency("Orchard.Logging.LoggingModule")]
UPDATE
Just realized I haven't addressed the most important part of the question here:)
Yes, Orchard uses log4net so you may alter the default settings via Config/log4net.config file.
There is a great article on how Orchard Logging works. (I am not sure if it is ok to copy and paste the entire article). This is the link: Injection Logger in Orchard
So the trick is this:
Whenever a class requires a Logger instance, all it needs to do is to
declare a ILogger property, that’s it. And later, in your class, you
can use this property to Logging at anytime
And how is this done?
When Orchard web application startup, the OrchardStarter will be used
to do most of the registration work.
In a few words, it looks all the code in all projects, gets all the classes that use an ILogger property, and implements it for you (if not implemented), using Castle's logger factory.

Can Microsoft Code Contracts be used with an ASP.NET Website?

I'm currently using Microsoft Code Contracts in an ASP.NET MVC application without any issues but I can not seem to get it quite running in a basic ASP.NET Web site. I'm not entirely sure it was made to work with this type of project (although it shouldn't matter) so I wanted to bring it up to everyone.
I can compile the contracts just fine but the code skips over them since I'm assuming it hasn't been enabled through the Properties Page like you would do in other project types (ie ASP.NET MVC). I've gone to the property page of the project (which displays a dialog instead of the typical properties page) in my ASP.NET web site but it does not yield the same menu options and as such, doesn't have a section devoted to Code Contracts.
Also, I have Microsoft Code Contracts properly enabled within a class library project that I use to separate my business logic from the web site. The contracts compile fine but when a contract is violated, it throws a rather uninformative "Exception of type 'System.ExecutionEngineException' was thrown" error with no inner exception. My contract specifies a message to display upon violation but it is nowhere within the exception. It simply halts the execution of the process (which I believe is the default functionality for Microsoft Code Contracts).
I can't find anywhere that explicitly states that a particular project type can or can't (or shouldn't) be used with Contracts so I just wanted to see if anyone has had this issue.
Thanks for any help!
I had the same problem and this is how I solved it:
In the Referenced Class Libraries, right click -> properties -> code contracts.
Make sure "perform contract checking" is checked. I had mine set to "Full"
Contract Reference Assembly: make sure it is set to "Build"
Save your changes.
In the Referenced Class Libraries that have no contracts in their code, set the Contract Reference Assembly to "Do Not Build".
Then in the MVC project, have the Code Contracts "perform contract checking" checked. I had mine set to "Full".
Hope that helps somebody.
This sounds less like a Contracts and more like a build/config issue. Have you tried to deploy a prebuilt website? Are you sure that your website code sees the contracts code? Is the ASP.NET runtime using the CLR 4.0, or does it see the earlier Microsoft.Contracts.dll? Etc.

Resources