OracleParameter AssociativeArray bug in ODP.Net 11
Today I was writing some code that was wrapping up stored procedures for an Oracle database. In one situation we were needing to retrieve a result set based on a list of values that we had in memory. Oracle provides a really sweet bit of functionality that allows you to pass an array to an OracleParameter object and have that value passed through to your stored procedure as one parameter value.
I have no idea how this looks or works on the stored procedure side of things, but it's pretty slick in .Net. All you need to do is create a normal Oracle parameter object, pass the array into the value and set the CollectionType to PLSQLAssociativeArray.
One of the ways that you can create an OracleParameter is to use the constructor overload for (string name, object value). This works fine when you're creating native typed, single value parameters that are have either input or output directions. It even works great when you're creating an output cursor type parameter. When you try to use this constructor overload and pass it an array, things go horribly wrong.
Passing the array into that constructor overload causes an Object Reference Not Set exception to be thrown. After a bit of poking around, it became clear that using a different constructor and setting the OracleParameter.Value property to the array would work just fine.
Offending code
string[] myArray = new string[5] { "sdf", "weo", "wdi", "saf", "vbc" }; OracleParameter parameter = new OracleParameter("myParameterName", myArray);
Working code
string[] myArray = new string[5] { "sdf", "weo", "wdi", "saf", "vbc" }; OracleParameter parameter = new OracleParameter("myParameterName", OracleDbType.Varchar2) parameter.Value = myArray;
I did some looking at the Oracle.DataAccess.dll using Reflector and couldn't seen an obvious reason for this to be happening, but here's what I suspect. The constructor is taking in the array and trying to store it in an internal collection of some type. When it attempts to add values to that internal collection during the constructor execution, the internal collection is still set to null. When you run the constructor and subsequently set the Value property, something has initialized that internal collection, eliminating the possibility of this exception occurring.
Nothin But C# v3.5 Edmonton
It's official. I will be offering the Nothin But C# v3.5 course in Edmonton during the week of March 31st to April 4th. If you're familiar with JP's Nothin But series of courses, you'll know what this is going to be like. If not, here's a brief synopsis of how the course will work.
You arrive in the morning prepared to learn about C# and .Net 3.5. I will take you on a coding ride that will end, depending on your willingness and availability, somewhere between 8 and 16 hours later. Rinse and repeat for each of the five days that week.
Here are the details of the course. Registrations can be made through this link. If you have any questions, shoot me an email at donald.belcham@gmail.com.
Overview
Nothin’ But C# v3.5 is a 5 day boot camp styled course that provides in depth training in the new language features in version 3.5 of the .Net Framework. Attendees will work with the new features in this version of the Framework to gain an understanding of their operation at a very deep level and aid them in the pragmatic implementation of these tools in their daily development.
While learning to use the new features of .Net v3.5, the students will also be introduced to foundational object oriented programming techniques. They will learn both how to implement these techniques as well as understanding the benefits that they offer.
By the end of the course you will have knowledge of the new features at a very detailed level. You will understand the concepts behind their existence, the limitations that they have and how you can use them to write better code in real applications. None of the concepts will be taught using wizards, drag and drop or templates. Attendees will be learning how to implement these language features combined with OO best practices and using techniques such as TDD.
Attendees should have a good understanding of programming in .Net and OO practices. This is not an introductory course for learning to program with .Net.
Core Concepts Overview
- New language features in .Net 3.5
- Extension Methods – helping to make fluent interfaces
- Lambda Expressions – from refreshers on delegates all the way to the lean lambda
- Linq – for SQL, XML, Objects, etc.
- New User Interface Controls
- ASP.NET MVC
- Object Oriented Foundations
Detailed Topic Coverage Breakdown
- New Language Features
- Simple Properties
- Anonymous Constructors
- Anonymous Types
- DateTime2
- TimeZoneInfo
- HashSet<T>
- Active Directory Integration
- Diagnostics
- Cross Framework compatibility
- Extension Methods
- Using with primitive types
- Using with complex types
- Using with enumerations
- Using to build fluent interfaces
- How they are interpreted by the compiler
- Dangers and code smells
- Lambda Expressions
- Refresher on Delegates
- Refresher on Anonymous Delegates
- Refresher on Predicates
- Learn the syntax
- Replacing Anonymous Delegates with Lambdas
- How are they interpreted by the compiler
- Linq
- Linq fundamentals
- How is Linq interpreted by the compiler
- Linq to SQL
- Linq to XML
- Linq to Objects
- Linq to Dataset
- Linq and performance
- UI Components
- ListView control
- DataPager control
- ASP.NET MVC
- MVC fundamentals
- Writing Views
- Routing
- Plugging in Inversion of Control containers
- Testability
- Object Oriented Foundations
- Single Responsibility Principle
- Separation of Concerns
- Design by Contract
- Dependency Injection and Inversion of Control
- Design Patterns
Target Audience
This is an intermediate level course that will prepare developers to work with the release of the .Net 3.5 framework. Attendees should have a working knowledge of .Net and knowledge of the following
-
Core working knowledge of either Visual Basic or C#
-
Base grasp of Object Oriented Design principles
-
High level understanding of SQL Server and XML
Intended Outcomes
Once attendees have completed this course they should have a strong, practical understanding of the following:
-
New base language features in the .Net 3.5 framework
-
Lambda expressions
-
Linq for SQL, XML and Objects
-
Extension methods
-
ASP.NET MVC
-
Design by contract
-
Practical application of basic patterns
-
Test Driven Development
Victoria Code Camp Wrapup
I was out in Victoria last weekend working on my ability to sell myself as well as presenting on C# 3.0 and .NET 3.5 Beyond Link and Parachuting into a Brownfield. Nolan and the people at the Victoria .NET Developer Association have scored a really great location at UVic for this event. The building is new and clean, the rooms are large and comfortable and the A/V equipment is fantastic.
I'm not going to post any code for my C# 3.0 talk. Instead I'm going to point you to a couple of posts from last summer. These three posts (Simple Properties and Anonymous Properties, Extension Methods, and the Follow up on Anonymous Constructors) cover everything from the presentation with the exception of the part on lambda expressions. One day I'm going to post a screencast on lambdas.....one day.....
In my Parachuting into Brownfields presentation there wasn't any code take-aways since the whole presentation was based on a slide show. You can download the slide show here.
If you have the chance, make a trip into Victoria next January and attend the Victoria Code Camp. Its well worth the trip.
Victoria Code Camp '08
If you've got the time this weekend, and you're in the area, drop by the Victoria Code Camp. There are some brilliant speakers at it this year and Tom, Dave and I are presenting in an attempt to ensure some level of mediocrity. I'll be up in the afternoon doing presentations on .NET 3.5 and C# 3.0 Beyond Linq and Parachuting into a Brownfield.
Nolan has setup a Code Camp blog that some of the different presenters have been posting to. It' a pretty cool idea to have something like this to get people interested in the speakers and the topics. If you're wondering what Brownfield is, I have a post there (and on this blog) that describes it.
Setting environment dependant properties in nAnt
This is a little something that I discovered recently while writing some nAnt scripts. I love to have One Script to Compile Them All so that I can ensure that the build server and all the developers are compiling and executing the tests in the exact same manner. One of the things that you will find is that you'll have some variable values getting set one way for the local build and another way for the build on the build server. A really good example of this is what I was showing in my recent post on versioning assemblies using nAnt. In that post I showed a technique for setting a property to hold a version number that is only available when CruiseControl.NET is launching the build script.
<property name="version" value="0.0.0.0"/>
<if test="${property::exists('CCNetLabel')}"> <property name="version" value="${CCNetLabel}"/> </if>
Usually you would think of it existing in the script like this
<project>
<property name="version" value="0.0.0.0"/>
<task name="compile">
<if test="${property::exists('CCNetLabel')}"> <property name="version" value="${CCNetLabel}"/> </if>
</task>
</project>
This ensures that there always is a version number (0.0.0.0 in this case) and that it will be changed when compile is launched by CruiseControl.NET. In my most recent scripting endevour I was faced with a lot of values being set in this manner. At one point I had refactored all the variable setting out into its own task. Every time that I had to add another variable that required this type of treatment, I felt a little bit dirtier about the script. If I had to change the "version" variable, it would potentially need to be changed in two places. That's when I figured out that this will work in nAnt.
<project>
<property name="version" value="0.0.0.0"/>
<if test="${property::exists('CCNetLabel')}"><property name="version" value="${CCNetLabel}"/></if>
<task name="compile">
<!-- do compile stuff in here -->
</task>
</project>
You can add conditional statement to a nAnt script outside of the task elements. All of the property setting and conditionals are executed immediately when the script is loaded by nAnt. This has allowed me to do all of my CruiseControl.NET dependent variable changes within the main block of the script and not have to worry about them being run when a task is called.
It's amazing what a little thing like this can do to help clean up a script.
Controlling the unit test environment
My last post talked about abstracting the implementation of an IoC container so that you could implement more than one container if you had the need to. One of the coolest uses of this kind of abstraction that I've seen in quite some time is what JP Boodhoo did in his Nothin' But .Net Store codebase. I'm going to summarize it here, but you need to look at the code to see how sweet it really is.
In the code base JP has abstracted his IoC container in a very similar way to what I showed in my previous post. On top of the IoC abstraction he has an implementation of a dependency resolver that gives the programmer one point of coding contact that doesn't care which container is implemented inside of it.
If you're looking in the codebase, head on over to the testing project and look through the classes in the \test\xUnit\Utility folder. Here you'll see that JP has implemented a couple of custom attributes. The purpose of these attributes is to give the developer a way to control, at a test by test level, which IoC container is used when a test is executing. Based on the code in his sample app, JP has run into three different scenarios in that code that he needed to be able to handle.
The first scenario is where the test has no need of an IoC container, which results in no attribute telling the test which container to use. If you're working on a very pure unit test, this will be the situation that you're in.
Sometimes you will want your tests to use a container that is configured and implemented just as it would be in production. In that case there is a custom attribute that ensures that the production container is loaded up. Most likely you'd use something like this when you're working on integration tests.
The last scenario is where you want to test a piece of code that has a dependency on a something from the container. The situation occurring in the Nothin' But .Net code is one where there is a logging call in the middle of the unit of code being tested. In this specific case there is a call to a logging container that is using a static call. As we know, static calls make testing very difficult. You can't dependency inject into them. In the case of this logging class, it needs to call the IoC container to load up the logging framework that is being used. Because of this, if you don't load up the container before executing a unit of code that contains a call to the logging class, it will throw an error when it tries to call the IoC container.
The result is that you need to initialize a container before you launch any test that may have logging used in it. The standard way to do that would be to use the StartUp or TestFixtureStartUp methods in your test suite. What happens if you need to use a different container on test #1 than you do on test #2? This is where JP's implementation of custom attributes really shines. Throw which ever attribute you want onto the test you're currently working with and voila, container configured. It does exactly what you need it to and it doesn't clutter up your tests with a bunch of setup code.
The problem with JP's implementation? Well, if you're using MbUnit, there isn't one. I looked at nUnit and there doesn't appear to be a way to achieve the same attribute inheritance option. The biggest reason is that the TestAttribute class is sealed up and inherits directly from System.Attribute which stops you from being able to hook the test execution prior to it starting. As a result, the only way that I can get test by test level configuration of my container is to embed the container loading in the tests themselves. Not a great solution, but one I'll probably end up having to use until I have a second or third reason to convince people to make the move to a different testing framework.
Always wrap up your third parties
Today I was working through some code refactoring when I came across my implementation of the Castle Windsor container exposed off of the Global.asax file. I had put it there because I needed to get it initialized during Application_Start and I wanted to put it somewhere that was easy to get at from the rest of the code. When I exposed it off of Application_Start, I did it as a property of type IWindsorContainer.
In the end I needed to be able use a different implementation of a container. Since I'm not in control of the IWindsorContainer interface, I didn't feel comfortable creating a new implementation based on that. Instead I created my own interface and implementation. The implementation for the main production container is just an adapter wrapping the IWindsorContainer. It looked something like this:
public class WindsorDependencContainer:IDependencyContainer { private readonly IWindsorContainer _windsorContainer; public WindsorDependencContainer(IWindsorContainer windsorContainer) { _windsorContainer = windsorContainer; } public Interface ResolveFor<Interface>() { return _windsorContainer.Resolve<Interface>(); } }
Because I'm using my own interface I could go ahead and implement another simple container and make use of it. Maybe something like this:
public class SimpleDependencyContainer:IDependencyContainer { private IDictionary<Type, object> _dependencies; public SimpleDependencyContainer():this(new Dictionary<Type, object>()) { } public SimpleDependencyContainer(IDictionary<Type, object> dependencies) { _dependencies = dependencies; } public Interface ResolveFor<Interface>() { return (Interface) _dependencies[typeof (Interface)]; } }
I went from having my code being tied to the Windsor implementation of an IoC container to having my application be able to implement any container that I desire. I've preached and preached that you should wrap everything that you're implementing from a third party. For some reason I forgot this time and it damn near bit me in the ass.
Why this was important to me is the subject of a future blog post.
Training -- Nothin' But .NET 3.5
As you've probably already read on JP's blog, I'm going to be doing some training through him starting this year. The first course that I've been designing is a take on his Nothin' But series and style of courses. Semi-coordinated with the official launch of Visual Studio 2008 and .NET 3.5, I've put together a course called Nothin' But .NET 3.5.
The course will center around the new language and IDE features that were released with Visual Studio 2008 and .NET 3.5, plus some time with the ASP.NET MVC framework as well. As if that wasn't enough to keep you busy learning for the week, all these things will be looked at and worked on with a focus on good OO design. Concepts and practices like SRP, SoC, Dependency Injection, IoC and TDD will feature prominently beside the new framework.
Like I said, I'm going to be putting the course on in the same style as JP has been doing his. You'll get 5 days of in depth, hands on experience with v3.5 of the .NET Framework. The days will be a minimum of 8 hours, but will go on for as long as the students want them to. Hot lunches and dinners, if required, will be provided everyday. Exact course details are going to be published in the next few days. Watch here for that.
If anyone is interested in taking the course, shoot me an email at donald.belcham@gmail.com The plan is to take the course on the road, so no matter where you're at, if you're interested let me know and I'll see if there's enough interest to bring it near you.
I'm really looking forward to what the coming year will bring. Hopefully I see some of you in these courses.
ReSharper 3.1 gotcha with .NET 3.5
My current project is working in .NET 3.5 and, of course, I've pimped my IDE with some ReSharper goodness. I've noticed one thing that is making me itch for the day that ReSharper v4 comes out. If you are using an extension method in your code you need to have a "using" statement for it's namespace or else the code won't compile. When ReSharper analyzes the "using" statements it doesn't pick up that this namespace is being used since it has no idea what extension methods are. As a result the "using" statement is greyed out and if you use Ctrl-Alt-F to reformat and clean you code, it will be removed. Of course you code doesn't compile then.
To stop this from happening the best thing that I've come up with is to turn off the "using" optimization feature in Ctrl-Alt-F by unchecking the first checkbox on the window. The problem with that is that I now don't clean up any of the unused "using" statements in any of my files. It could be better (I'm guessing ReSharper 4) will take care of this, but I figure that the project is going to go on past the release of ReSharper v4 so I'll just go back and clean up the dead "using" statements at that time.
Update:
Paul Stovell left me a comment that there are a couple of options natively in Visual Studio 2008 that will help me out. I First tried binding a key stroke (Shift-Alt-F was nice and close to the ReSharper Ctrl-Alt-F) to Edit.RemoveUnusedUsings and voila....problem solved. I now leave you to wonder if Paul Stovell is the Thunder From Down Under....
Was it a failure?
The last contract that I finished up was very trying on many fronts. One of the things that they sold me on during the hiring process was the fact that they were following Agile practices. On arrival it was pretty apparent to me that their definition of Agile was quite different from mine. One of the tasks that I took on during the year I was there was to try to bring more agility to the process.
During the year I fought to try to get the test team into the iterative process so that we could say that a feature was complete once both development and testing were complete. On that front I failed in glorious fashion. I also worked hard to get the results of each iteration to be released to the acceptance testers (product owners who were power users). I was never able to get the delivery and our iterations to synch up.
Looking back, I'd suggest that these were the two biggest things that make me consider my attempts at making the project more agile a failure. There were numerous reasons to why I never managed to make those things happen, none of which I'm going to talk about here. Looking at it now, what I was saying was that success (or agility) had only been achieved if all things were implemented successfully.
I've been watching a great video of a presentation on Tuning Scrum by Jeff Sutherland that is available on Google Videos. It's worth watching the whole presentation, but the thing that caught my eye is near the end of it. Agility is incremental. In the presentation they talk about Type A, B and C Scrum. There's a whole matrix explaining what each type of Scrum requires to have been considered implemented. Type A requires that the Development Team be engaged, but nobody else. Type A also requires that releases are occurring every 4 to 6 iterations. It also suggests that new feature requests take 4 - 6 months to be delivered.
If I use those there metrics, I was able to get our project to meet the requirements for Type A scrum. In my mind I was trying to get to Type C, which has much more rigorous requirements to be considered implemented (which we definitely didn't meet).
So maybe the time that I spent working on the project's methodology during that contract wasn't a complete waste. We managed to get an engaged Development Team, release to acceptance testers on a much more frequent basis than the team before and we decreased the amount of time that the client had to wait to see a new feature. None happened to the extent that met my aggressive metrics, but they moved in the right direction.
Versioning Applications Using nAnt and CruiseControl.NET
During my presentation at DevTeach in Vancouver, I showed a technique for setting up versioning of your applications using nAnt and CruiseControl.NET. Since then I've had a couple of people ask me if I could post something on this as they missed getting notes on it when they were in Vancouver. Here we go.
Versioning of .NET applications is done through the values that are in the AssemblyInfo.cs file. When you create a new project in Visual Studio that file is created for you. In it there is a bunch of assembly metadata information. AssemblyVersion, AssemblyCompany, AssemblyTitle and a number of others are in there. By default the AssemblyVersion value is set to 1.0.0.0. Regardless of the number of times that you compile the application, the version will stay the same since this value isn't automatically incremented.
If we're working in a Continuous Integration environment we have the capability to incrementally version the assemblies created during each integration phase. There are two components to accomplishing this. The first piece of the puzzle is getting CruiseControl.Net to provide an automatically incrementing value. The second piece is using nAnt to create an customized version of the AssemblyInfo.cs file that can then be compiled into the assembly.
CruiseControl.Net takes care of automatically incrementing a value for you. By default CCNet is using the Default Labeller which starts at 0 and increments by one for each successful integration. This could be used to version your application, but in the end your application may have a build label of 843, which doesn't really conform to the industry standard for version format (1.0.0.0). The Default Labeller has a prefix node that will allow you to prefix the automatically incrementing build number. If you set the prefix node to 2.0.0. and the last successful build was #569 then the labeller will create a label value 2.0.0.569.
One of the other labeller blocks that I regularly use is the Iteration Labeller. The Iteration Labeller works much like the Default Labeller. The Iteration Labeller is most useful if you are working on an iterative release schedule with a fixed and consistent duration for each iteration. Configuring the Iteration Labeller requires you to set the duration (say 14 if you are releasing every 2 weeks) and the release start date (what was the first day of the first iteration). Like the Default Labeller, you also provide a prefix, but only for the first two values in the four part build label (2.0. -- always remember the last "." for it to work correctly). CruiseControl.Net will take care of automatically incrementing the last two values for you. As the iteration duration passes, the third value in the build label will increment by one (from 2.0.0.x to 2.0.1.x) and the final value in the build label will reset to zero (from 2.0.0.59 to 2.0.1.0). The great thing about this labeller is that you will be able to look at the version number of an assembly and immediately associate it with an iteration release, and probably the feature set that should have been included in it or the defects that should have been fixed in it.
You don't have to use one of just these two labellers. There are a number of others that offer different value and may be better suited to your project.
Once you have CCNet configured to create a build label that you're happy with using as a version number, you can move off to nAnt and put that value to use. When you use the nAnt Task within CCNet, some CCNet values are automatically pushed through to the nAnt script being called. One of those values is CCNetLabel. You can use this in nAnt just like any other nAnt property.
One of the nice features in nAnt is the asminfo Task. With it you can create a customized replacement for the default AssemblyInfo.cs file created by Visual Studio. This may look something like this in your nAnt build script.
<asminfo output="CommonAssemblyInfo.cs" language="CSharp"> <imports> <import namespace="System" /> <import namespace="System.Reflection" /> </imports> <attributes> <attribute type="AssemblyVersionAttribute" value="${CCNetLabel}" /> <attribute type="AssemblyCopyrightAttribute" value="Copyright (c) 2008 My Company Inc" /> <attribute type="AssemblyCompanyAttribute" value="My Company Inc." /> <attribute type="AssemblyProductAttribute" value="My Application Name" /> </attributes> </asminfo>
So we've created the custom AssemblyInfo file that we wanted (in this case called CommonAssemblyInfo.cs). Now you need to get this included into your project. In the csc Task in the compilation portion of your nAnt script you will need to make sure to include the generated custom AssemblyInfo file and also exclude the AssemblyInfo files generated automatically by Visual Studio. If you don't exclude the auto generated AssemblyInfo file you will get a error at this compilation point in the nAnt build script.
<csc target="library" output="MyApplication.dll" debug="true"> <sources> <include name="C:\working\MyApplicationSolutionFolder\**\*.cs"/> <exclude name="C:\working\MyApplicationSolutionFolder\**\AssemblyInfo.cs"/> <include name="C:\working\MyApplicationSolutionFolder\CommonAssemblyInfo.cs"/> </sources>
That's all great. You now have your Continuous Integration automatically versioning your application. There's more that you should probably do though.
I'm a huge proponent of having the developers running the exact same nAnt build script locally on their machines. If the developers are doing this I know that the application is repeatedly being executed, as if it were going to production, before it's even getting to the integration server. Developers will be executing the build script through nAnt, not CruiseControl.NET. This will cause problems with the versioning information I showed above. Without CCNet kicking off the build process, none of the values that it pushes into nAnt will be available. For the purpose of this post, that means that we will not have the CCNetLabel when we run the build script from nAnt by itself. This will actually cause an error when we try to run the build script. To avoid that happening we need to make use of the property::exists nAnt Function and a temporary property.
<property name="version" value="0.0.0.0"/>
<if test="${property::exists('CCNetLabel')}"> <property name="version" value="${CCNetLabel}"/> </if>
<asminfo output="CommonAssemblyInfo.cs" language="CSharp"> <imports> <import namespace="System" /> <import namespace="System.Reflection" /> </imports> <attributes> <attribute type="AssemblyVersionAttribute" value="${version}" /> <attribute type="AssemblyCopyrightAttribute" value="Copyright (c) 2008 My Company Inc." /> <attribute type="AssemblyCompanyAttribute" value="My Company Inc." /> <attribute type="AssemblyProductAttribute" value="My Application Name" /> </attributes> </asminfo>
What that block of xml prior to the asminfo task is doing is to ensure that there is a version number for the application even if the CCNetLabel is not available (the developer is running the build script on their local machine). The first step is to setup the temporary property 'version' and setting it to a default value. The next thing we setup is the 'if' block that checks to see if the CCNetLabel property is available. When it is (if the build script is running because CCNet kicked it off), the 'version' property is reassigned the value that was passed in using the CCNetLabel property. The final step is to use the 'version' property when we create the custom CommonAssemblyInfo.cs file.
One of the things that I like about using the 0.0.0.0 default value is that you will always know that you have a rouge compile and deploy if you find a file with that version in your production or test environment. Like using the Iteration Labeller, using a default value provides you with a quick point of reference based on the metadata associated with your application.