NHibernate and the Repository Pattern


I’ve been writing a small time tracker web application to teach myself ASP.Net MVC, and am using NHibernate as the ORM.  I’m trying to use best practises while building this app, and one issue I was trying to deal with was whether to build a layer over the top of NHibernate. My first set of controller actions used NHibernate directly, with a dependency injected ISessionFactory. This was fine for simple queries (like get Task with id 1) but it meant more and more of my model concerns were leaking into my Controllers. I had thought that NHibernate provided enough of an abstraction over my model for this to not matter, but I was quite wrong.

Remembering I had seen some argument over whether using a generic repository was a good idea or not, I started searching around and found quite a few blogs saying it was a bad idea. They made sense, and one blog had a great solution: Create a Repository<T, U> abstract class for common CRUD style operations, inherit your specific Repository from that, and only expose meaningful methods in your interface to client code. The benefits of this approach are many – your client code can only see methods that are applicable to each model class, you don’t have to duplicate your common CRUD operations for each model class, and it is easy as pie to unit test.

This last point is the one worth mentioning in my books. The great thing about separation of concerns is it should make things easier to pull apart for unit testing. Because my Repository methods have meaningful names, and are pretty fine grained, my mocking setup looks almost readable. It is immediately obvious from reading my tests that TaskController.List(5) should call ITaskRepository.GetLatestTasks(5). Not only that, but most of the Controller actions have been reduced to “Get this from Repository, return to View” or “Save this thing to the Repository”. They are small, obvious methods, and that makes them easier to test, and easier to maintain.



Windows 7 Shortcut Keys


I found a great list of keyboard shortcuts for Windows 7 today here. The best part of this list were the keys for manipulating windows – Windows + ← (Left Arrow) will dock the window to the left hand side of the screen, much like if you drag the window to the side of the screen. The right arrow also works like this.

If you have multiple monitors, using the mouse it doesn’t let you dock to the side connected to the other screen. So you can only dock to the far left and far right with the mouse. Not so with the keyboard. Each time you hit the keyboard combo, it will move it to the next dock position in that direction. That means you can have windows docked all over your extended desktop, like so:

Desktop

I’ve got two windows on each screen (as you can see, the right hand screen has the task bar, so you should be able to see where the screens split).

This is pretty useful at home. Having huge screens is great, being able to have 4 docked windows without fiddling around with the mouse is fantastic.



Fun with the Symbian Emulator


The other night I stumbled on the PyS60 project, an open source port of the python runtime to Symbian S60 based phones. I own a Nokia N95, and I got kind of excited about this because I would like to mess around with development for it but can’t bring myself to work with C++ in my spare time.

I thought it would be pretty easy to develop for as Python is interpreted, I thought I could just edit text files on the phone and run them to test them out. Turns out you can’t do that (not easily anyway), you need to package them on your computer, then upload the package to the phone, then install it, then run it. That killed that idea.

I looked at the Symbian emulator, and the PyS60 team have a mod for it that installs the python runtime so you can just run script files on the emulated phone. “This is great!” I think, before actually trying it.

For starters, the python runtime doesn’t work in the emulator when the emulator is running on Windows 7 x64 – damn. I have a VPC image with Windows XP on it though, so I fire that up, install everything, then try run it. The emulator crashes after about 15 seconds of loading.

After browsing the Nokia forums for a while, I find out the problem. VPC is actually connecting to the virtual machine over RDP, and so the audio drivers are the RDP Remote Audio drivers.

What do audio drivers have to do with a phone emulator I hear you ask? Good question, but it is one the Nokia forum dwellers have no answer for. Many people have complained that the Symbian Emulator does not work when connecting to the machine hosting it via RDP. There are other issues with particular sound card drivers or applications also causing it to crash. This is a prime example of bad error handling. Why, if the audio part of the emulator cannot work with some drivers, does it crash instead of continuing without audio?

So that brought down my plans for making millions of dollars from fart applications for Symbian based phones.



Strange Visual Studio lockup after debugging


I had been having an issue with VS 2008 on Windows 7 x64 today. After debugging an application the whole IDE would lock up, minimise itself, then bring itself back to the foreground. This was pretty disruptive and I was getting quite irritated with it, but I could not find any mention of it through Google.

I did happen to stumble upon a StackOverflow question (here) where a different problem was outlined, however this answer reminded me of an issue Scott Hanselman had with an app he was doing a demo with, so I thought I would give it the fix a shot. Strangely enough, I think it has fixed it, although I am not sure why (it seems unrelated). Anyway, here is the fix, just in case anyone else has a similar problem:

Fix:
Disable checking of Publisher’s Certificate Revocation

  1. Go to Internet Options in Internet Explorer or Control Panel
  2. Then go the Security Tab, scroll towards the bottom
  3. Uncheck the ‘Check for Publisher’s Certificate Revocation’ checkbox
  4. Click OK.


New Monitor


Today I got a new 24″ Samsung T240 for my office at home. I’ve been working from home a lot recently and have really been missing my dual monitor setup from work, even though it is only my laptop with an old 17″ LCD. Two monitors definitely make a big difference to my productivity when coding. I already had a 22″ Samsung 226BW, which now looks thoroughly inadequate next to the 24″ as you can see from the photo below.

My New Desk Arrangement

My New Desk Arrangement

Once I got used to the larger monitor I had a pretty productive day though. The T240 is a decent monitor for developing on, judging from one day’s usage. Text is clear, and after a little tweaking the colour looked about right, enough for my purposes anyway. Not to mention it is a nice looking monitor. All in all, it was well worth the money I/the business spent on it.



Twitter, or How I Learned to Stop Worrying and Love Short Messages


Today I took a bold step, swallowed a chunk of my pride, and signed up for Twitter. I’m not usually a big fan of Social Networking, but Twitter is slightly different. For starters, I don’t think any of my friends are using it. Secondly, There’s no real "profile" like you get from Facebook or others.

I got the idea from Ayende’s blog, kindof. His blog is quite interesting to watch, because it is made up of lots of small updates. It almost seems like more of a note taking system than a blog sometimes, in a good way. For myself, I tend not to write blog posts because they take a little longer than I’m willing to give during the day to write, so Twitter’s 140 character limit could work for me. It’s just a trial anyway, if it doesn’t work out I’ll dump it.

So how I think I’ll work now is: Post short messages to Twitter like reminders, helpful hints, and status updates, and post longer information like information about side projects and interesting topics on my blog.

If anyone wants to follow me on twitter, here’s my page: http://twitter.com/jamiepenney. Be aware that there will be a bit more personal stuff there, my blog so far has just been technical but I’ll probably use Twitter for personal and work messages.



Ook Interpreter, Written in C# and F#


Another little short side project I worked on over the weekend was an interpreter for Ook, an odd little language "designed for Orangutans". It only has a few syntax elements and 8 different statements so I figured it would be a fun use of my basic F# skills (I’ve been reading Fundamentals of F# and Expert F# on Safari Books through work). Using the example files on bluesorcerer.net as test files, I successfully got it running in half a day. I can’t say it is the fastest or most efficient interpreter for Ook, but it is my first interpreter so it was a learning experience. If you have any questions or comments on how I implemented it, please feel free to add them below.

Enough talk, here’s the source: OokInterpreter.zip

You’ll need the latest F# CTP installed to open this project.



Viewing Dependencies Between Projects in Visual Studio


A while ago there was a question on Stack Overflow about how one could go about mapping the dependencies between Visual Studio projects and solutions (see here: http://stackoverflow.com/questions/471154/how-can-i-map-out-which-visual-studio-solutions-use-which-projects). At the time I had been doing a little bit of work with GraphViz, and suggested that it could be used for the diagramming part. The problem itself seemed kind of interesting, so I decided to implement a solution myself for kicks.

My tool takes a visual studio solution, and produces a PNG image showing the dependencies between the projects in that solution. Pretty basic stuff, but it involves:

  1. Parsing a Visual Studio .sln file.
  2. Parsing the .csproj files referenced in the .sln file. (I don’t think it is C# specific but have not tested it on other project types).
  3. Creating an in memory representation of the solution structure.
  4. Creating a graph in QuickGraph to represent that structure.
  5. Creating a dot file for GraphViz from that graph.
  6. Pass that file to GraphViz and display the output.

This results in something like this:

dv_output

The source code is here. Feel free to do what you like with it, it only took me about 3-4 hours to get it all working. However if you actually use it as part of another project, please leave a comment.

You’ll need the latest version of GraphViz, which can be downloaded from here: http://graphviz.org/Download_windows.php. I’ve been using the development snapshot, but the stable release should be fine. When my tool first runs, it’ll ask you for the location of graphviz. You need to specify the location of dot.exe, which by default is in %Program Files%\GraphViz 2.21\bin.

Standard disclaimer: I’m not responsible for anything that goes wrong when using this thing. You have the source, you should check it out before running it. If it wipes your system and kills your firstborn child feel free to let me know, but don’t expect me to do anything about it.



TechEd 08 – Day 3


DEV375: Reactive Programming – Ivan Towlson

  • History of developing for windows clients
    • Win16/Win32 – Procedural style (message loops)
    • ActiveX/Visual Basic – Limited OO style, events + components
    • Windows Forms – Component oriented style
    • Common themes
      • Write code to copy data from model to control
      • Write code to detect changes in control data
      • Write code to copy data from control to model
      • Detect changes in model data or use gatekeeper
  • What is better about WPF/Silverlight?
    • Enhanced component model encapsulates common plumbing.
    • Designer-developer workflow needs a declarative programming style to work well.
    • Hard to write robust OO/procedural code against a lookless model.
  • Reactive programming is like binding values together. Think like how you can create formula’s in Excel – changing the value of one of the cells in a formula updates the result of the formula, and it keeps doing it.
  • Benefits
    • Remove plumbing code, no need to track changes in model and controls and copy data between
    • View/model relationship expressed in view instead of in controller/presenter code. Express the what, not the how.
    • Works well with the lookless approach – view reacts to model change, rather than the model manipulating the view.
  • .Net works on a notification system (INotifyPropertyChanged) – when something changes, dependent values re-evaluate themselves.
  • Issues
    • We need to react to changes to derived data -> use converters for this.
    • A reactive expression may produce unacceptable values (user input?). Solution is to use validation.

Bindable LINQ

  • How do you query an ObservableCollection? How do you observably query an ObservableCollection?
  • LINQ queries don’t provide change notification!
  • Bindable LINQ is a community project to enable reactive controls to back easily onto LINQ queries
  • Key API : AsBindable() – extension method on IEnumerable<T>

SEC201: Do These Ten Things or Get Own3d – Steve Riley

1. Use precise terminology

  • Vulnerability – The problem
    • Code
    • Configuration
    • Circumvention – Security rules that are so draconian that they encourage people to actively try to get around it.
  • Threat – The person that carries out the attack
    • External
    • Internal
  • Exploit – the code that exploits the vulnerability
  • Exposure – The cost of the attack being carried out.
  • Risk

2. Accept that no one will like you

3. Think like a bad guy

People will not like you for this either.

4. Understand the science

  • Identity is not Authentication.
  • Encryption is not Integrity
  • Inspection is not Intent – Can’t tell intent by looking at someone’s stuff.
  • Secrecy is not Trust – just because you can make something a secret, doesn’t mean you can trust it.
  • People are not Technology – All the technology in the world will not solve your technology problem.
  • "Defence in depth" = "I am a parrot"
  • Stupidity is not Malice
  • Usability and Security are a tradeoff.

5. Protect your gear

  • Patch your stuff.
  • Use the firewall.
  • Don’t run as admin, or reduce number of admins.
  • Install anti-malware, or scan fileshares.
  • Don’t tweak.
  • Rebuild, don’t disinfect.

6. Swallow your pride

7. Reconsidering the laws

  • Law 1: If a bad guy can persuade you to run his program on your computer, it is not yours anymore.
  • Law 2: If a bad guy can alter the operating system on your computer, it’s not yours anymore.
  • Law 3: If a bad guy has unrestricted physical access to your computer, it’s not your computer anymore.
  • Law 4: If you allow a bad guy to upload programs to your website, it’s not your website anymore.
  • Law 5: Weak passwords trump strong security.
  • Law 6: A computer is only as secure as the administrator is trustworthy.
  • Law 7: Encrypted data is only as secure as the decryption key.
  • Law 8: An out of date is only marginally better worse than no virus scanner at all.
  • Law 9: Absolute anonymity isn’t practical, in real life or on the web.
  • Law 10: Technology is not a panacea.

8. Classify, and classify again.

  • Access
    • Principle of least privilege – others and yourself. If this principle interferes with your business process and is part of the OS, email Steve.
  • Data
    • Confidentiality, retention, recovery.
  • Trust
    • Functions, directions.

9. Don’t let your guard down.

  • People are always trying to sell you silver bullets/snake oil.
  • Trustworthy people will discuss the downsides of their software

10. Protection, not restriction.



TechEd 08 – Day 2


ARC202: I am not an Architect, I am an architect – Dr. Neil Roodyn

  • Why do most projects fail?
    • There are risks in developing software – laws, quality, misunderstood business needs, etc.
    • Unhappy customers.
  • History
    • Pioneering era – early computing. Software Development Process: Chaotic.
    • Stabilizing era – First demand for programmers,structure comes to development. SDP: Predictability. Based on engineering discipline.
    • Micro era – Drop in price of computing, more customer expectations.
    • Internet era – mid 90’s till present. Interconnectivity, change in pace of development. Customer expectations have outpaced developer abilities. SDP: Adaptive.
  • Predictability might be impossible in a creative field.
  • Requirements change in every project. "Change is Inevitable".
  • Software needs to move away from the separation of architect and developer.
  • The majority of the cost of a system is usually the software development, and the major component of that is personal costs.
  • Craftsmanship is a different approach to software development.
    • Needs dedication – constant learning.
    • Duplication of software is low cost – this makes it more difficult to get revenue from your work.
    • Mentoring – Share experiences and knowledge.
    • Taking time out to think about things in the background – some of the best ideas are discovered while not actively thinking about the problem.
    • Accomplishment.
    • Need to set up processes so that developers can learn from their own and others mistakes.
  • Why promote the best coders into positions where they don’t write code?
  • Customers have a lot of choices – need to educate them on the tradeoff between cost and quality.
  • Happy developers create better quality code.
  • High quality software is possible – needs good supporting tools.
  • People over process.

SEC314: Secure Development Patterns – How not to screw yourself during development – Corneliu L. Tusnea

  • Distributed authentication systems work by verifying security tokens are valid, rather than verifying usernames and passwords on each service. The more times the password verification code has to be repeated the more chances there are for data leakage or failure.
  • Security should not be part of the code, it should be part of some external configuration – what user can use what services.
    • You still need to set attributes in code to determine what services to manage with security. This provides a better security model as there is only one place for look for specific security policy, and the code only needs to be referred to determine if it can be configured with security policy.
  • XSS protection is difficult to do yourself – the Microsoft security guys have written a library called AntiXSS, use that. HtmlEncode does not protect against XSS attacks. You should create a basic replacement for Label and Literal that AntiXSS encodes the text it displays and set up a TagMap to these new tags.
  • Validators are a source of duplication in a system.
  • Exceptions can leak information if used naively. A better method is to attach an enum to your exceptions, and to show a message based off of that. This gives you an easy way of internationalising error messages too.

WEB305: Pumping Iron: Dynamic Languages on .Net – Harry Pierson

  • Tradeoff between Type Safety and Flexibility
    • Rails ActiveRecord example – AR adds the column names of a table as properties on the model class at run time.
  • Real products are being shipped on IronPython – ResolverOne
  • Dynamic languages are very productive – good for initial work on greenfield projects.
  • Dynamic languages are not as fast as Static languages, so optimise by replacing slow parts of Iron(Ruby/Python) with C#. This is easy in the Iron* languages.
  • Dynamic Languages are easy to teach and learn.
    • Short on Ceremony – You don’t have to add extra stuff like package management or class creation to python if you don’t want to.
  • Formatting and whitespace matters. All Python code looks the same, so it is easy to start working with someone else’s code.
  • Dynamic languages are powerful.
    • AOP is easy in Python – it is possible to pass functions around as they are first level citizens, or you can use decorators to wrap functions.
    • You can create new types at runtime – example given was an XML to Python loader, which created Python objects from any given XML document.
  • Iron* languages are first class .Net citizens.
    • Interop with other .Net code. Easy to use C# or VB.Net code from Iron* languages, but it is harder to go the other way. Standard .Net assemblies just work in Iron*.
  • Iron* languages are embeddable by using the DLR.
  • Microsoft are working on integration with Visual Studio currently, due in 2009.
  • IronRuby and IronPython are both true Open Source.