HTTP Error 500.19 - Internal Server Error: 0x8007007b Cannot read configuration file

by Oliver 20. March 2013 15:24

While setting up a specification tests project for our new TeamReview tool, I was facing an HTTP 500.19 error when hosting our site in IIS Express. There are lots of questions on stackoverflow concerning this error, Microsoft has a whole page on it, but there is a whole bunch of suberrors that this error addresses. Error 0x8007007b: Cannot read configuration file Unfortunately, none of the above mentioned links contained or solved the specific error code I was seeing: Error Code    0x8007007b Config Error    Cannot read configuration file Config File    \\?\C:\Projects\_teamaton\teamreview\TeamReview.Specs\bin\Debug\..\..\..\TeamReview.Web\web.config After some reading, trying, fiddling, it appeared to me that maybe the path to the config file somehow messed up IIS Express. I admit that it was at least a bit unusual to use the parent directory dots. But it came from my test harness code where I wanted to use relative paths and used Path.Combine() to do that: var webPath = Path.Combine(Environment.CurrentDirectory, "..", "..", "..", "TeamReview.Web"); Pitfall: .. in path Well, it turns out IIS Express didn't like it. Once I called it with a cleaned up path string, everything just worked: "C:\Program Files (x86)\IIS Express\iisexpress.exe" /path:"C:\Projects\_teamaton\teamreview\TeamReview.Web" /port:12345 /systray:false So, watch out for your physical path values when using IIS Express! Use DirectoryInfo to navigate up your directory tree To get the correct path without using absolute paths but also avoiding the .. I used the DirectoryInfo class: var webPath = Path.Combine( new DirectoryInfo(Environment.CurrentDirectory).Parent.Parent.Parent.FullName, "TeamReview.Web");

Automatic Deployment of a New Discoverize Portal

by Oliver 11. March 2013 15:02

This is a technical post about how we automatically deploy new portals that will be run by our own portal software discoverize. After filling in and submitting our portal creation form we do the following: Save the entered information into /App_Data/<PortalName>/portal.xml Trigger the TeamCity build through a web request to a specific URL Send an email with the request status or any errors that occurred Display a Thank You page. Now, the TeamCity build configuration that was triggered under 2. does the following: Execute the Powershell script create-portal.ps1 in c:\projects\discoverize create the AppPool Discoverize-Portals if it doesn't exist yet (all our portals run within it) iterate over all folders inside wwwroot\discoverize.com\App_Data if a folder with the same name exists under wwwroot\discoverize-portals, skip it else move the current folder from wwwroot\discoverize.com\App_Data to wwwroot\discoverize-portals add a line with the full path to the new portal folder to newportals.txt (e.g. C:\inetpub\wwwroot\discoverize-portals\<PortalName>) add a new site to IIS and set its AppPool to Discoverize-Portals start the new site in IIS (needs Admin privileges, that's why we use a parameterized task scheduler task for that) Build the source code from the repository Execute the Deploy-NewPortals target from deploy.proj using MSBuild in c:\projects\discoverize Iterate over the entries in newportals.txt, for each entry do: Copy the build output from step 2. to wwwroot\discoverize-portals\<PortalName> Run the site setup (this uses Orchard's setup method) with our own recipe (using Orchard.exe) Call an action (SetupComplete) on the new site to mark deployment as done Create a default entry so there's something to look at (using Orchard.exe) The SetupComplete action then finishes doing this: save the information of the portal.xml into an application specific configuration file create new user "portal-owner" for content management send an email about the successful installation of the new portal Quite complex, if I look at it now, but it works!

SQL Server Compact timed out waiting for a lock

by Oliver 28. January 2013 14:26

Today, I faced the exception mentioned in the post title: SQL Server Compact timed out waiting for a lock. The default lock time is 2000ms for devices and 5000ms for desktops. The default lock timeout can be increased in the connection string using the ssce: default lock timeout property. (Plus some session details). Circumstances The exception was thrown in my local dev environment while working on our Orchard CMS based portal software discoverize, calling any page in the portal. Obviously, something was wrong not with a single page but rather with a piece of infrastructure. Interestingly enough, only a few moments before trying to open the web site I had done some database manipulation using SqlCeCmd deleting some unneeded columns from one of our tables. It seems that after that the site broke. Solutions tried I tried to get hold of the DB like this: stop and start the web site in IIS (using appcmd stop site "discoverize" and appcmd stop site "discoverize") – no change take DB offline by renaming the file – waited a few moments, renamed it back – no change! Here I started wondering where the lock is saved – is it inside the DB? took the whole application pool offline and restarted it – bang! That helped. I now have my site back up and running and can continue develepment. Conclusion If you encounter the SQL CE timeout error during development inside a web application, restarting the app's app pool will probably get you back to work. Happy coding!

SQL Server Compact timed out waiting for a lock

by Oliver 28. January 2013 14:26

Today, I faced the exception mentioned in the post title: SQL Server Compact timed out waiting for a lock. The default lock time is 2000ms for devices and 5000ms for desktops. The default lock timeout can be increased in the connection string using the ssce: default lock timeout property. (Plus some session details). Circumstances The exception was thrown in my local dev environment while working on our Orchard CMS based portal software discoverize, calling any page in the portal. Obviously, something was wrong not with a single page but rather with a piece of infrastructure. Interestingly enough, only a few moments before trying to open the web site I had done some database manipulation using SqlCeCmd deleting some unneeded columns from one of our tables. It seems that after that the site broke. Solutions tried I tried to get hold of the DB like this: stop and start the web site in IIS (using appcmd stop site "discoverize" and appcmd stop site "discoverize") – no change take DB offline by renaming the file – waited a few moments, renamed it back – no change! Here I started wondering where the lock is saved – is it inside the DB? took the whole application pool offline and restarted it – bang! That helped. I now have my site back up and running and can continue develepment. Conclusion If you encounter the SQL CE timeout error during development inside a web application, restarting the app's app pool will probably get you back to work. Happy coding!

URL Rewriting and Routing in Orchard CMS / ASP.NET MVC

by Oliver 28. August 2012 23:41

Working on Marinas.info, we want to create SEO friendly links to specific searches that will hopefully rank high up in the search engines. They should look something like www.marinas.info/germany for marinas situated in Germany or www.marinas.info/wífi for marinas that provide wifi internet access. We also plan on supporting most European languages, some 30+ or so, even if not from the start. Anyway, the number of URLs we will generate is likely to explode, and we need a solution to consistently generate and handle those thousands of different URLs. This post investigates a few solutions that have popped up. External URL Rewriting solutions – UrlRewritingNet and the IIS Url Rewrite Module The two solutions listed here are called external because they integrate with the ASP.NET MVC request pipeline in way that they will be invisible to the actual web application. Routes would be rewritten in an early step and the application would only get to see the rewritten URL that it would know how to handle. UrlRewritingNet Since 2006, UrlRewritingNet has been around and I assume it’s a widespread solution. We use it in Camping.info, and probably the best part is the easy configuration. Still, I remember that we had a few problems with it that needed fixing, so we would most likely have to use that slightly customized version. I’m not 100% sure if it would work with MVC out of the box since we’ve only used it with ASP.NET WebForms. IIS Url Rewrite Module This is a solution by Microsoft that would certainly get the job done, too. I haven’t really used it yet in any larger project though, so I’d have to dive into it first. If you feel like giving it a go, check out http://learn.iis.net/page.aspx/734/url-rewrite-module/. Internal solutions – Orchard Rewrite Rules and ASP.NET MVC Routing These approaches work inside the application. Orchard Rewrite Rules Orchard Rewrite Rules is an Orchard Module that brings (a subset of) mod_rewrite style URL rewriting to any Orchard installation. We’ve successfully used it e.g. to redirect traffic from http://marinas.info to http://www.marinas.info. The greatest benefit is that it’s just another module that you can simply enable and disable at runtime from within the application without a need to recycle the app pool as would be the case for the two external rewriting solutions since their configuration is coupled to the web.config file. The drawback of this solution is that we’re also new to its syntax and it’s not that clear (yet) how we would efficiently map the thousands of routes with their dynamic values that we are aiming at. ASP.NET MVC Routing It seems that ASP.NET MVC’s built-in routing engine can provide us with what we are looking for. At first glance, looking at the standard examples of route definition, it didn't appear that promising. Remember, we want to support URLs such as www.marinas.info/germany and www.marinas.info/wifi for a lot of search categories. The routes to match those request would either have to be very specific, e.g. one per category, or very general, e.g. one for all categories. The first approach would lead to the thousands of routes I mentioned earlier, the latter would also catch requests for other parts of the application that might have nothing to do with search since it’s so general. It turns out there are more advanced features in ASP.NET MVC Routing that allow to overcome these restrictions. Custom Route Constraint with IRouteConstraint and Custom Route Handler with MvcRouteHandler This answer on Stack Overflow to a question concerning exactly the same problem points to a blog post on writing your own Route Constraint which is a great way to deal with the second problem mentioned above, that a too general route would match too many requests. The custom route constraint could e.g. constrain the application of a certain route to only valid values. Another approach, presented in this post on SEO friendly URLs in MVC, would be to derive from the default MvcRouteHandler and implement some custom logic to handle our custom URLs. Conclusion: ASP.NET MVC Routing has it all I’m glad I set out to examine those different solutions because I totally underestimated the power of ASP.NET MVC Routing if I hadn’t. Another great post on Optimizing ASP.NET MVC3 Routing talks about even more of its aspects and how Stack Overflow handles their large number of routes with high performance using (mostly) built-in functionality. Looks very much like this is the way to go! Happy coding!

Writing Acceptance Tests for an Orchard / ASP.NET MVC Application – using SpecFlow, Coypu (Selenium) and the MvcIntegrationTestFramework

by Oliver 22. August 2012 13:48

When we started development on Marinas.info, we decided to write acceptance tests for all important features of our application. This decision was even more justified by the fact that a bunch of similar platforms are to follow using the same codebase. We wanted an application with less bugs and easier maintenance. Writing good, automated acceptance tests is not easy and it’s not fast, either. For some time now, we’ve been trying to get the first set of our tests run green, which proved especially tricky on our TeamCity continuous integration server. This post investigates a working solution. The ingredients: SpecFlow, Coypu (Selenium), Browser, Web Server, and MvcIntegrationTestFramework SpecFlow In .NET world, using SpecFlow to write acceptance tests is nothing new and has recently become, yet again, more appealing after its update to version 1.9. One of our scenarios for verifying image upload functionality looks like this: It’s simple to write, easy to read and great living documentation. For Browser based tests you need: Coypu (Selenium) Everyone who has written tests for Selenium for even a mildly ajax-y site knows how painful it can be to create reliably working tests. Coypu alleviates the pain and makes test creation as straight-forward as it should be in the first place. Coypu is: A robust wrapper for browser automation tools on .Net, such as Selenium WebDriver that eases automating ajax-heavy websites and reduces coupling to the HTML, CSS & JS A more intuitive DSL for interacting with the browser in the way a human being would A few examples of Coypu’s clean API can be seen here in one of the step definitions for the above scenario (Browser is an instance of the BrowserSession class from Coypu): A web browser To run browser based tests you, of course, need … a browser! Coypu offers support for quite a bunch of them, including the usual suspects Internet Explorer, Chrome, and Firefox. A web server You need to host your application in some web server or another to process requests. Well, this statement turns out to be only partially true, as you will see with the MvcIntegrationTestFramework. But at least for browser based test you need a web server, and you basically have the choice between IIS and IIS Express (if you don’t want to write your own or use someone else’s implementation). We chose IIS Express as it is manageable through a non-administrator account, but it needs to be installed on all machines that will execute the tests. For non-browser based tests: MvcIntegrationTestFramework Introduced by Steven Sanderson in 2009, this small framework allows to write integration tests for ASP.NET MVC applications and execute them without a browser! It empowers you to make assertions on your controllers’ actions’ results rather than on the rendered html output by injecting some clever hooks into your MVC application under test. An example of how a test would look can be found in the above mentioned post. The “magic” of this framework lies in the use of ApplicationHost.CreateApplicationHost() which creates an application domain for hosting your ASP.NET application. Check out this screenshot of part of the source code: How to put the pieces together After a quite radical evolution of our test code (which you can read up on in my follow-up post The Long Road to Browser Based Acceptance Testing), we finally settled for the following: Before the first test starts, setup an instance of the AUT (application under test). This includes: deploying the AUT as we do for our staging environment, but to a temp folder initialize an AppHost instance à la MvcIntegrationTestFramework, i.e. an ASP.NET enabled application domain that hosts the AUT execute the Orchard setup command via the AppHost instance (instead of running the setup through a browser, which we used to do but was a lot slower) Before each test run (SpecFlow scenario) we then execute various commands to setup the environment for the concrete test, e.g.: clean the database simply by overwriting it with a copy we saved after the initial setup create Marina entries that will be displayed and searchable on the site, again, using the AppHost instance Once we want to execute steps in the browser, we do the following: start an instance of IIS Express pointing to the deployed application (we used the wrapper code from Spinning up IISExpress for integration testing) initiate a Coypu BrowserSession which under the hood creates an instance of the browser you choose after battling with Internet Explorer, Chrome, and Firefox Portable, we now use Firefox 10.0.6 ESR (Extended Support Release) because version 10 is of now the highest version supported by Selenium (2.1.25) and the ESR doesn’t ask to be updated all the time After each test run (SpecFlow scenario) we do this: close the browser shut down the IIS Express instance (we slightly modified the above mentioned wrapper code calling Kill() on the process instance after the call to CloseMainWindow() so that it reliably terminates even on TeamCity) Conclusion Setting up a reliable environment for automatically executing acceptance tests has not been a walk through the park but we finally have a solution that basically “just works”. Hopefully, our experience will help you save a couple of hours and also some headache along the way Happy coding!

From batch string replacement to date time formatting – a list of often used web resources

by Oliver 27. June 2012 14:40

This is only the beginning… Batch String replacement: http://ss64.com/nt/syntax-replace.html Date formatting T-SQL, using CONVERT or CAST: http://msdn.microsoft.com/en-us/library/ms187928.aspx .NET: Custom Date and Time Format Strings, Standard Date and Time Format Strings Windows Open recent window from taskbar when clicking on icon instead of showing list of open windows: http://www.howtogeek.com/howto/16334/make-the-taskbar-buttons-switch-to-the-last-active-window-in-windows-7/ Logging Filters for log4net: http://www.claassen.net/geek/blog/2009/06/log4net-filtering-by-logger.html

A jQuery based tooltip solution for a large web application

by Oliver 13. March 2012 01:37

Finally, with an update we rolled out last week, (almost) all tooltips on Camping.Info look and behave similar, differing mostly in positioning and size, but not in the general look and feel. We chose the jQuery Tools Tooltip as the base for our own solution and it got us pretty far, but there were some pitfalls and scenarios that we needed to handle ourselves. This post is about what limitations we experienced and how we dealt with them. The original As you can read in the jQuery Tools Tooltip documentation, the tooltip plugin is highly configurable. It can take different elements as the tooltip for any given trigger: the value of title attribute of the trigger element the html element immediately following the trigger the html element immediately following the first parent of the trigger an arbitrary html element on the page. You can also position the tooltip pretty much wherever you want relatively to the trigger: Our adaptations Another way to chose the tooltip We found one more useful way to define the tooltip for a trigger element: if the trigger is e.g. a table cell in an html table and you don’t want to specify a static tooltip for some or all table cells but a different one for each cell or at least a number of cells, it makes sense to define the tooltip element inside the trigger (the table cell). Since this effect was not achievable extending the jQuery Tools Tooltip plugin we started changing their source: Breaking the tooltip out of some parent container We also faced some problem properly showing tooltips that needed to “break out” of some bounding box, inside which they were defined (i.e. their html markup). This problem e.g. occurred inside elements with style position: relative, which we have a few of on Camping.Info. Our first attempt was to clone the tooltip element and show the clone instead of the original. This worked in almost all cases – until we tried to attach some more behavior to elements inside the tooltip. The behavior, e.g. some click event handler that we expected to fire when clicking on some element inside the tooltip, wouldn’t execute, since we were working with the clone! So we decided to simply move the tooltip up in the DOM tree for the time it is being shown, more precisely just beneath the form tag that we have on all our pages. We create a placeholder at the place where we removed the tooltip to reinsert it again once it’s being hidden. The code we added to the show() method looks like this: … and here’s the counterpart in hide(): Now, this works quite well everywhere, independent of the position of the tooltip in the DOM tree. Global tooltip configuration Using inline static configuration One feature we quickly missed was some kind of static tooltip configuration without calling  $(...).tooltip({ settings: ... }) for every single tooltip we wanted to create or hook up, respectively. What we came up with is to use the HTML5 data attributes to define any specific configuration statically inside the trigger element’s html markup. Thus, we need to call the tooltip initialization code only once for the whole page. The configuration now looks like this: We use specific prefixes with the data attributes to make them easier to understand, e.g. data-tt-position for an attribute that is used for tooltips and jq-tt-trigger for a class that is used by some jQuery code for tooltips. To process this kind of static configuration we need some custom code that will, at some point, call the original (well, modified by now) plugin code. Unfortunately, the jQuery Tools Tooltip plugin was not designed to allow runtime configuration of the tooltip to show, but we found a way using the onBeforeShow and onHide event handlers. The basic idea is to change the global Tooltip configuration during the first method so that the tooltip we will be showing will be configured correctly, and to reset the global configuration once the tooltip has been hidden again. To achieve this, we iterate over all configuration properties that the jQuery Tools Tooltip plugin supports and search for the respective data attributes on the currently processes trigger element. One example would be the position property: to replace the default value provided by the plugin we look for an attribute that’s called data-tt-position and use its value to temporarily overwrite the default value during the onBeforeShow event handler. Using global profiles Once we had the static configuration working and started to replace all of those clumsy and overly complicated AjaxControlToolkit HoverMenuExtenders, it quickly turned out that we were copy’n’pasting the same configuration in a thousand places. This was not only ugly and violated the DRY principle, it also lead to some unnecessarily bloated html. As a solution to this maintenance nightmare we came up with profiles that comprise a set of configuration options that would else be repeated over and over again: Now, they lead to some really clean html markup: The only change from using the inline static configuration is to use the profile’s properties – everything else stays the same! Conclusion The jQuery Tools Tooltip plugin is a nice, small and highly configurable tool for easy tooltip creation and usage. In a larger web application there a few shortcomings that we’ve addressed here and which we’ve provided working solutions for. We hope to release those changes soon in its own project on our GitHub account. Happy coding!

ToDebugString() – give me some debug info about my object, e.g. Request.Url

by Oliver 16. September 2011 20:06

Lately, I was having trouble debugging certain parts of my code in Visual Studio, and all I wanted to know was the value of some variable at some point in time. Well, I’d use some logging if I could just get at that value easily. But for some objects I don’t really know what I’m looking for or where I should be looking for it. So just give me the values of all the members of that object, will ya? And could you recurse that? But no deeper than 3 levels, alright? Or let’s say… 5? public static string ToDebugString(this object obj, int maxdepth, int depth=0) { if (obj == null) return "null";   if (obj is IConvertible) return obj.ToString();   if (depth >= maxdepth) return "...";   var sb = new StringBuilder();   if (depth > 0) sb.AppendLine();   foreach (var propertyInfo in obj.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance)) { sb.Append(new string(' ', 2*depth)).Append(propertyInfo.Name).Append(": "); try { var value = propertyInfo.GetValue(obj, new object[0]); sb.AppendLine(ToDebugString(value, maxdepth, depth + 1)); } catch (Exception ex) { sb.AppendLine(string.Format("[{0}]", ex.Message)); } }   // remove newline from end of string var newLine = Environment.NewLine; if (sb.Length >= newLine.Length) sb.Replace(newLine, "", sb.Length - newLine.Length, newLine.Length);   return sb.ToString(); } With this little helper I can now simply call anyobject.ToDebugString(4 /* maxdepth */) and I get a nicely formatted debug view of that object; e.g. Request.Url.ToDebugString(3) gives me: AbsolutePath: /logg.aspxAbsoluteUri: http://localhost:55235/logg.aspxAuthority: localhost:55235Host: localhostHostNameType: DnsIsDefaultPort: FalseIsFile: FalseIsLoopback: TrueIsUnc: FalseLocalPath: /logg.aspxPathAndQuery: /logg.aspxPort: 55235Query: Fragment: Scheme: httpOriginalString: http://localhost:55235/logg.aspxDnsSafeHost: localhostIsAbsoluteUri: TrueSegments: Length: 2 LongLength: 2 Rank: 1 SyncRoot: Length: 2 LongLength: 2 Rank: 1 SyncRoot: ... IsReadOnly: False IsFixedSize: True IsSynchronized: False IsReadOnly: False IsFixedSize: True IsSynchronized: FalseUserEscaped: FalseUserInfo: Nice Right now this method chokes on indexed properties but once I’ll need it I’ll go and look for a way to include them. It also chokes any exceptions on the way to just get the job done. Happy coding!

MSBuild and Visual Studio 2010 generate different DLLs

by Oliver 6. September 2011 22:18

Recently, we encountered a quite surprising behavior of MSBuild – the continuous integration build of our new collaborative Todo Management app (we hope to go into beta soon!) would produce a broken version whereas the local build with VS2010 was all smooth and well. Our admin and tester already posted about this problem over at his blog: MSBuild does not build like Visual Studio 2010. The exception message finally led me down the right path: Server Error in '/' Application. No constructors on type 'Teamaton.TodoCore.Repositories.TodoRepositoryJson' can be found with 'Public binding flags'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: Autofac.Core.DependencyResolutionException: No constructors on type 'Teamaton.TodoCore.Repositories.TodoRepositoryJson' can be found with 'Public binding flags'. The TodoRepositoryJson is a type we used at the very beginning of our development to quickly get started using a JSON document as data store. Later we switched to SQLite, so now we have another implementation: TodoRepositoryDb. Both implement the same interface ITodoRepository. Turns out, the Autofac type registering code was the culprit: 1: var builder = new ContainerBuilder(); 2: builder.RegisterAssemblyTypes(typeof (Todo).Assembly) 3: .Where(t => t.Name.Contains("Repository")) 4: .AsImplementedInterfaces() 5: .InstancePerLifetimeScope(); What worked with Visual Studio, didn’t work with MSBuild: obviously – well, now it is – both ITodoRepository implementations were registered with Autofac, and while Autofac’s assembly scanning delivered them in the order we assumed from the DLL built with VS  – first, TodoRepositoryJson, and second, TodoRepositoryDb, thus overriding the first registration – MSBuild seems to build a DLL which returns the inverse order! Very strange. Honestly, I’m not familiar with the anatomy of DLLs and surprised by this result. But it’s the only explanation I’ve found so far. Well, the solution to the problem is, of course, to care more about what we register with Autofac and in which order. Happy coding, Oliver

About Oliver

shades-of-orange.com code blog logo I build web applications using ASP.NET and have a passion for javascript. Enjoy MVC 4 and Orchard CMS, and I do TDD whenever I can. I like clean code. Love to spend time with my wife and our children. My profile on Stack Exchange, a network of free, community-driven Q&A sites

About Anton

shades-of-orange.com code blog logo I'm a software developer at teamaton. I code in C# and work with MVC, Orchard, SpecFlow, Coypu and NHibernate. I enjoy beach volleyball, board games and Coke.