Category Archives: Software Development

This category contains all my posts about software development. Tutorials, solutions to problems I’ve met, interesting things I’ve stumbled over, code samples, stuff I don’t want to forget, et cetera.

Missing time zones in WAMP MySQL

If you try to run for example SET time_zone = 'Europe/Oslo' on the default MySQL database that comes with WAMP you might get an error saying the time zone doesn’t exist.

Apparently this is because the time_zone tables for some reason are empty.

How to fix

  1. Go to dev.mysql.com/downloads/timezones.html
  2. Download the POSIX standard Time zone description tables, version 2011n zip archive
  3. Extract the files and overwrite the ones in C:\wamp\bin\mysql\mysql5.6.17\data\mysql, or whatever your equivalent path would be
  4. Restart MySQL

Setting the time zone should now work :)

Simple PHP proxy for cross origin HEAD requests

Have some Javascript that runs through all the URLs on a site of mine to prep caching and check for dead links and other problems. Problem is that the site also includes embedded video files hosted by someone else. These fails of course because of cross origin restrictions and since I’m not in control of their servers I needed a workaround.

I wrote this small PHP script to work as a proxy and as far as I can see it works pretty great. Short and easy to follow as well, so that’s always fun :)

So basically the script just pipes through whatever headers it gets to the the target URL an pipes back whatever headers it gets in the response. Seems to work, but let me know of weaknesses and easy improvements if you see any :)

<?php

$request_headers = getallheaders();
unset($request_headers['Cookie']);
unset($request_headers['Host']);

foreach($request_headers as $key => &$value)
    $value = $key.': '.$value;

$url = $_SERVER['QUERY_STRING'];
$limit = 20;

$curl = curl_init();
do
{
    curl_setopt_array($curl, array
    (
        CURLOPT_URL => $url,
        CURLOPT_HTTPHEADER => $request_headers,
       
        CURLOPT_RETURNTRANSFER => TRUE,
        CURLOPT_HEADER => TRUE,
        CURLOPT_NOBODY => TRUE,

        CURLOPT_FOLLOWLOCATION => TRUE,
        CURLOPT_MAXREDIRS => $limit--,
    ));

    ob_start();
    $headers = trim(curl_exec($curl));
    $url = curl_getinfo($curl, CURLINFO_REDIRECT_URL);
    ob_end_clean();
}
while($url and $limit > 0);

curl_close($curl);

$headers = trim(substr($headers, strrpos($headers, "\r\n\r\n")));
header_remove();
foreach(explode("\r\n", $headers) as $h)
    header($h);

Notes

  • The Cookie and Host headers sent from the browser are removed so they don’t mess up the request.
  • CURL wasn’t acting properly where I deployed this. It didn’t follow redirects, and curl_exec output content to the browser even with return transfer set to true. So it has a manual workaround for following the redirects and uses output buffering to make sure nothing goes to the browser before we want to.

ASP.NET MVC Areas in separate projects/assemblies

Had to implement a webshop section for an ASP.NET MVC website project which was to be reused by another one. Solving it was a bit finicky, so documenting it roughly here in case I need to do it again in the future. Not sure I remember all the steps, but hopefully it’ll be enough to reproduce the effect:P

The main problem here is the way razor views are compiled run-time and that is solved by using the Razor Generator VS extension to pre-compile the views and the belonging RazorGenerator.Mvc Nuget package to enable the web application to find them during run-time.

Don’t know if the solution I ended up with is the best, but it worked fairly great. If you have better/cleaner solutions please leave a comment :)

Continue reading

Use the ASP.NET MVC layout for all Areas

Areas in an ASP.NET MVC web application doesn’t use the layout of your web application by default. The reason (as far as I understand) is that your _ViewStart.cshtml which is usually located in ~/Views/ is only visible by views in that folder and its sub-folders.

So the solution, turns out, was more or less just to move that file up a level.

  1. Move ~/Views/_ViewStart.cshtml to ~/_ViewStart.cshtml.
  2. Cut or copy the following elements from ~/Views/Web.config and merge them into ~/Web.config. I say merge, because configSections for example probably already exists, so put the sectionGroup inside it. Don’t know if the Web.config handles multiple configSections…
      <configSections>
        <sectionGroup name="system.web.webPages.razor" ...>
          ...
        </sectionGroup>
      </configSections>

      <system.web.webPages.razor>
        ...
      </system.web.webPages.razor>

All areas should now use the the same layout as the rest of your application.

Output embedded resources into Razor views

In relation to my ASP.NET MVC Areas in separate projects thing I needed to share some tiny bits of javascript and css between pages in this separate project. Could probably be solved better by looking into the bundling stuff, but as a quick fix I decided to just compile the javascript and css files into the assembly and output them raw into my views. Quick and simple.

  1. Set the Build Action of your js and css file to Embedded Resource
  2. Add this extension method to a static class.
    public static IHtmlString RawResource(this HtmlHelper html, Type type, string resourceName)
    {
        using (var s = type.Assembly.GetManifestResourceStream(resourceName) ?? new MemoryStream())
        using (var r = new StreamReader(s))
        {
            s.Position = 0;
            return new HtmlString(r.ReadToEnd());
        }
    }
  3. Make sure the extension method is available in your view
    @using The.Namespace.Of.My.Static.Class
  4. Use the method in your view
    <script type="text/javascript">
        @Html.RawResource(typeof(AnyClassInAssembyOfEmbeddedResource), "Default.Namespace.Of.Project.Resources.file.js");
    </script>

    <style type="text/css">
        @Html.RawResource(typeof(AnyClassInAssembyOfEmbeddedResource), "Default.Namespace.Of.Project.Resources.file.min.css")
    </style>

Easy peasy. And slightly hackish and ugly… let me know if you have smoother, cleaner bundling approach ;)

If you’re having problems figuring out the right name of your embedded resource, see my post on how to use embedded resources for how to list them all out.

Helpful Sublime Text 2 packages

Keep forgetting the names of packages I like to install when setting up Sublime Text 2. Or that I should install them to begin with. So here’s a note to self on packages I should install whenever I reinstall this fantastic editor. And a note to you if you use the editor and didn’t know such helpful packages existed.

  • Package Control, the package that adds a package manager to the editor. After that is installed, simply press Ctrl+Shift+p, bring up Install Package by typing “ip”, and hit enter. You can then search for packages and install them super easy.
  • Highlight, for copying syntax highlighted code either as HTML or as RTF. Nice for pasting code into emails, documents, etc.
  • Indent XML, for… indenting XML. Been very helpful for cleaning up messy SOAP requests from logs, etc.
  • LESS, for syntax highlighting of LESS files
  • Markdown Preview, for quick preview of markdown files in the browser
  • Text Pastry, for fun pasting madness. You can for example paste in sequences of numbers.

Use WinMerge for comparing archives with TortoiseSVN

I really like the Diff Viewer that comes with TortoiseSVN, but from what I can gather it doesn’t seem to support anything but text files, which is fair enough, but I need to compare archives as well. Zip and Jar files in particular.

WinMerge supports that, and can be integrated with TortoiseSVN very easily right through its installer. But I prefer the diff viewer that comes with TortoiseSVN and the archive diff isn’t recursive by default, so I decided to set it up manually.

  1. Install WinMerge
    (without the automagic TortoiseSVN integration)

  2. Install the WinMerge 7-zip plugin for archive support
    (I couldn’t get the shared install to work, so had to use the application specific one)
    7zmergeinstall

  3. Open TortoiseSVN Settings, Diff Viewer, Advanced
  4. Add rows with extension set to .zip, .jar and whatever archives you want WinMerge to handle and set external program to the following:
    C:\Program Files (x86)\WinMerge\WinMergeU.exe /r /x /e /u /dl %bname /dr %yname %base %mine

If I now for example ask TortoiseSVN for a Diff with previous version of a jar file, I get WinMerge with a recursive comparison of the archive contents. I also recommend that you deselect Show Identical Items under View.