Friday, 13 January 2012

Interfaces on Anonymous function revisted in C#

Last year I wrote a blog about adding interfaces to anonymous functions in Python. Since then I have being programming in .Net (C# and VB.Net) and was curious to see how easy it would be to achieve something similar in C#. I'm not using any IoC frameworks in C# so I wrote a very stupid one just for testing.

C# differs in a few key areas. You can't modify an object’s properties at runtime in C# without doing some Assembly hacking and even if you could, you can't add interfaces to anonymous or lamdba functions. So adding an interface and then adapting a runtime object based on its interfaces isn’t possible, so I ended up having to pass both interfaces around at all points (not ideal). The other major difference is that C# requires strict typing of the anonymous function so you can see 2 explicit casts in the code.

This isn’t the correct way of achieving this in C# but I found the contrast of coding something Pythonic in a different language interesting.





public interface IConcreteInterface { }
public interface ILambdaExpression { }

public class AdapterManager
{
protected readonly List<Adapter> services = new List<Adapter>();

public void registerAdapter<T, U>(object val)
{
var adapter = new Adapter() {
adapts = typeof(U),
implements = typeof(T),
val = val
};
services.Add(adapter);
}

public object resolve<T, U>()
{
return (from x in services where x.adapts == typeof(U) && x.implements == typeof(T) select x.val).Single();
}
}

var gsm = new AdapterManager();
gsm.registerAdapter<IConcreteInterface, ILambdaExpression1>((Func<string>)(() => "Hello World"));

var adapted = gsm.resolve<IConcreteInterface, ILambdaExpression1>();
var lambdaExp = (Func<string>)result
var result = lambdaExp();

Monday, 26 September 2011

IIS .net 4 Application Pool and being unable to login using IE.

I recently installed .net 4 on an IIS 7.5 box and after registering it found that IE wouldn't login to any v4 sites using Windows (Integrated) Authentication. It would prompt for a password until eventually returning a 401.1. Firefox worked and so did IE from the IIS box itself.

The solution was to move the "NTLM" Authentication Provider to the top of the provider list (above "Negotiate"). Goto your site->Authentication, in actions click "Providers..." and move NTLM to the top.

Anyone know why?

Monday, 18 July 2011

Dynamic CAML Query

I had a need to create a CAML query based on a dynamic set of user options. Basically a search routine with parameters such as start date, end date etc. I created this nice recursive method to add n query conditions to the Where part of a CAML query. It's restricted to a single comparison operator at the moment because that's all I needed.

Protected Function ComposeCamlQuery(ByVal conditions As IList(Of String), ByVal op As String, ByVal query As String) As String
Return If(conditions.Count = 1, _
String.Format(query, conditions(0)), _
ComposeCamlQuery(conditions.Skip(1).ToList(), op, String.Format(query, String.Format("<{0}>{1}{{0}}", op, conditions(0)))))

End Function


You can use it like so:
Dim conditions As New List(Of String)

conditions .Add(<Geq>
<FieldRef Name='Created'/>
<Value IncludeTimeValue='FALSE' Type='DateTime'><%= Format(startDate, "yyyy-MM-ddTHH:mm:ssZ") %></Value>
</Geq>.ToString())

Dim whereQuery As String = ComposeCamlQuery(conditions, "And", "<where>{0}</where>")

camlQuery.ViewXml = <view>
<query>
<%= XElement.Parse(whereQuery)) %>
</query>
<rowlimit>2000</rowlimit>
</view>.ToString()

Thursday, 30 June 2011

WPF Binding to a Dictionary

Found this useful tip recently. You can bind a WPF control to any indexed property, including dictionaries.

DataMemberBinding="{Binding MyDict[MyKey]}"

This caught me out because the syntax is very C# and I use VB.Net.

You can also do this programmatically.

DataMemberBinding = New Binding("MyDict[MyKey]")

Tuesday, 7 June 2011

ASP from a Python/Zope perspective.

I have recently changed jobs (hence the lack of posts recently), switching from 3 years of dedicated open source Python development, mainly in the Zopes and Plone, to Microsoft ASP.NET. I thought that a post is some of my observations on the transition would be interesting.

ASP.NET has a very different ethos to any of the Python frameworks I have used in the past. It is far more frontend orientated, with most of the functionality tied in some way to the HTML page. The typical way to construct a page in ASP is to embed (pre-built) ASP html controls into a page’s markup (using XML). Examples of the controls are textbox, label, image, table etc. There are python frameworks that do this, it’s not that unusual, but ASP takes it to a whole new level.

One of the most useful functions of a control is that it is capable of automatically maintaining its own state throughout multiple POSTS and reloads. Fill in a text box and on page reload you text will still be there without you having to code anything.

Control can also disseminate datasources, such as SQL, Arrays or even web services. A table control can be linked to a SQL datasource which will then render as a HTML table of data without writing a single line of actual code.

The power of these controls far surpasses those available in python frameworks, especially if you start buying commercial controls. A table control can by default render a HTML table capable of allowing end user to filter, group, sort and export the data. Nice ajax updates are also relatively simply. Link the table control to an ajax manager control and any functions that would previously have been a POST get transformed to ajax. As a nice example you can generate graphs from a datasource control using the charting controls in about 2 minutes.

So where is the down side, there has to be one right? Yes there is. The main problem with ASP.NET is actually where Python shines: in the elegant control of information from source to page. ASP may well be able to do very clever things quickly and simply on the front end, but controlling the data through a full lifecycle can be a pain as soon if you want the least bit of customisation.

How do you check for specific errors that occur when fetching data on one of those fancy automated datasources? - You have to subscribe to its events. What if I want to change how and when the data is fetched? – You have to hope the control exposes the functionality you want and documents it. In comparison Python frameworks almost universally provide a very consistent model for the organisation of data, from your SQLAlchemy model, to your queries to your View and data marshalling up to the template. It can be done nicely is ASP but it takes more time and design to get it correct.

Python’s organisational architecture is far superior to ASP’s and only getting better with clean and simple design patters (decorators), WSGI, Clean object models, Views, Routes etc. ASP’s out of the box front end elements are equally as superior to anything Python frameworks has to offer, the likes of Deform are a nice clean, Pythonic start but don’t get anywhere near to power of their ASP equivalents.

Monday, 13 September 2010

Zope Interfaces on Anonymous Functions.

Pretty old, but It's something I've not come across yet as a Zope coder. I was reading about Zope Interfaces vs. Python's ABC and found that in Zope you can attach interfaces to any object in Python, not just classes, and since pretty much everything in Python is an object.....
You can never have too many examples of getting stuff to work, so to illustrate the point, I give you: attaching an interface to an anonymous function.

from zope.interface import Interface, implements, directlyProvides
from zope.component import getGlobalSiteManager, adapts

class ILambdaExpression(Interface):
pass
class IConcreteInterface(Interface):
pass

class MyAdapter(object):
implements(IConcreteInterface)
adapts(ILambdaExpression)
def __init__(self, lambda_exp):
self.lambda_exp = lambda_exp
def __call__(self):
return filter(self.lambda_exp, [1,2,3,4,5,6])

gsm = getGlobalSiteManager()
gsm.registerAdapter(MyAdapter)

myFilter = lambda i : i > 3
directlyProvides(myFilter, ILambdaExpression)

result = IConcreteInterface(myFilter)()
print result

>>> [4, 5, 6]

Simple but pretty cool.

Tuesday, 10 August 2010

Error checking II

Last month I wrote a blog on why error checking and correction should be documented better and discussed more. In addition the "how" of error checking, it also seems like the "where" to error check can be ill documented and is effected by the tools and frameworks you maybe using.

When designing a function/method one decision that always needs to be made is whether to throw an exception or return a error/default value on an irrecoverable error. The best solution is normally to throw the exception. Returning a default value can make the API more complex, reduces the details about the original error and makes the code difficult to extend and debug. Catching the exception and returning a sensible default value is usually best left to the last point at which you can intercept it. This generally means directly before it hits the user interface.
def myFunction():
"""Allows an errors in doSomething to propagate.
Returns an array or throws an exception."""
return doSomething()

def myDefaultFunction():
"""Returns a default value.
Returns an array.
"""
result = []
try:
result = doSomething()
except StandardError:
pass
return result

A good example of why this can get messy is the MVC architecture pattern. MVC separates the data logic (Model), presentation logic (View) and the Controller which negotiate responses and submissions. The natural place for those pesky unresolved errors is in the View where they can be handled appropriately. The problem occurs because in a lot of frameworks the View is often synonymous with a template that doesn't have the necessary control to handle uncaught exceptions*. So we have to move the logic out, but the View has access to both the Model and the Controller (if it doesn't, it's not MVC) and we don't really want to have to catch exceptions and return default values in the Model. The Model controls the data and is important to the business logic; errors here need to be explicit, not default. So this leaves is with a bit of a mismatch of requirements that can further muddy the waters leading to clear and concise error checking.

* There is a lot of ambiguity in the definition of MVC, but the fact remains that a lot of frameworks explicitly allow the user access to both the View logic, be it template, presentation code, or both, and the Model (context).