Defining custom regions in TypeScript files and preserving their content during CodeSmith template based code generation

I am looking to do some TypeScript code generation with CodeSmith and I’d like to use PreserveMerge merging strategy(preserve merge preserves your custom code within generated code between regenerations). CodeSmith’s merging mechanism is powerful and flexible (besides preserve it supports insert merge strategy as well. But if you feel constrained then feel free to create your own merging strategy). Out of the box it supports C#, VB.NET, XML and T-SQL start region and end region notation. This is a problem for TypeScript because, it can’t use any of those with TypeScript files hence I have to define my own start and end region keywords.

So I came up with

/// #region [Name]

and

/// #endregion

notations – TypeScript will ignore them (as comments) and they are explicit enough. Nothing Earth shattering but they should do the job for me.

Definining new region keywords for CodeSmith

Now I have to update CodeSmith with my these new TypeScript region keywords.

CodeSmith uses regular expressions for searching region keywords. They are defined in registry under the key HKEY_CURRENT_USER\Software\CodeSmith\<VERSION>\LanguageRegionDefinition. Here is a C# definition

image

The definition consists of LanguageKeys, RegionStartRegex and RegionEndRegex. Pretty much self-explanatory.

Here is my TypeScript entry under next available number 4 (also attached to this post):

LanguageKeys: Typescript|TS
RegionStartRegex: ^[ \t]*///[ \t]*\#region(?:[ \t]*(?<name>[^\r\n]*))?[ \t]*\r?\n
RegionEndRegex: ^[ \t]*///[ \t]*\#endregion[ \t]*\r?\n

Creating the node 4 as a sibling to other region definitions does the trick. Note: LanguageKeys is important when you set the merge strategy (you can use any of strings that are pipe delimited: either TypeScript or TS in my case).

Using regions in TypeScript generated code

Let’s create a very simple proof of concept (the project is attached to this post).

First create new console project and then add a CodeSmith template for TypeScript code. As a TargetLanguage you could put "TypeScript” even though CodeSmith doesn’t really know how to syntax color it. It is just a hint for CodeSmith. Place one or more region delimiters within template (mine is really simple one, just to show the concept), here is my template:

<%@ Template Language="C#" TargetLanguage="TypeScript" Debug="False" %>

module RegionTest {
  function tubo(){
    var i = 5;
    /// #region Test
    /// #endregion
  }
}

Add CodeSmith project file and add the above template as an output. In the Edit Output settings set the proper output file name (test.ts in my case), Merge type as “PreserveRegions” and Initialization string as “RegionNameRegex=.*;” or “RegionNameRegex=.*;Language=TypeScript;” if you didn’t set it as TargetLanguage (it defaults to template’s TargetLanguage when not defined). RegionNameRegex gives you a chance to use only selected region names for preserve strategy – in my case any name or no name will do. Below are my Edit Output settings.

image

Generate the code, the output content should appear just like the template definition since there is no real code generation.

Add custom code within the Test region in generated test.ts file (not in template), like:

/// #region Test
alert ("wow, this is really a persistent alert");
/// #endregion

And generate the code once more. If everything is in place the new output should have persisted the custom code of the Test region.

 

Conclusion

To enable CodeSmith’s PreserveRegion merging strategy in an unsuported TypeScript language I had to add a registry key and that’s it. The simplicity of making a language supported in this case shows the CodeSmith flexibility and power and the CodeSmith’s use or registry shows bad practice Smile they should really use files instead of registry (hint).

TestPreserve.zip (20.95 kb)

typescrip-regions.reg (614.00 bytes)

How to compile MvvmCross v3 sources

As you well know, or you might not, MvvmCross is a cross platform MVVM framework supporting many platforms, such as Android and iOS (both through Xamarin), WPF, WinRT, WP7. Feature worth drooling.

Now, AFAIK there are two versions available. v2 (aka vNext) which is supposedly stable and v3 which is work in progress but holds many improvements. Here is how to get v3 sources compiled for Android (I didn’t test others) in case you run into problems like me.

  1. head to Github repository for v3 branch (optionally)
  2. use git clone –b v3 git://github.com/slodge/MvvmCross.git do fetch sources
  3. open MvvmCross_All.sln solution (using Visual Studio 2012) which references all projects for all platforms. If you don’t have Touch support (or others) Visual Studio will let you know. You can safely ignore those warnings.
  4. build solution. If it does consider yourself lucky, otherwise continue reading.
  5. If you get something like

Error 172 Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'. Perhaps it doesn't exist in the Mono for Android profile?
File name: 'Newtonsoft.Json.dll'

then there is a problem with build process. My guess is that it happens because portable class libraries, which Newtonsoft.Json.dll is, aren’t officially supported by Xamarin. Yet.

The workaround is to get Newtonsoft.Json sources (use PCL csproj version), include the project into solution and replace the reference in Plugins\Cirrious\Json\Cirrious.MvvmCross.Plugins.Json project with the Newtonsof.Json project itself.

Now you can run samples, at least I did – tested with Samples\Tutorial\Tutorial.UI.Droid.

There is another build error you might encounter (in general for Xamarin.Android). Sometimes the build process yields a ton of senseless errors (can’t find classes, interfaces, etc.) even though the code should compile. Try building again – most of the times it builds without errors the second time.

If you are interested into MvvmCross project make sure you read Stuart’s blog (creator of MvvmCross).

I have to test it a bit now, so more blog posts on the topic might follow.

Have fun with MVVM everywhere.

No more forums at rthand

For few of you who used my forums: I’ve decided to shut down my forums at forums.rthand.com. Not much traffic and constant spamming/attacks weren’t worth my time. I think my time will be better spent in my projects.

You can still contact me through many channels, such as this blog’s Contact page (which should be working lately), twitter (@mihamarkic) and so on.

Thanks everybody that contributed to forums!

Blog engine’s e-mail problems

For some reason I didn’t notice that my blog engine wasn’t properly notifying me of your comments sent through Contact page and thus I was actually unaware of any comment sent.

Hence I apologize to everybody that contacted me and got no response.

I am pretty sure the notification system is working properly now.

Free Succinctly book series from Syncfusion

Lately Syncfusion started producing e-books grouped under Succinctly series. The books are for developers on (mostly) Microsoft platform and are a free download albeit registration is required. I’ve peeked into few of them and I have to say I like them.

They won’t replace commercial n-hundred pages long developer books though but they provide you an introduction, the basics of the topic and serve as quick reference. So it is worth checking them out and kudos to Syncfusion.

An exotic DevEx’ ReportDesigner breaking change in 12.2

If you ever customized (excellent) DevExpress ReportDesigner you might have used this line of code to obtain a reference to IDataSourceCollectionProvider within ReportDesigner class which allows to access field list:

IDataSourceCollectionProvider dataSourceCollectionProvider = 
    designerHost.GetDesigner(designerHost.RootComponent) 
    as IDataSourceCollectionProvider;

This code worked well in 12.1 and perhaps in earlier 12.2 versions but it certainly won’t work in 12.2.5. The bad part is that it fails in runtime, while it still compiles perfectly. At least it fails consistently – always. The reason is that access to various services (IDataSourceCollectionProvider is one of them) is now through ReportDesigner.GetService(Type serviceType) method. Replacing the part above with the one below does the trick:

IDataSourceCollectionProvider dataSourceCollectionProvider = 
    (IDataSourceCollectionProvider)designerHost.GetService(
        typeof(IDataSourceCollectionProvider)
    );

The new is more readable and it could be even better if it used generics. I’d certainly consider this declaration instead:

T GetService<T>()
  where T: class
{
   ...
}

which would yield even more readable assignment:

IDataSourceCollectionProvider dataSourceCollectionProvider = 
    designerHost.GetService<IDataSourceCollectionProvider>();

There you have the fix.

Just developing for Windows 8 Store gives your privacy a funeral

I was poking around with excellent MonoGame framework by creating a simple game, or better, starting to create a simple game. So far I’ve spent a day to build some infrastructure from scratch and I am able to show a main screen with simple menu items. Nothing really ground-breaking.

The aspect I am most interested right now is cross platform development with MonoGame. Hence my simple game is built with cross platform support from beginning. Main development target is Windows 7 x64 because it is the easiest to debug the application on. I’ve ported the game successfully to Android as well by using Mono For Android – tested on both emulator and my Google Nexus phone. Port means just creating a bootstraper (an Android app that launches the game within an activity) and linking the sources to Mono For Android projects (here Project Linker comes to great help, though shame that Microsoft Patterns And Practices team seemingly abandoned it).

 

 

Windows Phone 8 emulator requirements are insane

Next I wanted to port it to Windows Phone 8 since its SDK is fresh from the oven and MonoGame supports it (not sure at what stage the support is). However, Windows Phone 8 SDK emulator requirements are just too much: Visual Studio 2012, Windows 8 Pro, 4GB RAM, and CPU with SLAT support to run the emulator which in turn runs on Hyper-V. I don’t have a Windows Phone 8 device so I wanted to give the emulator a test run. I have Windows 8 Pro on my laptop but, albeit perfectly functional, the CPU doesn’t feature SLAT. SLAT is required by Hyper-V on client versions of Windows 8. The interesting fact is that VMWare Workstation runs perfectly well without or with SLAT. Be also aware that VMWare Workstation and Hyper-V on Windows 8 won't coexist peacefully - Workstation will work only when Hyper-V feature isn't present. The bottom line is that the Windows Phone 8 emulator won’t run on my laptop. I could run it on my workstation but I haven’t migrated to Windows 8 at this time.

Windows 8 development license isn’t something for privacy consciousness

Next I wanted to run a Metro aka Windows Store Apps version of my game. Those should run just fine on my laptop. I started by creating a new Windows Store application and Visual Studio 2012 immediately notified me that I need a developer license for Windows 8 which is free. But reading its privacy statement made me wonder.


When you request a developer license, Microsoft collects information about your PC and the apps installed on it. This information includes your PC’s name, manufacturer, and model; your IP address; a unique identifier generated based on your PC’s hardware configuration; and the edition of Windows you’re using.
….
Microsoft may access or disclose information about you, including the content of your communications, in order to: (a) comply with the law or respond to lawful requests or legal process; (b) protect the rights or property of Microsoft or our customers, including the enforcement of our agreements or policies governing your use of the services; or (c) act on a good faith belief that such access or disclosure is necessary to protect the personal safety of Microsoft employees, customers, or the public. We may also disclose personal information as part of a corporate transaction such as a merger or sale of assets.

Remember, I wanted to test my game locally. And for that I’d need to send all sort of data to Microsoft? What the heck? Furthermore those legal obligations are really flexible. Not that I have anything to hide or against Microsoft but still why do I have to disclose installed applications on my computer and such? Note that I wouldn’t send my data to any company just to test an application on the local machine. So, for the time being, I will skip Windows Store App version as well.

Progress so far:

  • Windows Desktop [checked]
  • Android [checked]
  • Windows Phone 8 [unknown]
  • Windows Store App [unknown]
  • Windows Phone 7 [unknown,soon]

There is only one platform left to try – Windows Phone 7 where I don’t foresee any problems, just didn’t have time yet.

Getting proper OpenGL driver for older AMD(ex. ATI) graphics cards on Windows 8

I have a not so new laptop that features ATI Radeon HD 3650 Mobility graphics cards. Which is quite fine for the usual tasks. According to AMD website it features OpenGL 3.2 which is, again, good enough. Nothing spectacular but fine.

Lately I’ve upgraded it to a SSD disk and at the same time I did a fresh Windows 8 install (previously it was Windows 7). Everything worked out very well. The laptop is usable again and quite fast now. Yesterday I tried to experiment with MonoGame, an open source implementation of, now legacy, XNA Framework – the framework that was supposed to run everywhere but Microsoft ditched it for some reason. Anyway, I’ve tried to run a sample MonoGame application and immediately faced a problem. First it was throwing an exception that OpenAL.dll is missing. Odd. I’ve found a standalone installation for OpenAL but the I run into another, more descriptive problem, something like: can’t find entry point for ‘glBindFramebuffer’ in OpenGL32.dll. That basically says that I had a pre-OpenGL 2.0 installed (MonoGame uses OpenTK which in turn requires minimum 2.0 version of OpenGL). How is that possible?

From what I understand the situation is that AMD isn’t supporting the Radeon Mobility HD 3xxx with Windows 8 and hence it doesn’t provide OpenGL drivers. So everything falls back to Microsoft provided OpenGL 1.1. That is nicely shown using GPU Caps Viewer application. This is ever more surprising because we had proper OpenGL drivers for it under Windows 7. If it was a desktop machine I’d consider changing the graphics card but that’s just not possible on the laptop. And I wasn’t quite happy to buy a newer laptop just for that, even more so because my laptop is doing just fine.

The solution

The solution is to install the latest drivers for Windows 7 manually. It is actually quick, easy and it works. You’ll find the procedure in Make Your Old Graphics Drivers Work in Windows 8article on Lockergnome. The only differences from article are that just right clicking on INF file doesn’t work nor the INF file is named exactly like the one in the article – it has higher number, probably because it is a newer one. Instead of the right click->install, which didn’t work, I had to go to Computer->right click->Manage->Device Manager->Display adapters->ATI Mobility Radeon HD 3650->right click->Properties->Driver->Update Driver->Browser my computer for driver software->Let me pick from a list of device drivers on my computer->Select proper INF file.

And voila – now I have OpenGL 3.3 support and MonoGame runs like a charm. Happy OpenGLing!

SSD’s firmware version might be really important

I had a good old Asus EEE 1005HA netbook running Windows 7 just fine, albeit slow. The best way of speed it up was to upgrade it to a SSD. The I/O difference should speed it up considerably as the original disk was a 5400rpm one. The SSD prices are low enough, too.

So I went and bought a small, reasonably priced OCZ Vertex Plush 60GB SSD. The disk replacement process isn’t a very simple one because the disk is buried in the guts of the netbook. See one and two (there are more videos, just google them) and be careful with the connectors as they are really fragile.

I’ve replaced the disk, put everything back together and then booted Windows 8 x86 from an USB stick (the easiest way to burn an ISO to an USB stick is to use Windows 7 USB/DVD Download tool). Everything went smooth until Windows finalized the setup. Bam. I’ve got an “Windows couldn’t configure hardware on this device” error (very helpful description, isn’t it). After restart the computer didn’t boot but rather complained about missing boot disk. Huh? That’s odd and when Windows install fails it has to do with hardware issues usually – this time it hinted some sort of problems related to the SSD. Perhaps the problem lies in the Intel Atom CPU or something other on my netbook. Hence I’ve tried installing Windows 7 x86 as I knew it works. Bam. The same error. Changing BIOS settings didn’t help either. Same error over and over again. I’ve also got odd errors during partition management. BTW I’d really like to know which genius at Microsoft thought of requiring the Windows license key before OS is installed (yes, yes, you have to retype it each try you make, very annoying in such cases). Just for fun I tried installing Ubuntu and, surprisingly, I had no problems and everything was really smooth. At this point I was tempted to leave it with Ubuntu but I had other requirements and had to have Windows.

Then I started googling around if somebody experienced similar problem and after a while I’ve come to a forum thread where they mentioned very faulty OCZ Vertex Plus firmware. According to that thread older (than the latest 3.55) firmware versions have fatal issues with Windows. Only the latest and newest 3.55 should work. Coming from HDD world I never thought that a disk firmware could create such havoc but it fitted the description of my problems. Note that there is no easy way to check the disk’s firmware version without the OS installed (and even then). Anyway, there is an ISO you have to burn to a CD and boot computer from there (beforehand make sure the SSD is in IDE, not AHCI mode). The ISO is linux based and you’d need an utility to burn it to USB stick (netbooks don’t have CD drives usually). Free UNetbootin does the work just fine.

Once I’ve booted from firmware upgrade USB stick I discovered that my SSD was running firmware version 3.50. Bingo. Update went smoothly and after yet another Windows 8 reinstall everything worked as it should.

Sometimes (Visual Studio) error messages are just misleading

Take into account this code

Task.Factory.StartNew(
    () =>
    {
        throw new Exception();
    }).
    ContinueWith(
        t =>
        {
        },
    TaskScheduler.FromCurrentSynchronizationContext);

Which results in following error:

error CS1593: Delegate 'System.Action<System.Threading.Tasks.Task,object>' does not take 1 arguments

If I use an overload that takes TaskContinuationOptions.OnlyOnFaulted instead of TaskScheduler.FromCurrentSynchronizationContext it just works. There are two overloads (among twenty of them) of ContinueWith:

public Task ContinueWith(Action<Task> continuationAction, TaskContinuationOptions continuationOptions);
public Task ContinueWith(Action<Task> continuationAction, TaskScheduler scheduler);

So, why does the later work and the former doesn’t? Can you guess without reading on?

The explanation is really simple - TaskScheduler.FromCurrentSynchronizationContext is not a property but a method and thus it should be used like TaskScheduler.FromCurrentSynchronizationContext(). Once brackets are in place it works. Rookie mistake.

However the C# compiler’s error message is misleading in this case. Instead of reporting that FromCurrentSynchronizationContext is a method and not a property it yields “can’t find proper overloaded method”. At least it could yield both errors.