Encrypting Passwords and Keys in web.config

by Anton19. April 2014 19:18

We wanted to encrypt our passwords which we store in the web.config of our Webapplication. Most of the WorldWideweb pointed to the use of aspnet_regiis.exe: http://msdn.microsoft.com/en-us/library/53tyfkaw(v=vs.100).aspx We want to use the encrypted web.config on a few machines, so we need to import the decryption keys on those machines.

I pretty much used the walkthrough provided by Microsoft.

  1. Ceate a custom RSA key container: aspnet_regiis -pc "CampingInfo" –exp
  2. Grant the application access to the keys: aspnet_regiis -pa "CampingInfo" "NT AUTHORITY\NETWORK SERVICE". The ASP.NET identity can be found via creating and calling a page “Response.Write(System.Security.Principal.WindowsIdentity.GetCurrent().Name);”
  3. Add a configuration provider to the web.config:
  4. <configuration>
    <add name="CampingInfoProvider"
    useMachineContainer="true" />

  5. Put the to be encrypted settings in a custom section in the web.config:
    <section name="secureAppSettings" type="System.Configuration.NameValueSectionHandler" />
    <add key="somepassword" value="xyz" />

  6. Encrypt the custom section: aspnet_regiis -pef "secureAppSettings" "C:\<path to dirctory where web.config resides>" -prov "CampingInfo"
  7. Export the RSA key container: aspnet_regiis -px "CampingInfo" "c:\keys.xml" -pri
  8. Copy the xml file to a second server which runs the same application (with the same, now partially encrypted web.config).
  9. Import the RSA key container on the second server: aspnet_regiis -pi "CampingInfo" "c:\keys.xml"
  10. Grant the application on the second server access to the keys as in 2. (Identity may be different.)

enjoyed the post?


Retrieving random content items (rows) from a SQL database in Orchard with HQL queries

by Oliver22. February 2014 12:37

We're adding some Premium functionality to discoverize right now, and part of that is the so-called Premium block which is a showcase of six Premium entries. Now, choosing the right entries for that block is the interesting part: as long as we don't have six Premium entries to show, we want to fill up the left over space with some random entries that haven't booked our Premium feature, yet.

Get random rows from SQL database

There are plenty of articles and stackoverflow discussions on the topic of how to (quickly) retrieve some random rows from a SQL database. I wanted to get something to work simply and quickly, not necessarily high performance. Incorporating any kind of hand-crafted SQL query was really the last option since it would mean to get hold of an ISessionLocator instance to get at the underlying NHibernate ISession to then create a custom SQL query and execute it. Not my favorite path, really. Luckily, the IContentManager interface contains the method HqlQuery which returns an IHqlQuery containing these interesting details:

/// <summary>
/// Adds a join to a specific relationship.
/// </summary>
/// <param name="alias">An expression pointing to the joined relationship.</param>
/// <param name="order">An order expression.</param>
IHqlQuery OrderBy(Action<IAliasFactory> alias, Action<IHqlSortFactory> order);

…and IHqlSortFactory contains a Random() method. This finally got me going!

HQL queries in Orchard

HQL queries are a great feature in (N)Hibernate that allow you to write almost-SQL queries against your domain models. I won't go into further detail here, but be sure to digest that!

Orchard's IContentManager interface contains the method HqlQuery() to generate a new HQL query. Unfortunately, there's almost no usage of this feature throughout the whole Orchard solution. So let me document here how I used the HqlQuery to retrieve some random entries from our DB:

// retrieve count items of type "Entry" sorted randomly
return contentManager.HqlQuery()
    .OrderBy(alias => alias.ContentItem(), sort => sort.Random())
    .Slice(0, count)
    .Select(item => item.Id);

And one more:

// retrieve <count> older items filtered by some restrictions, sorted randomly
return contentManager.HqlQuery()
    .Where(alias => alias.ContentPartRecord<PremiumPartRecord>(),
           expr => expr.Eq("Active", true))
    .Where(alias => alias.ContentPartRecord<PremiumPartRecord>(),
           expr => expr.Lt("BookingDateTime", recentDateTime))
    .OrderBy(alias => alias.ContentItem(), sort => sort.Random())
    .Slice(0, count)
    .Select(item => item.Id);

Even with the source code at hand, thanks to Orchard's MIT license, the implementation of this API in the over 600 lines long DefaultHqlQuery is not always straight-forward to put into practice. Most of all I was missing a unit test suite that would show off some of the core features of this API and I'm honestly scratching my head of how someone could build such an API without unit tests!

Random() uses newid() : monitor the query performance

The above solution was easy enough to implement once I've got my head around Orchard's HQL query API. But be aware that this method uses the newid() approach (more here) and thus needs to a) generate a new id for each row in the given table and b) sort all of those ids to then retrieve the top N rows. Orchard has this detail neatly abstracted away in the ISqlStatementProvider implementation classes. Here's the relevant code from SqlServerStatementProvider (identical code is used for SqlCe):

public string GetStatement(string command) {
switch (command) {
case "random":
return "newid()";
return null;

For completeness, here's the generated SQL from the first query above (with variable names shortened for better readability):

select content.Id as col_0_0_
from Test_ContentItemVersionRecord content
inner join Test_ContentItemRecord itemRec
on content.ContentItemRecord_id = itemRec.Id
inner join Test_ContentTypeRecord typeRec
on itemRec.ContentType_id = typeRec.Id
where ( typeRec.Name in ('Entry') )
and content.Published = 1 order by newid()

This approach works well enough on small data sets but may become a problem if your data grows. So please keep a constant eye on all your random queries' performance.

Happy HQL-ing!

GIT tip: fast-forward local branch to the head of its remote tracking branch without checking it out

by Oliver6. February 2014 00:23

Not much else to say than what's mentioned in the title. I come across the need to do so mostly before deployments from my machine where I want to update my local master branch to the HEAD of the remote master branch. Here's how to do that:

   1: git fetch origin master:master

Thank you stackoverflow and Cupcake!

Productivity boost with MSBuild: use /maxcpucount

by Oliver28. January 2014 21:24

This is embarrassing. For the n-th time during the past couple of years I've felt an unease waiting for our projects (read: solutions) to compile. I kept seeing this:


This is MSBuild using 1 (!), yes, one!, of the 8 CPU cores I've sitting in my machine to get my work done. What about the other 7? Why don't you use them, MSBuild? With that single core, currently my simple local build of our project discoverize takes around 36 seconds:


Tell MSBuild to use all cpu cores

Well, it's as easy as adding /m or /maxcpucount to your msbuild command line build to boost your build times:

image image

Down to 8 seconds with 3 additional characters: [space]/m. That's easily a 4.5 times improvement!

Your mileage may vary

Of course, every project is different, so your speed increase might be higher or a lot lower than what I've seen. But it's an easy measure to get at least some improvement in build times with very little effort. Don't trust Visual Studio on that one, though – the solution builds slowly there, still.

For reference, let me tell you, that the /maxcpucount switch can actually take a parameter value like so: /maxcpucount:4. So if you lots of other stuff going on in the background or I don't know for what reason, really, you can limit the number of cpus used by MSBuild.

Props to the Orchard team for a highly parallelizable build

One of the specifics of the Orchard source code that's the base for discoverize is the very loose coupling between the 70+ projects in the solution. This allows MSBuild to distribute the compilation work to a high number of threads because there are almost no dependencies between the projects that MSBuild would have to respect. Great work!

Happy building!

Where would *you* put your job offer?

by Oliver28. January 2014 01:20

Last year, we were looking for a developer to strengthen our team and we put the job offer on our homepage. Nothing fancy there. Booking.com found a much more interesting place to put their job offer without much noise. Look at this Fiddler screenshot:


This response is from today so if you're looking for a job in Amsterdam, go get it!

Orchard CMS - ContentPart will not update if made invisible through placement

by Oliver17. December 2013 22:01

Today we decided that auto-updating our entries' urls when their names change is a rather good idea. Our entries are ContentItems consisting of our custom EntryPart, an AutoroutePart, and some more that are not important here. I thought it would be a matter of minutes to get this user story done. Simply set the correct Autoroute setting inside a migration step and it should work:

public int UpdateFrom9() {
         "Entry", cfg => cfg.WithPart(
             acfg => acfg.WithSetting("AutorouteSettings.AutomaticAdjustmentOnEdit", "true")));
     return 10; }

Well, it didn't.

Placement affects ContentPart updates

In discoverize, we offer a distinct management area (totally separated from the Admin area) where owners of entries can edit their own entry's data but not much more. The decision which url should point to their respective entry is one that we don't want them to make so we simply never rendered the AutoroutePart's edit view using the following line in our management modules placement.info file:

<Place Parts_Autoroute_Edit="-" />

It turned out that this will cause Orchard to skip running through the POST related Editor() overload in the AutoroutePartDriver because in the ContentPartDriver.UpdateEditor() method there is an explicit check for the location of the currently processed part being empty:

if (string.IsNullOrEmpty(location) || location == "-") {
     return editor; }

Because of the above check, the handling of the AutoroutePart of the currently saved entry is stopped right there and the code that is responsible for triggering the url regeneration based is never called.

Updating ContentParts despite Invisible Edit View

The solution is simple – thanks to Orchard's phenomenal architecture – and consists of two steps:

  1. Make the AutoroutePart's edit view visible in the placement.info:
    <Place Parts_Autoroute_Edit="Content:after"/>
  2. Remove all code from the AutoroutePart's edit view:

With this in place, Orchard won't enter the if (location == "-") condition above but instead will execute the url regeneration we were after in the first place.

Beware of Unrendered Views

So, Orchard connects certain behavior to the visibility of our parts' rendered views. Not what I'd call intuitive, but at least now we know.

Happy Coding!

IRIs and URIs; or: Internet Explorer does not decode encoded non-ASCII characters in its address bar

by Oliver24. October 2013 23:03

Some facts about IE and its address bar

IE can display non-ASCII characters in the address bar if you put them there by hand or click a link that contains such in unencoded form, e.g. http://marinas.info/marina/fürther-wassersportclub.

IE sends a request for the correctly encoded URL, which is http://marinas.info/marina/marina/f%C3%BCrther-wassersportclub.

Now, if you're in IE and click on the second link above, IE will not decode the URL back to the unencoded version – it will just keep the encoded URL in the address bar. If, instead, you're reading this page in FF or Chrome, the encoded URL above will be gracefully decoded into its unencoded counterpart.

URIs and IRIs


First off, let me tell you that I'm by no means an expert in this field. I'm trying to get my around URIs, IRIs, encodings and beautiful web sites and URLs just like probably half of the web developer world out there. So please, verify what you read here and correct me where I am mistaken.

What the RFCs have to say

By today, more than a handful of RFC documents have been published concerning URIs:

RFC 3986 states the following about a URI:

A URI is an identifier consisting of a sequence of characters matching the syntax rule named <URI> in Section 3.

See the examples section, or refer to Appendix A for the ABNF for URIs.

RFC 3987 states the following about an IRI:

An IRI is a sequence of characters from the Universal Character Set (Unicode/ISO 10646).

In short, IRIs may contain Unicode characters while URI must not. Moreover, every URI is a valid IRI and every IRI can be encoded into a valid URI. Let's see an example again:

A great read on IRIs and their relationship to URIs can be found here by the W3C.

Support for IRIs

IRIs are not supported in HTTP as per RFC 2616. This implies that before requesting a resource identified by an IRI over HTTP it must be encoded as a URI first. This is what all mainstream browsers seem to do correctly – when you click on http://marinas.info/marina/marina/fürther-wassersportclub and inspect the request sent from your browser you will see that it actually requests http://marinas.info/marina/marina/f%C3%BCrther-wassersportclub.

HTML5 support IRIs as URLs: http://www.w3.org/html/wg/drafts/html/CR/infrastructure.html#urls.

Use IRIs today

It looks like you can safely use IRIs in your HTML pages today already. And doing so will actually persuade IE into displaying the correct non-ASCII characters. So why don't we?

JavaScript Coding Dojo bei ALT.NET Berlin

by Anton9. October 2013 11:41

I haven’t been to a coding dojo for quite some time. Since I have deficiencies in JavaScript, this sounded like fun. The event was again held at Hotelplan CC Services, and Mike Bild was the one who showed us the ropes.

He gave us an introduction to node.js, which is a packaged compilation of Google’s V8 JavaScript engine. It is quite extensible, for instance via the npm package manager (similar to nuget). There are many testing frameworks – Mike showed us and used mocha. It even has a runner, wich runs all the tests as soon as you make a change to the code (similar to ncrunch). After the explanatory part to all the tools, we started solving the KataTennis by applying TDD. It went quite well, the results can be seen here.

In the end Mike told us a bit about the task runner Grunt, and the possiblity to convert node.js code with requires into browser code with browserify.

Using Unit Tests to Satisfy SpecFlow Scenarios

by Anton2. October 2013 15:16

Ususally we spec out features using SpecFlow. Then we write out the step definitions and code the feature (or vice versa). When we programmed the “export entries” feature for the portal management area of discoverize, we did so using TDD (test driven development) with unit tests. Since it is an MVC project, we could mock the controller (and the services needed). It all went well, and in the end the feature was coded. Yet, the SpecFlow scenario had no step definitions to fulfill it.

Scenario: Export every property from every entry
Given I have 2 entries
When I export all properties
Then I get a file with 3 lines
And the first line are the column names, that is the property names
And each other line represents the data of one entry

Usually we write steps that follow links and push buttons in the web interface – as the user would do. This time – since we already had good coverage of the controller action – we decided to hook up the unit tests as the step definitions.

This is quite easy if you know how. We used the @unittest tag to suppress starting the IIS Express and browser for this scenario. Since our unit tests are in a different project than the SpecFlow tests we did everything according to this documentation. After a little refactoring in the unit tests to extract appropriate methods for the steps and adding the step attributes the SpecFlow scenario went green.

[Then(@"I get a file with (\d+) lines"), Scope(Tag = "unittest")]
public void FileHasLines(int numberOfLines) {
var lines = _exportText.Split('\n');
Assert.AreEqual(numberOfLines, lines.Count());

Deleting a Table from Orchard's SQL CE Database

by Oliver21. September 2013 11:08

In day-to-day development on discoverize, our Orchard based custom portal software, I use CompactView to look into my local instance's SQL CE database file if that's what I need to do.

Dropping a Table from my Orchard.sdf Database

Today, I was experimenting with some migrations code and needed to undo some table creation so that I could run an improved version on the same DB. I hoped for CompactView to get the job done, but somehow I couldn't get around how to do it from there. I tried running the following script from its SQL editor:

ALTER TABLE [Discoverize_Management_UsersEntriesPartRecord] DROP CONSTRAINT [PK__Discoverize_Management_UsersEntriesPartRecord__000000000000104D];
DROP TABLE [Discoverize_Management_UsersEntriesPartRecord];

Unfortunately, CompactView told me that the table was currently in use:


I was a bit baffled by this error. Somehow I had expected it to just work.

SqlCeCmd to the Rescue

Well, all is not lost. For some tasks I've already used the SQL Compact Command Line Tool in the past and it was waiting to be used again. This is what I first tried (without the newlines):

SqlCeCmd40.exe -d "Data Source=App_Data\Sites\Default\Orchard.sdf" -q "ALTER TABLE [Discoverize_Management_UsersEntriesPartRecord] DROP CONSTRAINT [PK__Discoverize_Management_UsersEntriesPartRecord__000000000000104D]; DROP TABLE [Discoverize_Management_UsersEntriesPartRecord];"

Unfortunately, this query returned an error:

There was an error parsing the query. [ Token line number = 1,Token line offset = 148,Token in error = DROP ]

This error referred to the DROP in the DROP TABLE statement which surprised me but a simple workaround was to just send two queries to the DB instead of a single one:

SqlCeCmd40.exe -d "Data Source=..\src\Orchard.Web\App_Data\Sites\Default\Orchard.sdf" -q "ALTER TABLE [Discoverize_Management_UsersEntriesPartRecord] DROP CONSTRAINT [PK__Discoverize_Management_UsersEntriesPartRecord__000000000000104D]"

(-1 rows affected)

C:\Projects\discoverize\tools>SqlCeCmd40.exe -d "Data Source=..\src\Orchard.Web\App_Data\Sites\Default\Orchard.sdf" -q "DROP TABLE [Discoverize_M

(-1 rows affected)

Checking back with CompactView, I verified that the table was now successfully deleted.

Do it Step by Step

I'm not a guru with SQL CE databases but verifying that my syntax was correct and breaking the task into smaller pieces already got me back on track.

Happy coding!

About Oliver

shades-of-orange.com code blog logo I build web applications using ASP.NET and have a passion for jQuery. 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 daughter.

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.