Powershell version for Righthand Intel Rapid Storage Technology

by Miha Markič6. June 2013 11:56

Since few guys asked if I'll be releasing new command line utilities for Intel Rapid Storage Technologies I've decided to refresh those old utilities with a fresh Powershell v3 version.

Check out the dedicate page.

Tags:

Tips for Setting Git on Windows for SSH

by Miha Markič20. May 2013 11:34

Last weekend I took some time to configure Git (and Gitolite for easier repository access management) on my Ubuntu server. It was a fun experience for a Linux newbie. Anyway, here are a bunch of things to watch out when configuring Git client on Windows.

If you want to use OpenSSH (SSH that comes with Git)

  1. Always generate public/private key pair using ssh-keygen -r rsa even when using PuTTY. (I initially made a mistake because I used Puttygen).
  2. Set the environment variable HOME=C:\Users\[USERNAME], this variable isn't set by default. SSH looks for private keys in the C:\Users\[USERNAME]\.ssh folder. Not sure whether there are options to instruct it to looks elsewhere.
  3. Use default key name which is id_rsa. From what I can tell SSH looks for identity and id_rsa names (no suffixes).

When using PuTTY (an alternative to OpenSSH)

  1. Set environment variable GIT_SSH = C:\Program Files (x86)\PuTTY\plink.exe (path valid for x64 system). This variable will tell Git what library to use for SSH communication.
  2. Run Pageant (part of PuTTY distribution) which will handle your private keys. Added bonus is that you don't have to repeat passphrase to private key when accessing it (granted you set the passphrase when you created the key - always a good practice).

Other tip would include trying the SSH connection to the server first using verbose output: SSH -vvv [USERONSERVER]@[SERVER]. This output helps to a certain extent.

Tags: , , , , , ,

Making JSON data strong typed with TypeScript and CodeSmith

by Miha Markič3. April 2013 12:20

The situation

Imagine a scenario where you have a JSON service that returns data and you'd like to have it strongly typed on javascript powered client side.

Let's say there is an ASP.NET MVC application that goes by the name MvcApplication33 (yes, the 33rd in a row of test applications) . There are two models in there in two files under Models folder:

namespace MvcApplication33.Models
{
    public class Customer
    {
        public string Name { get; set; }
        public string Surname { get; set; }
        public int Age { get; set; }
        public Order[] Orders { get; set; }
    }
}

namespace MvcApplication33.Models
{
    public class Order
    {
        public double Amount { get; set; }
        public string Category { get; set; }
        public bool IsActive { get; set; }
    }
}

There is also a ApiController derived CustomersController like:

namespace MvcApplication33.Controllers
{
    public class CustomersController: ApiController
    {
        public IEnumerable<Customer> GetCustomers()
        {
            return new Customer[]{ new Customer
            {
                Name = "Tubo",
                Age = 22,
                Orders = new[]{ new Order { Amount = 54, IsActive = true, Category = "waste"} }
            }};
        }
    }
}

It simply returns an Customer array consisting of a single customer with a single order. The javascript, well jQuery, code that gets this data would look like:

$(function () {
        $.getJSON("/api/customers", null, function (d) {
            var jsonCustomer = d;
        });
    });

The problem

While the code above works there is a drawback (mostly for people coming from strong typed languages): on the client side there is no metadata information at design time whatsoever. One is left with dynamic constructs. TypeScript addresses this with interfaces. One could write matching TypeScript interfaces for C# types like:

interface ICustomer {
    Name: string;
    Surname: string;
    Age: number;
    Orders: IOrder[];
}
interface IOrder {
    Amount: number;
    Category: string;
    IsActive: bool;
}

and then rewrite retrieval like

$(function () {
    $.getJSON("/api/customers", null,
        d =>
        {
            var customer = <ICustomer[]>d;
        });
});

This way customer becomes an instance of a type that implements ICustomer which means properties are now strong typed and intellisense works. Of course this is only TypeScript design time sugar which doesn't reflect in generated javascript code but that's enough to prevent a zillion of typing and other "easy to catch at design time" errors.

There is one problem though. Typing interfaces is boring, error prone and there are synchronization issues between manually typed ones and their C# originals.

The solution

There is already all metadata information for our interfaces in C# code. Hence I created a CodeSmith template that automatically creates TypeScript interfaces based on their C# originals by parsing C# code. When C# code changes the template can be rećrun to recreate interfaces. Almost one click error-less operation.

Here is how it works: the template parses all C# files in a given folder and subfolders and generates matching TypeScript interfaces with corresponding namesapaces (using TypeScript modules). The template output for the given problem would look like:

// Autogenerated using CodeSmith and JsonGenerator
// © Righthand, 2013
module MvcApplication33.Models {
export interface ICustomer {
    Name: string;
    Surname: string;
    Age: number;
    Orders: IOrder[];
}
export interface IOrder {
    Amount: number;
    Category: string;
    IsActive: bool;
}

    export module Subform {
        export interface ISubclass {
            Tubo: bool;
        }

    }
}

Just for testing nested interfaces there is also interface ISubclass from original file located in Models subfolder named (Subform).

 

The TypeScript file that uses the mentioned autogenerated interfaces should reference autogenerated interfaces file using <reference> directive. Here is a sample TypeScript test:

/// <reference path="typings/jquery/jquery.d.ts" />
/// <reference path="../CodeSmith/JsonInterfaces.ts" />
module KnockoutTest {
    $(function () {
        $.getJSON("/api/customers", null,
            d =>
            {
                var customers = <MvcApplication33.Models.ICustomer[]>d;
                alert(customer[0].Name);
            });
    });
}

How to

The template comes in two parts. An actual CodeSmith template (JsonInterfaces.cst) and a .net assembly (KnockoutGenerator.Extractor.Parser.dll - name should give you a hint where all this is going in a next blog post) which is used to extract metadata from C# sources. The assembly code could be a part of CodeSmith template but it is easier to develop (read: debug) code within Visual Studio. The assembly in turn uses NRefactory (free C# parser and much more) which (v4.x) is a part of CodeSmith, so no additional files required.

Perhaps the easiest way to use the template is to include these two files in a project and use CodeSmith from within Visual Studio. The template requires a single property: FolderWithModels which is rather self explanatory. Excerpts from attached sample project:

The CodeSmith project content located in Project1.csp:

<?xml version="1.0" encoding="utf-8"?>
<codeSmith xmlns="http://www.codesmithtools.com/schema/csp.xsd">
  <propertySets>
    <propertySet name="JsonInterfaces" output="JsonInterfaces.ts" template="JsonInterfaces.cst">
      <property name="FolderWithModels">..\Models</property>
    </propertySet>
  </propertySets>
</codeSmith>

The project structure. I tend to put CodeSmith related stuff in CodeSmith folder. Feel free to arrange it otherwise.

folder structure

Right click on Project1.csp and Generate Outputs should (re)generate JsonInterfaces.ts. Open the output file and if Web Essentials and TypeScript are installed it should (re)generate final JavaScript file.

The project itself won't show any meaningful output (for now) but you can use JSON output in a strongly typed way.

Have fun and read next post which will talk about further enhancements for knockoutjs.

You can download my sample project (without NuGet packages, just sources) which includes everything you need (subfolder CodeSmith).

MvcApplication33.zip (566.78 kb)

NOTE: The CodeSmith template could be rewritten to T-4 (using the same support assembly) however, one should make sure that NRefactory assemblies are there otherwise parser won't work.

Tags: , , ,

ASP.Net | CodeSmith | Visual Studio

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

by Miha Markič30. March 2013 17:35

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)

Tags:

How to compile MvvmCross v3 sources

by Miha Markič13. March 2013 11:22

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.

Tags:

.net | Mono For Android

No more forums at rthand

by Miha Markič20. February 2013 10:08

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!

Tags:

Announcement

Blog engine’s e-mail problems

by Miha Markič6. February 2013 15:11

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.

Tags:

Free Succinctly book series from Syncfusion

by Miha Markič16. January 2013 10:43

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.

Tags:

Book Review | Development

An exotic DevEx’ ReportDesigner breaking change in 12.2

by Miha Markič9. January 2013 18:59

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.

Tags: ,

.net | DevExpress

Just developing for Windows 8 Store gives your privacy a funeral

by Miha Markič2. November 2012 11:35

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.

Tags: ,

.net | Android | Development | MonoForAndroid

Miha Markic

About me
Righthand
 
Microsoft MVP
 
Developer Express' MVP
INETA Country Leader for Slovenia
INETA Country Leader for Slovenia

Slovene Developer Users Group Lead
Friends of Red-Gate
LLBLGenPro Partner

Miha currently works as a free lance consultant and software developer specialized in .net area.
He graduated in Computer and information science at the University of Ljubljana, Slovenia. He has accumulated experience in various programming languages such as Java, Visual Basic 3-6 (MCP), Visual C++, Delphi, C# and VB.Net through years.
He has experience in practically all (technical) stages of project development, including planning, framework development, user interface, business processes, as well as testing and documenting. He has worked on big and small projects in Slovenia and abroad (e.g. participated in completing level 3 IS for the Nucor steel plant, Hertford, USA).
Currently he enjoys programming in .net environment using C#. Since 2000 he has been active in Developer Express' DX Squad and has been ECDL trainer and tester. He also gives lectures on conferences and other events in Slovenia.

Month List

Tag cloud

Most comments

Manav Manav
1 comments
us United States
Richard Richard
1 comments
us United States
Mikael Falkvidd Mikael Falkvidd
1 comments
se Sweden

RecentComments

Comment RSS