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

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.

Related

MVC conversion project, fully qualified classes are not available unless 'Global' is added or System... is removed

My question is similar to here: ASP.NET System.Anything is not defined
I am in the process of converting a website project to an MVC 4 project. To do this, I created a new MVC project and imported all of my content from the previous website. Both projects are in VB, and I'm using Visual Studio 2010 SP1, with both the MVC 4 update and TFS 2012 update applied.
I now have errors popping up when I build the MVC project. Things like "Type 'System.Web.UI.Webcontrol' is not defined." When I hover over the error, two of the prompts I get to fix it are
1) Change 'System.Web.UI.WebControl' to 'Global.System.Web.UI.WebControl'
2) Change 'System.Web.UI.WebControl' to 'WebControl'
Both of these seem to fix it, but does anyone know why I can't use "System.Web.UI.WebControl" to refer to this class? I'd rather not change all of my code... there are 100s of thousands lines in there.
Update: Outside of the System and System.Web.UI namespaces, I can also drop the 'System.'. So 'System.Drawing.Color' would become 'Drawing.Color'.
There exists another namespace containing System in your solution somewhere (e.g. Abc.System.def) - probably in a referenced library. After the conversion, the project file probably imported the prefix to System in said namespace (e.g. Abc), so when you type in System, it resolves to Abc.System.
I posted this question before I had whittled down as much of the compile errors as possible.
It appears that after I had removed all the System. references from the previous App_Code classes, the real errors started appearing. There were all sorts of messages about aspx controls not existing.
Ultimately, it seemed that I needed to right-click on the .aspx pages from my website project and choose 'Convert to Web Application.' This generated a .aspx.designer.vb file with the asp.net control declarations in yet another partial class.
After doing that for all pages, I am now able to use System. throughout the app.
To others who've asked, this System. error was only affecting the non-page code. .aspx, .aspx.vb, .ascx, .ascx.vb, .ashx, etc., files were not affected.
This does make some sense, anyhow, as I had previously pulled in all the App_Code libraries prior to pulling in the pages, and the site compiled. After importing the pages and their code behinds, the order of the errors was just odd. But I stuck with it and found the underlying cause.
Thanks for the willingness to help. If you have any other questions, I'd be glad to respond.

Debugging SDL Tridion 2011 Custom Resolvers and the GetListPublishItems() method

In one of my C# Template Building Blocks I have the following line of code
publication.GetListPublishItems(uriTarget, false, false,
TDSDefinesInterop.ListColumnFilter.XMLListDefault, listRowFilter);
Before implementing a Custom Resolver, this code executed very quickly. Now that my resolver is implemented for the Publication ItemType the code executes really slowly. From this I conclude that the new Resolver is being called behind the scenes by the GetListPublishItems() method (which makes sense). I assume I need to modify the resolver somehow. However I can't seem to hit a break point in my resolver when the method is called.
I normally attach to the 'TcmTemplateDebugHost' when debugging a template or directly to the publisher process when debugging the resolver. My Resolver only seems to get hit when I first press Publish and not when the GetListPublishItems() method is called.
So this question is twofold:
Do Resolvers get called when the GetListPublishItems() method is used?
Assuming they are called, which process should I attach to when I need to debug it in this scenario?
I don't know for certain, but I can't imagine a sane scenario where a custom resolver wouldn't be involved in GetListPublishItems(). Your evidence seems to back this up, but of course, if we can answer the second part of your question, we'll know it for certain.
I imagine that any normal assumptions you've made about the hosting process are probably correct, so for example, if you are invoking your template during a publish, then the TcmPublisher will be the process. Alternatively, if you were to open up the publish dialog for the publication in the GUI and hit "Show Items To Publish", then it would probably be the COM Surrogate process (dllhost.exe)... and so on. One way to find out for sure, though, is to use Sysinternals Process Explorer, which has a very handy feature that will allow you to search for which processes have a given dll loaded. (Look in the Find menu)
One likely cause for a breakpoint failing to bite is that Visual Studio isn't able to load the symbols correctly. When you're debugging a template building block, Tridion explicitly loads the symbols from a known location, which you can configure (tridion.templating/debugging/#pdbdirectory in the CM config), which is where the template uploader places the PDBs. When the publisher process loads the custom resolver, I doubt if there's any such special mechanism to locate the symbols, so you'll have to fall back to standard .NET methods. The first thing I'd try is to ensure your symbols for the custom resolver class are located in the same place as the assembly (i.e. your bin directory). Failing that you could perhaps configure a symbols path in Visual studio.
The first thing to do is to watch the debug output in Visual Studio. If you start the process and then attach to it, you will see the various assemblies being loaded. If Visual Studio can find the symbols, you will see that the output says "Symbols Loaded".

What makes an ASP.NET project an application vs library?

I am inheriting some ASP.NET code (I am an OS guy, not a web dev (yet ;-)). The solution has been re-factored and there are multiple projects (libraries and asp.net sites) in it. Aside from the libraries, there are two asp.net projects (called MAINSITE and SUBSITE). Only MAINSITE is being used as the official site (as an asp.net site), and MAINSITE has a depency on the code in the SUBSITE asp.net site, but doesn't use the site itself. I am trying to figure out how to clean this up and convert SUBSITE into a library.
My quick question is, whenever I debug the MAINSITE (set as default), it runs two asp.net processes: MAINSITE and SUBSITE. And so, at the very least, how can I avoid this? Is there a quick/temporary solution to this?
My detailed question is this:
What makes an asp.net site an asp.net site? For instance, in C the difference between an dll and exe could be defined (superficially anyway) as the presence of a main, and potential export information for the library (among other things, of course). If I were to convert an exe to dll I might:
1. remove the main code
2. make sure the public interface was correct (and exported correctly)
3. convert the makefile to build a dll rather than an exe.
Can someone point me to some similar steps for asp.net to .net lib?
Maybe:
1. get rid of index.aspx
2. get rid of web.config
3. any *.cs files to remove?
4. how do I change the properties?
5. any gotchas?
Thanks so much for your help.
Details: Visual Studio 2008/.NET 3.5
There are many, many components to make an application run as an ASP.Net application. However, in terms of your actual Web Application project, there's really not that much difference between it and generic library code except for the fact that much of your code relies on the existence of the HttpApplication runtime.
Any code that utilizes the System.Web (especially System.Web.UI) is going to be suspect in terms of having this dependency. For example, all the code in page or webcontrol event handlers (Init, Load, PreRender, etc.) relies on the fact that there is an HttpHandler (running inside an HttpApplication) raising these events. If you run the same WebControl out of a library that's not in an ASP.Net project, none of this will ever happen and the control will be useless. However, that exact same library would be quite functional if executed in the context of an ASP.Net process.
It really boils down to what process you're running the library in. In most cases, ASP.Net processes are spawned by IIS, although it is possible to host an ASP.Net process in other types of programs as well.
There isn't a simple 5-step process for converting a web project to a library unfortunately. But as a rule of thumb, webcontrols, .aspx and .ascx codebehind aren't going to convert.
For a more detailed look at what makes code into an ASP.Net program, see Rick Strahl's "A Low level look at ASP.Net".
If you go to "File" > "New" > "New Project..." and then click on the (assuming you're using C#) "Visual C#" in the list on the left, you're given the ability to create a "Class Library" project. You can extract all the relevant code to one of these and then reference in in your "MAINSITE".
You will need to reference it in the "References" section of your MAINSITE project and may need to import your library project using the import keyword.

Compiling/Embedding ASCX templated UserControls for reuse in multiple web applications

I'm onto a real head scratcher here ... and it appears to be one of the more frustrating topics of ASP.NET.
I've got an assembly that implements a-lot of custom Linq stuff, which at it's core has zero web functionality. I have an additional assembly that extends this assembly with web specific behaviour.
The web specific behaviour comes with a couple of user controls marked up inside ASCX templated UserControls.
I'm having trouble putting a nice finish on this assembly so that it is simple to redeploy for use in other applications. Let me run through what I've tried so far:
Copied the ASCX files to the consuming web application using build events; far from ideal and quite a deployment nightmare.
Implemented a custom VirtualPathProvider and embedded the ASCX templates within the assembly as embedded resources. Unfortunately when using the Register directive in the consuming application it creates the designer declaration as a UserControl, where I would require a declaration of the actual control type; unforeseen (typically) and undesirable.
Created a Web Deployment Project to compile the UserControls, but the compiled user controls then become part of another assembly, and no longer descend from the class definitions in my web assembly--the assembly needs to instantiate them dependent on the request context.
So number 1 is just crap, number 2 doesn't give me the type support I desire and number 3 I think I'm about to produce a reasonable solution with:
Lump all non-control classes into the App_Code folder, prepare a factory class that will construct an object of the desired control type using reflection and the expectation that the type being reflected will be present in the deployment output (hopefully guaranteed by the presence of the ClassName attribute in the Control directive).
Theres also always the other option of rewriting the ASCX controls into custom controls, but just don't have the resources to consider it at the moment, and we've got no expertise in doing that, and they work fine as UserControls.
Am I missing something obvious, something maybe much simpler, or is this just purposefully difficult? I've read stories of the ASP.NET compilation process being very unfortunate in it's design on my travels across this topic.
Well I think I've done it ... by being mindful of a few of a few annoying pitfalls with my last approach, I recommend the following when compiling ASCX user controls in a Web Application Project using a Web Deployment Project:
Avoid putting classes in App_Code unless they're standalone or helper classes, ASP.NET treats this as a speshul folder, the meaning of which is lost on me, mayhem, confusion and chaos follows. Code in this folder does get output in the Web Deployment Project, though.
Pay close attention to your assembly names, their root namespaces and deployment output assembly name- you'll get access is denied errors if you have any naming conflicts during the aspnet_merge process.
Ultimately you'll most likely end up deploying 2 assemblies, I tried to create only one but the deployment output was still pointing to type definitions in the source assembly. This isn't a problem if you don't have any other types in your Web Application Project--I have so it was a problem for me. In my case, my final output was:
<Organisation>.<TechnologyName>.Web.DLL - Compiled Web Application Assembly (containing the ASCX templates)
<Organisation>.<TechnologyName>.Web.UI.DLL - ASP.NET Compiled UserControl assembly, created by Web Deployment Project
Clean often, and check that the Web Application Project's bin and obj paths are cleared of any previous junk built when you perhaps hadn't finalised your namespace or assembly naming scheme--the Web Deployment Project will be quite keen to include these, causing a fine mess.
Check your imported namespaces, the ASP.NET compiler likes to refer to the Import directive in the ASCX template, and it also considers imported namespaces present in web.config's <configuration><system.web><pages><namespaces> element, tweak if you get unknown definitions appearing during the deployment process.
Have some patience spare, it's quite tricky! But you do get some nice re distributable UserControls at the end of it!
Phew!

Using a custom build provider in an ASP.NET Web Application

I'm trying to find a way to generate an enums class dynamically from lookup tables in a database and still have the convenience of a normal class (i.e. intellisense).
I've spent the past few hours trying to figure out how to get a custom BuildProvider to work inside an ASP.NET Web Application. The code works perfectly in a Web Site. I then found an article on MSDN that says
Adding a customized BuildProvider class to the Web.config file works in an ASP.NET Web site but does not work in an ASP.NET Web application project. In a Web application project, the code that is generated by the BuildProvider class cannot be included in the application. For more information, see Compiling Web Application Projects.
Does anyone know if it is possible to generate code dynamically and still be able to 'use' it at design time? Using a web site is not an option. I need to use a web project.
Thanks!!
what is the point of an enum class for a dynamic lookup table? your code references will always be static anyway...
if the initial population of the lookup table is static, make an enum for that and don't reference any other values in the code
If MSDN is saying you can't do it, I'd take another approach. Maybe write a small Console application that writes your Enums.cs file and run it through the "Pre-build event command line". Then, every time you build the web application, the Enums class gets recreated and should be accessible through Intellisense.
Haven't done this myself. Hope it helps.

Resources