‘console’ is undefined

As shown in this post logging to the console can be very useful when writing JavaScript code. Unfortunately, the JavaScript console is not evenly supported by all browsers. You first have browsers which don’t know it at all (like IE8) and will throw the error which I use as the title of this post. And then even two browsers which do have a console object do not all implement the same functions.

Here’s a short overview of what’s supported by which browser (note that if you do not have the latest version of a specific browser, this particular version may not support all listed functions):

Function Firefox Chrome Internet Explorer Safari Opera
assert X  X  X
clear X  X
count X X  X  X  X
debug X X  X  X  X
dir X X  X  X
dirxml X  X  X  X
error X X  X  X
_exception X
group X X  X  X  X
groupCollapsed X X  X  X  X
groupEnd X X  X  X  X
info X X  X  X
log X X  X  X
markTimeline  X
profile X X  X
profileEnd X X  X
table X
time X X  X  X  X
timeEnd X X  X  X  X
timeline X
timelineEnd X
timeStamp X
trace X  X  X  X
warn X X  X  X

So even though there are quite a few functions supported by all browsers, you should still check whether the console exists and whether the particular function you want to use exists. But adding before each call to a console function a check for the console and for the function quickly becomes a pain.

A way to work around it is to:

  1. Create a dummy console object if console is not defined
  2. Create dummy functions for all functions not supported by the console object in this particular browser

The dummy console object is created by this code:

if (!window.console) {
        window.console = {};
}

So simple, if the global console variable doesn’t exist, create one as an empty object. Now we’ve got either a real console object or a dummy object, we got rid of the error message saying that console is undefined. But we’ll still get errors when our code calls undefined functions. So let’s go through all functions and for each of them create a dummy function if missing:

(function() {
	var funcList = ["assert", "clear", "count", 
		"debug", "dir", "dirxml", "error", 
		"_exception", "group", "groupCollapsed", 
		"groupEnd", "info", "log", "markTimeline", 
		"profile", "profileEnd", "table", "time", 
		"timeEnd", "timeline", "timelineEnd", 
		"timeStamp", "trace", "warn"];

	var funcName;

	for (var i=0; i < funcList .length; i++) {
		funcName = funcList [i];
		if (!window.console[funcName]) {
			window.console[funcName] = function() {};
		}
	}
})()

Here a few explanations how this works. First wrapping it all in (function() { … })() is used to scope the variables we define in there, so that we do not pollute the global scope.

Then we define an array containing all known console functions and iterate through them. For each function, we check whether the console object (the real one or the dummy one) have such a function defined. If not, we assign an empty function. This is done by using the fact that functions of an object are just special properties of the object and that object properties are indexed.

So, using this, you will get rid of all errors related to the console being undefined or console functions being undefined, but of course since we add empty implementations, using these empty implementations will still have no effect.

Of course, instead of using empty implementations you could log the calls to console functions somewhere (e.g. an array) so that you can access it. If I ever need it, I might actually write some code for it and update this post.

Chrome: Resource interpreted as Font but transferred with MIME type font/x-woff

When loading one of my website in Chrome, I noticed the following error message in the JavaScript console:

Resource interpreted as Font but transferred with MIME type font/x-woff: “https://xxx.xxx/xxx.woff”.

Actually it looks like it took too long to define and official MIME type for WOFF fonts and a few different MIME types have been used until the official one was defined:

  • font/x-woff
  • application/x-font-woff
  • application/font-woff – This is actually the official MIME type for WOFF fonts
  • font/woff

By default IIS7 will not know what to do with the WOFF font file, so you will get a 404 error when fetching it.

In my case I was using some third party files which defined the following in order to solve the 404 error:

  <system.webServer>
    <staticContent>
      <remove fileExtension=".woff" />
      <mimeMap fileExtension=".woff" mimeType="font/x-woff" />
    </staticContent>
  </system.webServer>

But this MIME type is now not in use anymore. So I tried the following:

  <system.webServer>
    <staticContent>
      <remove fileExtension=".woff" />
      <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
    </staticContent>
  </system.webServer>

And the error in the console was gone. Actually using application/x-font-woff instead of application/font-woff also works. This is probably because for a very long time, Chrome didn’t support the new MIME type and really expected application/x-font-woff.

If you’re using Apache as a Web Server, you will need to add the AddType directive to your .htaccess file:

AddType application/font-woff .woff

Note that you may get any of the following error messages which basically all mean that the mime type provided is not the expected one and you need to update the configuration of your web server:

resource interpreted as font but transferred with mime type font/x-woff
resource interpreted as font but transferred with mime type application/octet-stream
resource interpreted as font but transferred with mime type application/x-woff
resource interpreted as font but transferred with mime type application/x-font-otf
resource interpreted as font but transferred with mime type font/woff
resource interpreted as font but transferred with mime type font/truetype

If you have a similar problem with other types of files, please refer to the official list of Media Types (formerly called MIME types).

HTML5: Displaying the battery level

Note that this currently only works with Firefox. Support for Chrome and Internet Explorer is not yet available and it’s not yet known when it will be available.

The new Battery Status API allows you from a web page to access information about the battery status of the device rendering it. It is not only useful in order to show the current status but to implement battery status dependent logic e.g. increasing polling interval using Ajax or disabling animations in order to preserve the battery, or auto-saving in case the device goes out of power, prevent the user from performing long running operation which might not be able to finish because of the low remaining battery level.

First we’ll create the HTML and CSS in order to get an empty battery display looking like this:

The HTML code couldn’t be simpler. We just need a battery div:

<div id="battery"></div>

Now we need to display a border around the div and a smaller rectangle after it:

.battery:after {
    background-color: #fff;
    border: 2px solid #000;
    content: "";
    display: block;
    height: 16px;
    position: absolute;
    right: -6px;
    top: 6px;
    width: 6px;
}
.battery {
    background-color: #fff;
    border: 2px solid #000;
    height: 32px;
    margin-left: auto;
    margin-right: auto;
    position: relative;
    width: 100px;
}

Then we need to display a battery level within the battery display:

<div id="battery"><div id="battery-level"></div></div>

And we just need to add some CSS:

.battery .battery-level {
    background-color: #666;
    height: 100%;
}

By setting the width of .battery-level in pixels (or in percent which is the same since the element is 100 pixels wide) to the battery level in percents, we’ll get the right display:

Of course, one would expect our battery level display to show the level in a different color depending whether the battery is almost empty or not. So let’s introduce three CSS classes which will show the level in green, yellow or red:

Using the following CSS code:

.battery .battery-level.high {
    background-color: #66CD00;
}
.battery .battery-level.medium {
    background-color: #FCD116;
}
.battery .battery-level.low {
    background-color: #FF3333;
}

Before we move to the HTML5 part, let’s also display the battery level as text, by setting it as text on the battery-level element and by adding the following css rule:

.battery .battery-level {
    text-align: center;
}

It then looks like this:

10%
75%
95%

Now we’re almost done… All we need is what’s actually the main topic of this post: to get the battery level data using HTML5. For this we need to use the new Battery Status API.

The Battery Status API provides access the battery information through navigator.battery which implement the BatteryManager interface. This interface provides the following information:

  • whether the battery is currently charging
  • the charging time
  • the discharging time
  • the battery level

Additionally, it also provides events you can listen to:

  • onchargingchange
  • onchargingtimechange
  • ondischargingtimechange
  • onlevelchange

We will not use the events for now and just show the battery level when the page was loaded:

The JavaScript code to work with this API is pretty straight forward:

var battery = navigator.battery;
var level    = battery.level * 100;
var batteryLevel = jQuery('.battery .battery-level');
batteryLevel.css('width', level + '%');
batteryLevel.text(level + '%');
if (battery.charging) {
    batteryLevel.addClass('charging');
} else if (level > 50) {  
    batteryLevel.addClass('high');  
} else if (level >= 25 ) {  
    batteryLevel.addClass('medium');  
} else {  
    batteryLevel.addClass('low');  
}

If you want to update the battery level display as the battery charges and discharges:

Here’s the JavaScript code:

function updateBatteryDisplay(battery) {
	var level = battery.level * 100;
	var batteryLevel = jQuery('.battery .battery-level');
	batteryLevel.css('width', level + '%');
	batteryLevel.text(level + '%');
	if (battery.charging) {
	    batteryLevel.addClass('charging');
	    batteryLevel.removeClass('high');  
	    batteryLevel.removeClass('medium');  
	    batteryLevel.removeClass('low');  
	} else if (level > 50) {  
	    batteryLevel.addClass('high');  
	    batteryLevel.removeClass('charging');
	    batteryLevel.removeClass('medium');  
	    batteryLevel.removeClass('low');  
	} else if (level >= 25 ) {  
	    batteryLevel.addClass('medium');  
	    batteryLevel.removeClass('charging');
	    batteryLevel.removeClass('high');  
	    batteryLevel.removeClass('low');  
	} else {  
	    batteryLevel.addClass('low');  
	    batteryLevel.removeClass('charging');
	    batteryLevel.removeClass('high');  
	    batteryLevel.removeClass('medium');  
	}
}

var battery = navigator.battery;
updateBatteryDisplay(battery);
battery.onchargingchange = function () {
    updateBatteryDisplay(battery);
};
battery.onlevelchange = function () {
    updateBatteryDisplay(battery);
};

So the Battery Status API is a very powerful and useful API which is very easy to use. Now let’s hope it will soon be available in all major browsers !

ASP.NET: Slow first loading time

You might have experienced the problem that when you first load a large ASP.NET application (e.g. a CMS), it takes quite some time to load. If you then reload the page or even restart the browser and load the page again, it’s quite fast. There seems to be a few possible cause for this. So this post will not give you an extensive answer as to what all could go wrong but focus on application pool recycling.

What is an Application Pool?

Application Pools are used by IIS to isolate web applications. It allows you to use different settings in different applications. This is especially important when your different applications use different security settings. Applications in different application pools run in different windows processes (w3wp.exe) and thus also provide some kind of segregation by preventing an application from interfering with other applications. So an error in one application won’t cause other applications to crash or behave unexpectedly.

What is Application Pool Recycling?

Application pool recycling basically means that when a given event occurs, the resources related to an application pool will be recovered. It is mainly useful to prevent long running application from crashing or hanging e.g. because of memory leaks. When the recycling happens, a new worker process is started which will receive new web requests and the old one is shut down (once it’s done processing current requests), so there is no downtime while recycling.

Why does recycling cause the first load to last longer ?

Many applications need to first compile scripts or DLLs on the fly. Others need to load a large amount of data and pre-process it. This is basically what’s causing the delay on the first load. Afterwards once everything is compiled and data pre-processed, everything is fast.

Whenever an application pool is recycled and the worker processes are shutdown, next time the application is called, a new worker process needs to be started and these compilation and pre-processing activities need to be performed again.

When does recycling happen?

There are basically two different ways to recycle application pools:

  1. Recycling based on configuration
  2. On-demand recycling

On-demand recycling can be done:

  • in the IIS manager
  • from the command line using appcmd
  • using Windows Management Instrumentation (WMI) i.e. the ApplicationPool.Recycle method

Automatic application pool recycling can be configured to recycle:

  • when reaching a memory threshold (virtual memory or used memory)
  • when reaching a certain number of requests
  • at a scheduled time
  • after a scheduled time

Additionally, recycling will happen, when the configuration of an application is changed or when an unhealthy ISAPI condition is reported.

How to configure when automatic application pool recycling is done?

This can be configured in the Application Pools configuration panel of the IIS manager (Go to Start -> Administrative Tools -> Internet Information Services (IIS) Manager):

Application pool configuration

Select an application pool on the left-hand side and click on Recycling on the right.

The default configuration is to recycle an application pool after 29 hours (1740 minutes):

Application Pool Recycling Settings

If there are long periods of time during which your site/application has few hits, it might be a good idea to increase this default value. Actually, except if you know that you have a memory leak somewhere and do not manage to fix it, there is no big benefit in recycling your application pools at fixed intervals. If your application is running on a server where other applications are running, you may want to used the memory based maximums. Otherwise just removing the time interval based configuration may be a good solution. If nothing else it configured, you application pool will be recycled anyway once all available memory is used.

Idle Time-out

Also note that even though strictly speaking, it’s not an automatic application pool recycling, you can configure the application pool so that worker processes are shutdown after a specified amount on time being idle i.e. not receiving new requests or processing existing requests. The default value is 20 minutes. Actually I guess in most cases it makes no sense. It’s only useful if you have so limited resources that you need to get rid of unused application pools as fast as possible. So in most cases, I’d recommend setting the idle time-out to zero:

Application pool idle time-out

How do I know when recycling has occurred?

There are two places where you can configure under which conditions an event log entry is generated when an application pool is recycled.

The first one is when you press “Next” in the dialog shown above. You will then see the following:

Recycling application pool recycling events to log

The checkbox under “Configurable recycling events” are disable in this screenshot because I haven’t configured any  trigger for an automatic application pool recycling. But if you defined e.g. a number of requests, some checkboxes will be enabled.

Another place where you can set it is the Advanced Settings dialog. Just select your application pool and press “Advanced Settings”. The following dialog will be displayed:

Application pool advanced settings

The recycling settings are the bottom and contain a section called “Generate Recycle Event Log Entry”. You can then set the appropriate entries to true to get the required event log entries.

Also remember that starting from Windows 2008, you can have an email sent when an event is triggered.

Orchard CMS: NullReferenceException when adding roles

When clicking on “Add a role” in the Users administration, I got the following exception:

System.NullReferenceException: Object reference not set to an instance of an object.
at Orchard.Roles.Services.RoleService.GetInstalledPermissions()
at Orchard.Roles.Controllers.AdminController.Create()
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass13.<InvokeActionMethodWithFilters>b__10()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass13.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass13.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)

I found a reported issue which did look similar. It was reported against Orchard CMS 1.7 and was marked as resolved. I am using Orchard CMS 1.7.2. Unfortunately, the issue details neither show in which version it was solved nor what the actual root cause was. Since it was closed by Sébastian who’s an Orchard Core developer and was actually born in the same city as I was, I could have contacted him but in-between I found out what the problem was.

Actually my problem was caused by a module I am working on. When disabling the module, it worked fine and when reactivating it, it is broken again.

The problem was in the Permissions.cs file. There were basically two problems. Basically what Orchard does when you click on “Add a role” is to get all features and their permissions. The two problem I had were:

  1. The GetPermissions() method did not returned all permissions I had defined and was returning in GetDefaultStereotypes()
  2. ReSharper had suggested me to make the setter for the Feature property private since it was not accessed anywhere.

But fixing the first one alone didn’t solve anything. I guess it was necessary to fix it but the root cause of the problem was the private setter for the Feature property. Once I made it public again it worked fine:

public Feature Feature { get; set; }

So the lesson here is that especially when working with such a system as Orchard CMS you should not blindly implement changes in the visibility of properties or methods suggested by ReSharper/Visual Studio. Since properties and methods are rarely directly referenced, your tools will very often miss some dependencies.

 

 

 

Active Directory Authentication and Authorization in Orchard CMS

Since Orchard CMS doesn’t (yet) support authentication and authorization of domain users against an Active Directory, you have to install a module to achieve this. There are handful of modules which could help. I decided to use ActiveDirectoryAuthorization by Moov2 because it was the only one which had a decent number of downloads, reviews and a project site.

If you decide to use this module, you’ll first notice that there isn’t any complete documentation how to adapt your system so that the authentication and authorization works over an Active Directory. But there is a blog article which gives some instructions. Unfortunately, the instructions seem not to be complete.

Basically when it comes to the changes to be made in your web.config, the blog post says you should “simply replace the current Forms authentication settings with the authentication settings shown below”:

    <authentication mode="Windows" />
    <roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider"/>

Unfortunately, only with this change, whenever I entered my credentials, I used to get the same dialog over and over. What’s missing here, is that you also need to add an authorization tag, thus replacing:

    <authentication mode="Forms">
      <forms loginUrl="~/Users/Account/AccessDenied" timeout="2880" />
    </authentication>

by:

    <authentication mode="Windows"/> 
    <roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider"/> 
    <authorization>
	    <allow roles="aw001\Domain Users"/>
	    <deny users="?"/>
    </authorization>

Of course, you have to replace aw001 by your domain name.

The question mark in the deny tag basically means that anonymous users will be denied access and the allow tag that all Domain Users of this particular domain will be granted access.

After that, Orchard just gave me a white page. So at least something was activated… In the logs, I found the following exception:

2014-09-25 11:36:01,653 [6] Orchard.Environment.DefaultBuildManager – Error when compiling assembly under ~/Modules/ActiveDirectoryAuthorization/ActiveDirectoryAuthorization.csproj.
System.Web.HttpCompileException (0x80004005): c:\inetpub\wwwroot\orchard\Modules\ActiveDirectoryAuthorization\Core\Authorizer.cs(144): error CS1061: ‘Orchard.ContentManagement.IContentManager’ does not contain a definition for ‘Flush’ and no extension method ‘Flush’ accepting a first argument of type ‘Orchard.ContentManagement.IContentManager’ could be found (are you missing a using directive or an assembly reference?)
at System.Web.Compilation.AssemblyBuilder.Compile()
at System.Web.Compilation.BuildProvidersCompiler.PerformBuild()
at System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath)
at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
at System.Web.Compilation.BuildManager.GetVPathBuildResult(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean ensureIsUpToDate)
at System.Web.Compilation.BuildManager.GetCompiledAssembly(String virtualPath)
at Orchard.Environment.DefaultBuildManager.GetCompiledAssembly(String virtualPath) in Orchard\Environment\IBuildManager.cs:line 53

I could see the line of code where this was done but still wasn’t sure what I had to do. So I googled for it. There was exactly one hit. Somehow, it looks like someone had the same problem with a completely unrelated module. This problem was solved in this module and I checked what was the code change. It turns out they only removed the call to ContentManager.Flush(). So I gave it a try, editing ActiveDirectoryAuthorization\Core\Authorizer.cs and commenting out the following line in the CreateUser method:

_contentManager.Flush();

After that I could log in.

The other problem I had was that my domain user didn’t have the permissions I thought I had assigned. The problem is that I created a role with the same name as a group of this user in Active Directory but didn’t add the domain name to it i.e. I called my role myusergroup instead of aw001\myusergroup. After correcting it, it worked fine.

When logging in with a domain user, an Orchard User is created. You do not see in the Orchard administration that this user has the role you’ve created (which is called the same as an Active Directory group) but when considering the roles of the user for checking the permissions, now Orchard will use both the roles assigned in Orchard and the groups assigned to the user in the Active Directory. Great !

 

Orchard CMS: Package uploading and installation failed

You may get an error message like this when installing a new theme or module in Orchard CMS:

Package uploading and installation failed

There are a few things you need to check to find out what the problem is, make sure that:

  • your ApplicationPool is using the .NET Framework Version 4.0 and an Integrated Managed Pipeline Mode.
  • the ApplicationPool Identity is set to ApplicationPoolIdentity
  • the user your web server process is running under has write access to the Modules, Themes and App_Data directories.

For the last point, you can find out the user by opening the task manager, showing processes for all users and checking the User Name for IIS Worker Process (e.g. w3wp.exe). Then give this user write access to the three folders mentioned above.

First and last matching child in CSS and with jQuery

I recently noticed a few problems in some code I had written a few months ago:

  1. I am displaying a grid containing an empty first column and an empty last column and want to remove them. This only happened for the first row and not for the others
  2. I display a left border on all columns and additionally a right border on the last column. This also didn’t work anymore, the right border was missing.

These two problems were due to using the selector (once in CSS and once with jQuery) which do not do what I would expect.

First let’s assume we have a table-like div structure:

<div class="table">
    <div class="tr">
        <div class="th"></div>
        ...
        <div class="th"></div>
    </div>
    <div class="tr">
        <div class="td"></div>
        ...
        <div class="td"></div>
    </div>
    ...
    <div class="tr">
        <div class="td"></div>
        ...
        <div class="td"></div>
    </div>
</div>

In CSS, I can set the style of the first cell and of the last cell of each row like this:

div.tr div:first-child { }

div.tr div:last-child { }

To select them with jQuery:

jQuery("div.tr div:first-child")

jQuery("div.tr div:last-child")

Easy, right ? So where’s the problem ?

Well the problem is that is that it only worked by chance and as soon as I extended the generated html code, it broke. I needed to add some additional divs at the end of every line in the grid but have them be invisible. So basically, since the new divs where invisbile, the current last div would still have to be styled in a special way although it wasn’t the last div child anymore. So I just modified my CSS and jQuery selectors like this:

div.tr div.td:last-child { }
jQuery("div.tr div.d:last-child")

And the same for th as well. But it doesn’t work. What happens is that div.tr div.td:last-child doesn’t mean select the last child of div.tr being a div.td. It means select the last child of div.tr if it is a div.td. So since the last child of div.tr was not a div.td anymore, it failed.

So what I needed was a selector like :last-child-of-type. Well actually there is a selector :last-of-type. Unfortunately, it also failed using it since this selector doesn’t work with classes i.e. you can use div:last-of-type as selector but not div.class:last-of-type. So :last-of-type is useful to select the second div in this case:

<article>
    <p></p>
    <div></div>
    <div></div>
    <div></div>
    <p></p>
</article>

But not in our case. So what can be done ? Well, the way I went for (which just involved replacing an append by a prepend) was to move the hidden divs to the beginning of the row. So now I could use :last-child again. And since I was selecting the first line only with jQuery, I used the following:

$(".tr.cell").each(function() {
    $(this).children(".td").first().remove();
    $(this).children(".td").last().remove();
});

So it’d be great if :last-of-type could support classes or if there was a :last-of-class. But until there is, you can work around it with jQuery using a loop. In CSS, unfortunately, there seems to be no way to do it. The only way to select this last element of a type using CSS selectors is to assign it a class with javascript or while generating the HTML code and then selecting this class using CSS.

Generating new certificate in XAMPP for Windows

Since I had an older version of XAMPP for Windows installed, it was still using openssl 1.0.1e in which the heartbleed vulnerability was not yet fixed. So I installed the latest version and since the certificate in there was from 2013 I was not really sure whether it was safe or not so I decided to generate a new one. Here’s a short description how to do it.

Open a DOS prompt and navigate to the apache\bin directory in your XAMPP for Windows installation:

cd /D D:\Software\xampp\apache\bin

We’ll first define a couple of environment variables so that we do not need to provide them every time as parameter to openssl:

set OPENSSL_CONF=D:\Software\xampp\apache\conf\openssl.cnf
set RANDFILE=C:\Temp\.rnd

Now we’re ready to start. Generating a certificate involves 3 steps:

  1. Generating an RSA private key
  2. Generating a certificate sign request
  3. Generating a certificate

Note that since we are generating a self sign certificate, we can combine these 3 steps into 1 as described here.

Once the certificate is generated you can install it as shown here.

Generating an RSA private key

You can generate the key by executing the following:

D:\Software\xampp\apache\bin>openssl genrsa -out server.key 1024
Loading 'screen' into random state - done
Generating RSA private key, 1024 bit long modulus
............++++++
...........++++++
e is 65537 (0x10001)

This will create a file called server.key with a content similar to:

—–BEGIN RSA PRIVATE KEY—–
MIICXwIBAAKBgQDkQxjDD36nH9lfch9m+CS3TzIHYqrkEd0XGg+ki4E0QyP+Me9W
mJvPfEh8Gn9Iw18o4je9UN8gVWszm6GqBT0z3ryC10ZwQvi+hB+fRWNX3dC+cam8
EwA+NE3tVRGCHcjo73IFMixIsKfJ/1Rdj8lV0IX5PBform1hI6ao8jXH4QIDAQAB
AoGBAImgEtv5CaoGP++WRWy2DJ0heM6PJO4h/yWgpvHU0vAJ0ze+L8oMdVUiYCnD
aB8c/NEPo//XNNCv79TL7ystwXnTLlLR05n90Ta3SBFex1Pp48Rn7vLReZmiTrMc
6P7hqlKYCny+5zcx9gNzYJ73OsRoJGy0wdRRy6lRB87iiRDhAkEA9wz9Vc9vpDie
xsMVMfeEC7hOzUCHd3bX0Ye8BYBTVslQAZmrBQZv3Z59W+MSM3aJT6vPYtsMwIWH
zdvI7z/4nQJBAOyH3yuROrzrqFIe5YlyKLxeLx28T0IdYS1zwt064zfgMyi3eWG+
CAibg81cAMqlDhMzden8/CTYZYEQIhD6/xUCQQCA0tcvbdGrcpLo1kUxHv5OFjeR
M/rvwprbecoDnFzYvnTnwLe7ERY4HDMGPSv6he8oClFEHTFTGs4r/FWU3GjJAkEA
oYpeQawLOLGdoJBXZdqgtZ2BgkZ0vwu/rcIs6NjqC+RELF+6N6YIaJCFoMBgDgZS
KYzw0CCmuCdOk6nICl7RzQJBANeQEfc+FT3r3mdVLnyXraAjPxo+RFDZvWqQJiJY
MJUFZ9SPiaiNzVZhMijmAR3klnOz1XZlRhC/z9fzDJVopGk=
—–END RSA PRIVATE KEY—–

Note you can find instructions saying to use the -des3 option. Do not this will cause your key to contain a pass phrase:

D:\Software\xampp\apache\bin>openssl genrsa -des3 -out server.key 1024
Loading 'screen' into random state - done
Generating RSA private key, 1024 bit long modulus
......++++++
.........................++++++
e is 65537 (0x10001)
Enter pass phrase for server.key:
Verifying - Enter pass phrase for server.key:

Which will lead to such an error loading the key from XAMPP:

[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] AH02577: Init: SSLPassPhraseDialog builtin is not supported on Win32 (key file D:/Software/xampp/apache/conf/ssl.key/server.key)
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] AH02311: Fatal error initialising mod_ssl, exiting. See D:/Software/xampp/apache/logs/error.log for more information
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] AH02564: Failed to configure encrypted (?) private key localhost:8443:0, check D:/Software/xampp/apache/conf/ssl.key/server.key
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] SSL Library Error: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] SSL Library Error: error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] SSL Library Error: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] SSL Library Error: error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error (Type=RSA)
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] SSL Library Error: error:04093004:rsa routines:OLD_RSA_PRIV_DECODE:RSA lib
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] SSL Library Error: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] SSL Library Error: error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error (Type=PKCS8_PRIV_KEY_INFO)
AH00016: Configuration Failed

Generating a certificate sign request

You can then use the key to generate a certificate sign request using the following command:

D:\Software\xampp\apache\bin>openssl req -nodes -new -key server.key -out server.csr
Loading 'screen' into random state - done
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:.
State or Province Name (full name) [Some-State]:.
Locality Name (eg, city) []:.
Organization Name (eg, company) [Internet Widgits Pty Ltd]:localhost
Organizational Unit Name (eg, section) []:.
Common Name (e.g. server FQDN or YOUR name) []:localhost
Email Address []:.

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:mypassword
An optional company name []:.

You should of course use the appropriate data instead of localhost and dot (which means empty field). Also choose a different challenge password than mypassword.

This will create a file called server.csr containing something like:

—–BEGIN CERTIFICATE REQUEST—–
MIIBgjCB7AIBADAoMRIwEAYDVQQKDAlsb2NhbGhvc3QxEjAQBgNVBAMMCWxvY2Fs
aG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA5EMYww9+px/ZX3IfZvgk
t08yB2Kq5BHdFxoPpIuBNEMj/jHvVpibz3xIfBp/SMNfKOI3vVDfIFVrM5uhqgU9
M968gtdGcEL4voQfn0VjV93QvnGpvBMAPjRN7VURgh3I6O9yBTIsSLCnyf9UXY/J
VdCF+TwX6K5tYSOmqPI1x+ECAwEAAaAbMBkGCSqGSIb3DQEJBzEMDApteXBhc3N3
b3JkMA0GCSqGSIb3DQEBBQUAA4GBAKdmonasFGzPFiY8pgQThwIUvHo7her3SiPL
VkZqGbLT4NjoB2Yp7zi2qZ59qGLFHNFsfeBfnJZMFP2pGBbO1dW/2H1R0ogX95Ci
jIhwZFZD6xwpPkIWpau2dS1i5Q7kyBeGp/krfNHr/kSAUvaavq1R581yL2b5/ClY
9ARH/He/
—–END CERTIFICATE REQUEST—–

You probably do not need the -nodes option since it only applies when using openssl to generate a key using the req command. But I’d rather use it here although I do not need it than forget it when generating both the key and the certificate in a single step using the req command.

Generating a certificate

Now we need to generate the certificate using the following:

D:\Software\xampp\apache\bin>openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
Loading 'screen' into random state - done
Signature ok
subject=/O=localhost/CN=localhost
Getting Private key

If you get such an error:

unable to write 'random state'

it means you forgot to set the second environment variables as shown in the beginning of this post.

Generating a self-signed certificate in one step

When generating a self-signed certificate you can combine this all to one step using only the req command:

D:\Software\xampp\apache\bin>openssl req -nodes -new -x509 -keyout server.key -out server.crt
Loading 'screen' into random state - done
Generating a 1024 bit RSA private key
............++++++
............++++++
writing new private key to 'server.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:.
State or Province Name (full name) [Some-State]:.
Locality Name (eg, city) []:.
Organization Name (eg, company) [Internet Widgits Pty Ltd]:localhost
Organizational Unit Name (eg, section) []:.
Common Name (e.g. server FQDN or YOUR name) []:localhost
Email Address []:.

You should of course use the appropriate data instead of localhost and dot (which means empty field).

Installing the certificate

Now we just need to copy the key and the certificate to the apache installation:

D:\Software\xampp\apache\bin>copy /Y server.crt d:\Software\xampp\apache\conf\ssl.crt
        1 file(s) copied.

D:\Software\xampp\apache\bin>copy /Y server.key d:\Software\xampp\apache\conf\ssl.key
        1 file(s) copied.

After a restart of the Apache web server, your new certificate will be available.

FireBug: syntax error

I’ve moved my blog to a new WordPress theme over the weekend. Everything seems to work fine except that I get the following error message in FireBug:

syntax error doctype html

Obviously <!DOCTYPE html> is fine there. Then I noticed the file name associated with this error: ?v=1.11.0

After searching in the source code of the page for this I found the following:

script("http://benohead.com/?v=1.11.0").wait()

So it’s trying to load some JavaScript file but the name got lost and it ended up loading the main page. And HTML code doesn’t really parse well when you expect JavaScript. Thus the error with the DOCTYPE…

Since I was using the WordPress plugin “WP deferred javaScript” I immediately thought it might have something to do with it and disabled it. And the problem was gone…

If you have the same problem it might not be caused by the same plugin but the cause is most probably that some HTML code is loaded in a <script> tag. Always first check the JavaScript file name shown by FireBug it will directly lead you to the script tag in question.

Note that this error doesn’t only occur when you directly reference an HTML page instead of a JavaScript file. It can also occur when you have an empty src attribute like:

<script type="text/javascript" src=""></script>

Or if you point to a JavaScript file which doesn’t exist or an empty JavaScript file.