Monday, January 30, 2012

ASP.NET url changes with 301 permanent redirect

I deployed a new ASP.NET MVC web site and needed to indicate to google and links from other sites that the url for most pages had permanently changed (rather than give them a 404 error).

Adding simple dummy .aspx files for these old pages with the following (non-code behind) script with a 301 HTTP response did the trick with little fuss:


<%@ Page Language="C#" AutoEventWireup="false" Inherits="System.Web.UI.Page" %>
<script runat="server">
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        // Tell old links to go to the new url:
        Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","http://www.mydomain.com/mynewurl");
    }
</script>

At some point I'll simply delete them once I think the important external links have been updated.

Friday, January 27, 2012

Install Elmah logging with ASP.NET MVC 3

Elmah is a great logging tool for ASP.NET and works fine with ASP.NAT MVC 3 with these quick steps:

1. Ensure NuGet is installed in Visual Studio 2010 (shows as Library Package Manager under Tools menu)

2. Open the Package Manager console and install Elmah by typing:
PM> Install-Package Elmah.MVC
This updates the web.config with sectionGroup, httpModules and httpHandlers and adds dll references.

3. Add to web.config:
  <elmah>
    <security allowRemoteAccess="no" />
    <errorLog type="Elmah.XmlFileErrorLog, Elmah" logPath="~/App_Data/Elmah" />
  </elmah>

4. To enable error logging when customErrors is "on" add the following to Global.asax: [see: http://stackoverflow.com/questions/766610/how-to-get-elmah-to-work-with-asp-net-mvc-handleerror-attribute/5936867#5936867]

public class ElmahHandledErrorLoggerFilter : IExceptionFilter
{
    public void OnException (ExceptionContext context)
    {
        // Log only handled exceptions, because all other will be caught by ELMAH anyway.
        if (context.ExceptionHandled)
            Elmah.ErrorSignal.FromCurrentContext().Raise(context.Exception);
    }
}


And:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new ElmahHandledErrorLoggerFilter());  // Required so that Elmah still loggs errors when customErrors mode="On"
            filters.Add(new HandleErrorAttribute());
        }

Done.

Sunday, November 20, 2011

Grouping with linq in C#

Nice clear post on grouping with linq in C# (and VB.NET too) by Christian Nagel:
http://weblogs.thinktecture.com/cnagel/2010/10/linq-grouping-with-c-and-visual-basic.html

Lambda syntax: 



var q = Formula1.GetChampions()
.GroupBy(r => r.Country)
.Select(g => new
{
Count = g.Count(),
Group = g
})
.OrderByDescending(x => x.Count)
.ThenBy(x => x.Group.Key)
.Select(x => new
{
Country = x.Group.Key,
Count = x.Count,
Racers = x.Group.Select(r => r.FirstName + " " + r.LastName)
})
.Take(5);


Similarly in comprehension syntax: 

var q = (from r in Formula1.GetChampions()
                     group r by r.Country into g
                     let count = g.Count()
                     orderby count descending, g.Key
                     select new
                     {
                         Country = g.Key,
                         Count = count,
                         Racers = from r1 in g
                                  select r1.FirstName + " " + r1.LastName
                     }).Take(5);



Wednesday, September 28, 2011

Python 2.7 Setup Steps

UPDATE 2013:
Now follow these instructions: https://python-guide.readthedocs.org/en/latest/starting/install/win.html
Use distribute, not setuptools as described here
/UPDATE

I've set up Python 2.7 on several wind0ze machines recently, these are the "best practice" steps I now use:

  • Download and install Python 2.7 to C:\Python27
  • Download and install setuptools to C:\Python27\Lib\site-packages\
    (setuptools includes easy_install, so we can install pip! Read instructions for 32 vs 64bit versions)
  • Add env variable PYTHON_HOME=C:\Python27
  • Append env variable PATH with ;%PYTHON_HOME%;%PYTHON_HOME%\Scripts;
  • Run C:\Python27\Scripts>easy_install-2.7 pip to install pip
  • Install virtualenv: easy_install-2.7 virtualenv (now all pip install commands I run from a new virtualenv)
That takes care of the base environment.

Next is to install packages as required, remembering that matplotlib is best installed using an installer after executing "pip install numpy".

References:
pip Installation instructions (recommends installing pip using virtualenv)
Public service announcement (tool transition infographic)
How to install pip on Windows (installing pip globally using setuptools)
Installing matplotlib

Wednesday, September 14, 2011

python to solve linear system

Solving good ol' Ax=b:

>>> import numpy as np
>>> A = np.matrix('[3 -1 1; -1 1 -1; 1 -1 3]')
>>> A
matrix([[ 3, -1,  1],
        [-1,  1, -1],
        [ 1, -1,  3]])
>>> b = np.matrix('[1;1;1]')
>>> from scipy import linalg
>>> x = linalg.solve(A,b)
>>> x
array([[ 1.],
       [ 3.],
       [ 1.]])

See docs:
numpy.linalg.solve
routines.linalg
numpy solve examples (prob better than above!)

Tuesday, September 6, 2011

python to visualise vectors

I've been working on a simple example SVM problem and wanted to be able to visualise the vectors in 3D. Python with Matplotlib works nicely.

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt


fig = plt.figure()
ax = Axes3D(fig)


ax.plot3D([0,-1], [0,1], [0,1], zdir='z', label='x1 +1')
ax.plot3D([0,0], [0,1], [0,0], zdir='z', label='x2 -1')
ax.plot3D([0,1], [0,1], [0,1], zdir='z', label='x3 +1')
ax.plot3D([0,0], [0,0], [0,0], zdir='z', label='x4 +1')


ax.scatter([0,-1], [0,1], [0,1], zdir='z', label='x1')
ax.scatter([0,0], [0,1], [0,0], zdir='z', label='x2')
ax.scatter([0,1], [0,1], [0,1], zdir='z', label='x3')
ax.scatter([0,0], [0,0], [0,0], zdir='z', label='x4')


ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')


ax.legend()
plt.show()



To add an equation to the graph:

import numpy as np
x = np.linspace(-1, 1, 50)
y = 2*x**2
ax.plot3D(x, y, 0);

Sunday, August 21, 2011

LibSVM v3.1 python example

LibSVM v3.1 python example: (many older examples break in v3.1)


from svmutil import *
svm_model.predict = lambda self, x: svm_predict([0], [x], self)[0][0]
prob = svm_problem([1,-1], [[1,0,1], [-1,0,-1]])
param = svm_parameter()
param.kernel_type = LINEAR
param.C = 10
m=svm_train(prob, param)
m.predict([1,1,1])

From: http://stackoverflow.com/questions/4214868/an-example-using-libsvm-in-python/4215056