Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load On Error GoTo OwDear Stupid: On Error Resume Next Throw New Exception("Dun gone wrong.") On Error GoTo OwDear Throw New Exception("Another error.") OwDear: MsgBox("Another error.") End SubDocumented: http://msdn.microsoft.com/en-us/library/5hsw66as.aspx This is just awful!
Thursday, 31 January 2013
Asp.net will actually let you handle errors like this
VB.Net on a ASP.Net completely legit web page will do this:
Thursday, 5 July 2012
C# Anonymous, Lambdas, Delegates and Expressions...phew.
C# and by extension any .net language has complex support for both anonymous functions and lambdas. I found it quite useful to have a basic reference for these; so here it is.
Linq Expressions is where things start to get more complex. Linq expressions allow lambda functions to be reflected and turned into data instead of code, allowing you to change the function. A typical change would be from a .net lambda function to an SQL statement.
// Anonymous function using the delegate keyword. Func<string> anon = delegate() { return "x"; }); // Anonymous function from lambda. Func<string> lambda = () => "x"; // Same but using explicit typing. var anon2 = new Func<string>(delegate() { return "x"; });The function references (anon, lambda, anon2) are known in .net as delegates which is nomenclature for function pointer. Because C# is statically typed we have to explicitly type the delegate, hence 'Func'. Func is a generic delegate type: a predefined delegate, rather than having to specify it constantly. We could explicity define the delegate like this.
// Define delegate. delegate int myDelegate(int i); // Assign delegate. myDelegate anon = delegate(int i) { return i }; myDelegate lambda = x => x + 1;
Linq Expressions is where things start to get more complex. Linq expressions allow lambda functions to be reflected and turned into data instead of code, allowing you to change the function. A typical change would be from a .net lambda function to an SQL statement.
// Expression Expression<Func<string>> exp = () => "x"; // Can't be done. // Expression<Func<string>> exp2 = delegate() { return "x"; };However note that Linq Expressions cannot be created using anonymous functions. OK if you followed all that....lambda can also be written with a statement body rather than an expression body as we have seen so far. Statement bodies allow more complex multiline functions.
// Statement lambda Func<string> lambda = () => { return "x"; };Statement and expression body lambdas are functionaly identical, but they are different. Statement body lambdas cannot be made into expression trees. In practice this means that certain linq providers, such as Linq2Sql cannot use lambda functions created with statement bodies.
A lambda expression with a statement body cannot be converted to an expression treeOne final quirk I'll mention is that once you have an explicit Expression it can be used on an IQueryable, but not a standard IEnumerable. You have to 'unwrap' it, converting it back to a standard Func.
// OK, compiler sorts it out var l0 = new int[] { 1, 2, 3 }.Where(x => x < 2); var l1 = new int[] { 1, 2, 3 }.AsQueryable<int>().Where(x => x < 2); // Force exp to be an Expression Expression<Func<int, bool>> exp = x => x < 2; // Doesn't work - invalid arguments //var l2 = new int[] { 1, 2, 3 }.Where(exp); // Works on IQueryable var l3 = new int[] { 1, 2, 3 }.AsQueryable<int>().Where(exp); // Convert Expression back to standard Func to make it work. var l4 = new int[] { 1, 2, 3 }.Where(exp.Compile());
Labels:
.Net,
anonymous functions,
C#,
lambda,
linq,
programming
Thursday, 15 March 2012
C# Optional Arguments Gotcha
I came across an interesting quirk of C#'s optional arguments when coding a MVC site against my Linq2Sql BLL. The BLL handles all my database logic including the creation of the Linq DataContext. In some edge cases I need to recycle an existing DataContext; so I made the DataContext an optional parameter. All good until I instantiated a new instance of the BLL in my shiny new MVC website - new BLL() - and encountered this error:
Apparently the calling code must know about the optional object type even when it's not specified. After some googling it looks like the optional parameters are baked directly into the IL at compile time. It wouldn't make sense to do this on the callee side, so this seems very odd behaviour.
Error 11 The type 'System.Data.Linq.DataContext' is defined in an assembly that is not referenced.
Apparently the calling code must know about the optional object type even when it's not specified. After some googling it looks like the optional parameters are baked directly into the IL at compile time. It wouldn't make sense to do this on the callee side, so this seems very odd behaviour.
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.
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?
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.
You can use it like so:
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}}{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.
This caught me out because the syntax is very C# and I use VB.Net.
You can also do this programmatically.
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]")
Subscribe to:
Posts (Atom)