March 30, 2008 at 12:08 pm
· Filed under C#, java, lisp, python, ruby
For the last few years I’ve been learning and using Lisp more, and here is a disorganized, poorly-worded dump of how Lisp changed my opinion about other languages.
Static Types (as implemented by C# and Java) are oppressive.
I spend most of my time in C#, and it always feels like I’m toiling in the Type mines under the iron fist of compiler. I frequently run into problems where I can’t abstract common code because the .NET framework doesn’t use C#’s abstraction mechanisms enough (more detail). In Lisp it feels like types are a tool I can employ when I need it, but it’s rare that I need COERCE something from one type to another. Too much of my C# is devoted to casting to / from types, a hefty tax I pay to the compiler.
Syntax doesn’t have to be so hard.
I was recently working on a ruby script, and had to stop and think: “what does ruby want for ifs again? curly braces? indentation?” In Lisp it’s easy: it wants matching parentheses. You can add syntax if you find it useful (CL-INTERPOL is one of my common additions), but there’s nothing I need to remember, no need for cheat sheets. The simplicity also highlight the strangeness of things like python’s “pass” statement. There’s no human meaning to a pass statement, it’s just to handhold the parser, and I don’t think that should be one of my responsibilities.
Development tools don’t have to be such a pain in the ass.
In C#, I frequently end up waiting for Visual Studio, and that’s on a modern dual-core workstation with 2GB of RAM. In Lisp, I end up waiting once when I start slime/emacs, and once when I initially load a big system, and then everything else is pretty instant. That’s on my Asus EEEpc, a 900MHz Celeron with 512MB RAM. I could use cores to eliminate most of that start-up time. At work we have one fast server we all use to run our lisps, and if we didn’t have to run programs like Visual Studio, we could use low-power, low-cost workstations and be perfectly happy. I know some people think Emacs is a heavyweight program, but devenv.exe sets a new standard.
Variables don’t have to be so hard.
LET statements and lexical scoping in lisp are pretty basic, and meet all my needs. The scoping rules in other languages seem really overcomplicated by comparison. In C#, sometimes curly braces open a new scope, but sometimes not. Sometimes you have to declare variables away from their usage in order for them to be available in all the right scopes you want. In python / ruby, I’m frequently confused whether I’m declaring a new variable or using one from a higher scope. Most of that is from lack of ruby/python practice, but even when first learning Lisp, the rule was so simple that I never had trouble with it.
Permalink
February 13, 2008 at 6:58 pm
· Filed under ASP.NET, C#, annoying
Problem: .NET framework classes don’t use interfaces enough
Specific example: DataSource / DataBind()are separately defined on Repeater and GridView, (and Control, and many, many others), and my abstract base class doesn’t care which option an implementor chooses, it just wants to bind the data however the base control wants it.
Possible Solutions:
- Define interface
IDataBinding, class MyRepeater : Repeater, IDataBinding, class MyGridView : GridView, IDataBinding, etc.
Define interface IDataBinding, upgrade to C# 3, use extension methods to add IDataBinding nope, extension methods can’t do this
- Copy/paste identical code from my base class into concrete classes
- Use reflection to set
DataSource and call DataBind(), completely sidestepping the C# type system
Problem: .NET framework classes not designed for extension: “
cannot override inherited member 'System.Collections.Generic.Dictionary<X, Y>.Add(X, Y)' because it is not marked virtual, abstract, or override“
Specific Example: Extending System.Collections.Generic.Dictionary to do some permit a list of values for one key, so adding the first item is stored as a single value, but adding a second value to the same key stores both values in a list. Error message is: “cannot override inherited member 'System.Collections.Generic.Dictionary<X, Y>.Add(X, Y)' because it is not marked virtual, abstract, or override“
Possible Solutions:
- Define wrapper classes that encapsulates the framework class and implements all the base interfaces, with the vast majority of the code being straight delegation to the framework class:
class MyDict : IDictionary, [other interfaces...] {
private Dictionary<X,Y> dict = new Dictionary<X,Y>;
public bool Contains(X key){ return dict.Contains(key);}
[... other simple wrappers...]
}
- Find a less appropriate framework class that is designed for extension, duplicate behavior of the proper framework class manually, eg: add run-time type checks for
Hashtable.Add(object, object) in place of the letting the compiler handle the types as in Dictionary<X,Y>.Add(X, Y)
- Extend Dictionary<X,Y>, define a method
AddList(X,Y), and avoid using IDictionary in the rest of my code
- Upgrade the C# 3, use extension to add function
AddList to IDictionary, be sure to include those extensions on every consumer of IDictionary
Problem: .NET framwork classes not designed for extension: members declared private/ internal / protected internal
Specific Example: Storing additional data in ViewState on 2 different controls that have different base classes. One is a user control, another extends RadioButtonList to provide different UI for the same data
Possible solutions:
Upgrade to C# 3, use extension methods to add functions nope, extension methods can only see public members, ViewState is protected
- Use reflection to set
ViewState
- Copy/paste code into each control
- Define interface
IPublicViewstate, class MyRadioButtonList : RadioButtonList, IPublicViewState, class MyUserControl : UserControl, IPublicViewState, etc
As Nathan said, I’m stuck between a rock and
IHardPlace.
Permalink
July 5, 2007 at 6:17 pm
· Filed under C#, code snippet
I'm working on a simple command-line app, and have the need to collect a username and password. I don't want the password to be printed on the screen as they type, but System.Console.ReadLine doesn't seem to have any option to mask the input before it's echoed back to the console.
There are a couple ways I found to resolve this, the easy way, and the harder way with better UI.
Easy way:
C#:
-
ConsoleColor oldFore = Console.ForegroundColor;
-
Console.ForegroundColor = Console.BackgroundColor;
-
string password = Console.ReadLine();
-
Console.ForegroundColor = oldFore;
This basically hides the echoed input by setting the text color to be the same as the background color. This is a little weird because your users can't see any indication that they've entered any information.
The following function catches the input, and then echoes "*" instead. There's some rudimentary handling of backspace, but no other special keys (end, delete, arrow keys, etc) are handled properly. For now it's good enough for my use:
C#:
-
public static string ReadPassword() {
-
Stack<string> passbits =
new Stack<string>
();
-
//keep reading
-
for (ConsoleKeyInfo cki = Console.ReadKey(true); cki.Key != ConsoleKey.Enter; cki = Console.ReadKey(true)) {
-
if (cki.Key == ConsoleKey.Backspace) {
-
//rollback the cursor and write a space so it looks backspaced to the user
-
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
-
Console.Write(" ");
-
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
-
passbits.Pop();
-
}
-
else {
-
Console.Write("*");
-
passbits.Push(cki.KeyChar.ToString());
-
}
-
}
-
string[] pass = passbits.ToArray();
-
Array.Reverse(pass);
-
return string.Join(string.Empty, pass);
-
}
A bit messy and bug-ridden, but for now it's good enough for my purposes. When C# 3 comes out, I might be able to add things like this to the Console class using extension methods. Maybe a community-driven FrameworkPlus library will get some momentum, and we can all ditch our home-grown Utils libraries and reap the benefits of each other's work.
Permalink
June 19, 2007 at 3:22 pm
· Filed under ASP.NET, C#, CAS, open source
For a recent project I wanted to authenticate using Central Authentication Service (CAS), a single-sign on server deployed world-wide. My project is in ASP.NET, so I hunted down CASP, a C# class produced by John Tantalo at Case Western Reserve University. Coincidentally, John was also responsible for Planarity, a flash game which has only stolen mere days of my life.
I had a few nits to pick with it, so at the risk of calling his baby ugly:
- Doesn't handle the latest CAS protocol, CAS2
- Dumps the authenticated username into Session, which isn't what I wanted
- Doesn't use "using" statements when dealing with IDisposable objects
- Doesn't use XML comments, which .NET tools prefer
- Some minor duplication in specifying the login URL and the validation URL.
So, all in all nothing really big. I ended up going a little nuts with it resolving all my complaints. It can now speak CAS1 or CAS2, and has a bunch of options that I added in to solve my specific needs. It seems a little overcomplicated now, but I always get that feeling when I'm thinking in C#.
Installation
Pretty simple:
- Download the source: CASP.cs (BSD license)
- Add it to your project
Example usage
Like Tantalo's CASP, mine is designed to be used from a System.Web.UI.Page, and will redirect the browser about as needed.
Simplest example, uses CAS2 by default
C#:
-
protected void Page_Load(object sender, EventArgs e) {
-
string username = CASP.Authenticate("https://login.case.edu/cas/", this.Page);
-
//do whatever with username
-
}
Slightly more complex, using CAS1 and always renewing the authentication ticket
C#:
-
protected void Page_Load(object sender, EventArgs e) {
-
string username = CASP.Authenticate("https://login.case.edu/cas/", this.Page, true, false);
-
//do whatever with username
-
}
Most complex example, giving you flexibility to decide what to do about errors, etc
C#:
-
protected void Page_Load(object sender, EventArgs e) {
-
CASP casp =
new CASP
("https://login.case.edu/cas/",
this.
Page,
true);
//re-login every time
-
if (casp.Login()) {
-
try {
-
string username = casp.ServerValidate(); //or casp.Validate() for CAS1
-
//do whatever with username
-
}catch (CASP.ValidateException ex) {
-
//try again, something was messed up
-
casp.Login(true);
-
}
-
}
-
}
This code is certified:

Permalink
May 25, 2007 at 1:29 pm
· Filed under C#, annoying, code snippet
I was recently implementing some custom events, and found a couple of good (if old) articles describing how to do this efficiently using EventHandlerList:
Those articles go into why it's nicer to deal with one EventHandlerList instead of many seperate EventHandlers, so read those for more information. For the lazy, here's some code showing how you're supposed to use these things:
C#:
-
public class MyClass {
-
private EventHandlerList Events =
new EventHandlerList
();
-
-
public event EventHandler MyEvent {
-
add { Events.AddHandler("MyEvent", value); }
-
remove { Events.RemoveHandler("MyEvent", value); }
-
}
-
-
public event EventHandler MyOtherEvent {
-
add { Events.AddHandler("MyOtherEvent", value); }
-
remove { Events.RemoveHandler("MyOtherEvent", value); }
-
}
-
-
protected void OnMyEvent(object sender, EventArgs e) {
-
EventHandler handler = (EventHandler) Events["MyEvent"];
-
if (handler != null) {
-
handler(sender, e);
-
}
-
}
-
-
protected void OnMyOtherEvent(object sender, EventArgs e) {
-
EventHandler handler = (EventHandler) Events["MyOtherEvent"];
-
if (handler != null) {
-
handler(sender, e);
-
}
-
}
-
}
Pretty straightforward stuff. When you add an event handler to the list, you associate it with a key, and then when its time to trigger the events, you look for any handlers under the same key. The other day I was putting together something similar, and ran into some unexpected behavior with the keys. I had started by refactoring the magic strings into an enum:
C#:
-
protected enum MyEvents {
-
MyEvent,
-
MyOtherEvent
-
}
and replaced all the strings with members of that enum. I figured this would work just fine, but the change caused my unit test to fail. Upon debugging, the EventHandlerList was always returning null in my On*Event calls. After some more testing, the pattern became apparent: value types don't work as keys. This was somewhat unexpected, as I've used enums like this in Hashtables all over the place before. After doing a little Reflectoring, the actual search for the key comes down to traversing a linked list with a simple equality test, something like this:
C#:
-
while (head != null)
-
{
-
if (head.key == key)
-
{
-
return head;
-
}
-
head = head.next;
-
}
The culprit ends up being C#'s auto-boxing. The key is stored as an object, so my value types are being boxed on the way in, and therefore == is comparing object identity, not the object values. If EventHandlerList used head.key.Equals(key), everything would have worked how I expected. The solution to rid myself of magic strings now becomes using static objects as my keys, so the object identities will match:
C#:
-
private static readonly object MyEventKey =
new object();
-
private static readonly object MyOtherEventKey =
new object();
That pattern reminds me a lot of enums in Java before it got a enum keyword, which came on the heels of C#'s nice solution to the enumerated type problem. It'd be nice if I could use enums for their intended purpose, but cases like this make me a bit wary. Where else in the .NET framework am I going to find object identity equality where I expect to find object value equality? Is there some rational explanation for this, or is this just a bug?
Permalink
December 29, 2006 at 12:45 pm
· Filed under C#, code snippet
I've been playing with generics more, trying to ease the slog of C# development. The .NET framework allows you to do damn near everything, but its so freaking verbose. Almost anything I want to do with framework classes ends up taking 4-5 nearly identical lines, so I end up writing a lot of little wrapper functions to make one-liners.
The task I had at hand this time was to take a string of XML and deserialize is back into a C# object. I generated the C# object off of an .xsd file using xsd.exe (more info), so it has the spaghetti of attributes needed for the XmlSerializer.
public static T DeserializeFromXml<T>(string xml){
T result;
XmlSerializer ser = new XmlSerializer(typeof(T));
using(TextReader tr = new StringReader(xml)) {
result = (T) ser.Deserialize(tr);
}
return result;
}
With that utility function, now I can just:
MyClass obj = Utils.DeserializeFromXml<MyClass>(xml);
Working with these libraries, I always end up pondering why Microsoft didn't think to include shortcuts like this.
Permalink
November 17, 2006 at 3:46 pm
· Filed under C#, annoying
Once constant annoyance I've had with C# has been parsing a string into an enum.
Original C#:
MyEnum e = (MyEnum) Enum.Parse(typeof(MyEnum), "myvalue");
Using generics let you write a function to help:
public static T ParseEnum<T>(string name) {
return (T)Enum.Parse(typeof(T), name);
}
So then you can simply* say:
MyEnum e = ParseEnum<MyEnum>("myvalue");
A little nicer, but still annoying.
*: simply for C#
Permalink