At the end of the last post on this subject I had got to a point where I was successfully casting some examples, but the solution left a bit to be desired. I was trying to come up with some real examples where I could test this it all out, but I was finding nothing. I came to the inescapable conclusion that I would never use this code (oh well, it was a nice intellectual exercise…) because I just don’t work that way.
As I often tell my team, try to use the best tool for the job, so when I work with .NET objects I tend to work in C# using Visual Studio. NAV is a hammer, but not everything is a nail. I think the NAV world has often tried to be the all-in-one product but Microsoft are moving in a different direction now, and we should probably follow (e.g. no more investment on CRM inside NAV – instead focussing on integration, or just look at the Windows 10 model).
I try and keep a clear border (API) between C/AL and C# but of course you know this does come with some downsides/challenges, i.e. two different development environments, deployment of DLLs, debugging challenges, etc…
I found a few new(ish) .NET features Anonymous Methods, the Dynamic type and Dynamic Object and Lambda Expressions including the Convert Expression that seems like it will be able to do what we want. However all of these features rely quite heavily on C# syntax and getting them to work from NAV looked like it would involve quite a lot of scaffolding and Reflection to get to the appropriate methods.
Then I found is something that tries to treat C# as a scripting language www.csscript.net. I did get the basics of this working in NAV (let me know if you want to see the code) but there were a few small issues:
- You still need to deploy a couple of DLLs (only on Server and Dev machines so not too onerous)
- While I was working out the syntax it threw quite a lot of compile errors where it was very difficult to work out what was going wrong as I couldn’t debug
- My Service Tier on my Dev machine started crashing when I was testing this. I honestly don’t know if this was related or not, but the timing was suspicious.
Finally I found what looked from the title of the article to be exactly what I want: How to programmatically compile code using C# compiler. And reading it I had to laugh, because I recognised it as exactly the same solution that Waldo is using in the post I referenced in my first blog. So I have come full circle 😀
As I said then, I really like this trick – it has a good balance between using actual C# syntax but not having all the extra deployment. There are downsides to it – which I will explore in a future post. One that relates to the Casting problem is it is a LOT of C/AL code to run one line of C# code. For that reason I haven’t built any example code relating to Casting… Sorry… I don’t have unlimited time to play with these things… You’ll just have to trust that it will work (as I do) and try it yourself 😉