Archive for the ‘Exploring the CodeFluent Runtime’ Category

WPF Universal Converter

February 3, 2015 Leave a comment

When you create an application using WPF, you often have to write converters to change one value to the desired type. The .NET Framework already provides some basics converter such as BooleanToVisibilityConverter. These converters are very specifics and not configurable. For example you cannot change the visibility from Collapsed to Hidden. We do not want to spend time to write common converter so we create the UniversalConverter.

The converter is located in the CodeFluent.Runtime.dll or CodeFluent.Runtime.Client.dll. Please use the Nuget Package Manager to add this Package on your project:


Let’s see how to use it!

Basic conversion

    <windows:UniversalConverter x:Key="TypeConversionUniversalConverter" />

<CheckBox IsChecked="{Binding Converter={StaticResource TypeConversionUniversalConverter},
   Mode=OneWay}" DataContext="true"/>
<CheckBox IsChecked="{Binding Converter={StaticResource TypeConversionUniversalConverter}, 
   Mode=OneWay}" DataContext="yes"/>

UniversalConverter uses ConvertUtilities to convert the value to the desired type so string values “true” and “yes” will be converted to the Boolean value “true”.

Switch Case syntax

You can create a list of cases to fit all your needs. For instance:

<windows:UniversalConverter x:Key="BooleanToVisibilityConverter">
        <cfr:UniversalConverterCase Operator="Equal" Value="True" C
  onvertedValue="Visible" />
        <cfr:UniversalConverterCase Operator="Equal" Value="False" 
  ConvertedValue="Collapsed" />

As a C# switch you can set a default value:

<cfr:UniversalConverter x:Key="BooleanToVisibilityConverter" DefaultValue="Visible">
        <cfr:UniversalConverterCase Operator="Equal" Value="False" 
  ConvertedValue="Collapsed" />

There are currently 13 operators:

  • Equal,
  • NotEqual,
  • GreaterThan,
  • GreaterThanOrEqual,
  • LesserThan,
  • LesserThanOrEqual,
  • Between: minimum and maximum value included => [min:max[,
  • StartsWith,
  • EndsWith,
  • Contains,
  • IsType: type match exactly,
  • IsOfType: type or direved types,
  • JavaScript: Yes, you can use JavaScript to evaluate a condition!

And some options:

  • StringComparison
  • Trim
  • Nullify

Here’s a list of examples using different operators:

Check if a string contains NewLine using JavaScript

<cfr:UniversalConverter x:Key="HasMultipleLinesConverter" DefaultValue="False">
        <!--look for a CR or LF in the string string-->
        <cfr:UniversalConverterCase Value="/\r|\n/.exec(Value)!=null" 
  ConvertedValue="True" Operator="Javascript" />

Set error message background and foreground color

<cfr:UniversalConverter x:Key="ErrorTextBackgroundConverter" DefaultValue="Red">
        <cfr:UniversalConverterCase Value="" ConvertedValue="Transparent" />
<cfr:UniversalConverter x:Key="ErrorTextForegroundConverter" DefaultValue="White">
        <cfr:UniversalConverterCase Value="" ConvertedValue="Black" />

Test if a value is over 21

<cfr:UniversalConverter x:Key="IsOver21Converter" DefaultValue="false">
        <cfr:UniversalConverterCase Operator="GreaterThanOrEqual" Value="21" 
  ConvertedValue="true" Options="Convert" />

Is teenager

<cfr:UniversalConverter x:Key="IsTeenagerConverter" DefaultValue="false">
        <cfr:UniversalConverterCase Operator="Between" MinimumValue="13" 
  MaximumValue="20" ConvertedValue="true" Options="Convert" />

Compare types

<cfr:UniversalConverter x:Key="TypeConverter" DefaultValue="false">
        <cfr:UniversalConverterCase Operator="IsType" Value="System.String" 
  ConvertedValue="Type = String" />
        <cfr:UniversalConverterCase Operator="IsType" Value="System.Int32" 
  ConvertedValue="Type = int" />
        <cfr:UniversalConverterCase Operator="IsOfType" 
  Value="BaseClass, MyAssembly" ConvertedValue="Type is of type BaseClass" />

Is empty

<cfr:UniversalConverter x:Key="IsEmptyConverter" DefaultValue="Not empty">
        <cfr:UniversalConverterCase Operator="Equal" Options="Trim, Nullify" 
  ConvertedValue="Empty" />

<TextBox x:Name="TextBox"/>
<TextBlock Text="{Binding ElementName=TextBox, Path=Text, 
  Converter={StaticResource IsEmptyConverter}}" />

If you need more examples, please let us know. Our team will be happy to help you J.

Happy converting,

The R&D team

How to parse a command line?

January 16, 2015 1 comment

The CodeFluent Runtime offers to applications a clean and concise class for manipulating command line arguments and related tasks. Add the nugget package and refers the CommandLineUtilities class.

This class parses your command line arguments, find all parameters starting with – or / and all the values linked. I assumed that a value could be separated from a parameter with a : or a =.

During this article we are going to simulate this execution:

/Program.exe –ProductName:Word /SendEmail=true -amount:10.5


Gets a positioned argument from the command line and convert it to the type of the default value. If the argument is not found or if the value cannot be converted to the expected type, it returns the default value (internally it uses ConvertUtilities).

CommandLineUtilities.GetArgument(name:"ProductName", defaultValue:string.Empty); // -> “Word”
CommandLineUtilities.GetArgument(name:"ProductName", defaultValue:0); // -> 0
CommandLineUtilities.GetArgument(name:"SendEmail", defaultValue:false); // -> True
CommandLineUtilities.GetArgument("amount", double.MaxValue, new CultureInfo("en-US")); // -> 10.5D


Determines whether the argument is specified in the command line.

CommandLineUtilities.HasArgument(name:"ProductName"); // -> True
CommandLineUtilities.HasArgument(name:"debug"); // -> false


List all arguments, the name will be the key.

// -> {{“ ProductName”,”Word”},{“SendEmail”,”true”}}


Gets a value indicating whether help was requested.

// /Progam.exe /HELP
CommandLineUtilities.HelpRequested; // -> True

Happy CLI-ing !

The R&D Team.

Exploring the CodeFluent Runtime: Convert utilities

November 3, 2014 Leave a comment

Today, on the series Exploring the CodeFluent Runtime,  we are going to explore the useful ConvertUtilities class from the CodeFluent.Runtime or CodeFluent.Runtime.Client assembly.

First of all you need to reference the dll in your project and include the directive as follow:

using CodeFluent.Runtime.Utilities;

The CodeFluent.Runtime is a part of the CodeFluent Entities product or you can download the following nuget package.


Returns an instance of type T whose value is equivalent to a specified input object. If an error occurs, a computed default value of type T will be returned.

var convert1 = ConvertUtilities.ChangeType<int>("42");
// –> 42
ConvertUtilities.ChangeType<bool>("yes"); // –> True
ConvertUtilities.ChangeType<bool>("y"); // –> True
ConvertUtilities.ChangeType<bool>("1"); // –> True
ConvertUtilities.ChangeType<CultureInfo>(1036); // –> CultureInfo("fr-fr")
ConvertUtilities.ChangeType("10/30/2014", DateTime.Now, new CultureInfo("en-US")); // –> 'October  30<sup>Th</sup> 2014' fr-FR
ConvertUtilities.ChangeType("Monday, Tuesday Wednesday | 8", DayOfWeek.None); // –>  Monday | Tuesday | Wednesday | Thursday
// Available separators: space, comma, pipe


Sets the current thread culture. Handles integer values as lcid (


Decamelizes the specified text using default decamelization options.

ConvertUtilities.Decamelize("ProductName"); // –> "Product Name"
ConvertUtilities.Decamelize("ProductName", ConvertUtilities.DecamelizeOptions.ForceRestLower); // –> "Product name"


Evaluates the specified expression on a given container object (like Eval in Asp.Net WebForm). In case of an error, the defaultValue parameter will be returned.

ConvertUtilities.Evaluate(DateTime.Now, "TimeOfDay.Hours", typeof(int), defaultValue: 0); // –> 15 (depends of your time<span style="font-family:Wingdings;">J</span> )
ConvertUtilities.Evaluate(DateTime.Now, "TimeOf", typeof(int), defaultValue: 0);  // –> 0
ConvertUtilities.Evaluate(null, "TimeOfDay.Hours", typeof(int), defaultValue:  0); // –> 0 


Concatenates a collection into a string using a separator character. An expression is ran on each object in the collection using ASP.NET DataBinding syntax style.

List<DateTime> collection = new List<DateTime>
   new DateTime(2007, 10, 10),
   new DateTime(2010, 10, 10),
   new DateTime(2014, 10, 10)

ConvertUtilities.ConcatenateCollection(collection, "Year", " - "); //- > "2007 - 2010 - 2014"


Format file size in bytes to the correct unit.

ConvertUtilities.FormatFileSize(399960003); // –>  381,43 MB
ConvertUtilities.FormatFileSize(399960003, null, "N5", new CultureInfo("en-US")); // –> 381.43158 MB


Converts a file extension to the corresponding image format.

ConvertUtilities.FromFileExtension(".jpg"); // –> ImageFormat.Jpeg
ConvertUtilities.FromFileExtension("png"); // –> ImageFormat.Png


Determines whether the specified enum type has the Flags attribute.

Note: you can use Enum.HasFlag with .Net Framework 4.0 and higher.

ConvertUtilities.IsFlagsEnum(typeof(FileOptions)); // –> true 


Gets the maximum value for a given type.

ConvertUtilities.GetMaxValue(typeof(int)); // –> 2147483647 
ConvertUtilities.GetMaxValue(typeof(DateTime));// –> {12/31/9999 23:59:59}


Get a name guaranteed not to be in a given a list of names. This method appends numbers to a preferred name.

List<string> names = new List<string>
ConvertUtilities.GetUniqueName(names, "lionel", StringComparison.InvariantCultureIgnoreCase); // –>  lionel2
ConvertUtilities.GetUniqueName(names, "john", StringComparison.InvariantCultureIgnoreCase); // –> john


Nullifies the specified string.

ConvertUtilities.Nullify("Windows", trim: true);// –> Windows
ConvertUtilities.Nullify("   ", trim: true);// –> Null
ConvertUtilities.Nullify("   ", trim: false);// –> "  "


Removes diacritics (accents) from a text.

ConvertUtilities.RemoveDiacritics("éàèçàöâ"); // –> eaecaoa


Splits a text into a collection of typed objects. Returned objects are automatically converted into the proper type if needed.

ConvertUtilities.SplitToList<int>("25,4,15,42", ',');// –> {25, 4, 15, 42}
ConvertUtilities.SplitToList<long>("255,TTT", ',');  // –>{255, 0} Takes the default values of Type 


Converts a byte array to its hexadecimal string representation.

ConvertUtilities.ToHexa(new byte[] {0x43, 0x6F, 0x64, 0x65});// –> "436F6465"


Converts a string to its hexadecimal dump representation.

ConvertUtilities.ToHexaDump("CodeFluent Entities");
//Offset    00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F  0123456789ABCDEF
//--------  -----------------------------------------------  ----------------
//00000000  43 00 6F 00 64 00 65 00 46 00 6C 00 75 00 65 00  C.o.d.e.F.l.u.e.
//00000010  6E 00 74 00 20 00 45 00 6E 00 74 00 69 00 74 00  n.t. .E.n.t.i.t.
//00000020  69 00 65 00 73 00                                i.e.s.
ConvertUtilities.ToHexaDump(new byte[] {0x43, 0x6F, 0x64, 0x65});
//Offset    00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F  0123456789ABCDEF
//--------  -----------------------------------------------  ----------------
//00000000  43 6F 64 65                                      Code

As you’ve seen in this article, ConvertUtilities can be very useful for .Net developers.

Happy Converting!

The R&D Team

Single Instance Application in .NET

September 10, 2014 Leave a comment

Running a single instance of an application is very easy with CodeFluent Runtime. Add the following nugget package: and use the SingleInstance class:

SingleInstance _singleInstance = new SingleInstance("Unique Name"); 

public MainForm() 

  if (!_singleInstance.WaitForMutext(IntPtr.Zero, IntPtr.Zero)) 


If you want to make an action when the second instance is started, you can handle the windows message “”WM_” + uniqueName”:

protected override void WndProc(ref Message m) 
  if (m.Msg == _singleInstance.Message) 
    // your code
  base.WndProc(ref m); 

SingleInstance class provides a helper to activate a Form, so when the second instance is started, it actually display the form of the first instance:

public partial class MainForm : Form 
  SingleInstance _singleInstance = new SingleInstance("My App"); 

  protected override void WndProc(ref Message m) 
  // Display the window of the first instance 
    _singleInstance.OnWndProc(this, m, true); 
    base.WndProc(ref m); 

You can also force the instance to run, even if one is already running, by using the command line argument “/siForce” or “-siForce”.

$> myapp.exe /siForce 

Happy runtime exploration,

The R&D Team

CommonMark for C# using CodeFluent Runtime

September 5, 2014 Leave a comment

Markdown is a plain text language that can be converted to HTML. This language is well adopted: GitHub, StackOverflow, Reddit, some blogging platforms, and many others.

This language had no specification, so there were many different implementations. A few days ago, Standard Markdown, quickly renamed to Common Markdown, was born. This is the first specification of Markdown. At the same time, the C and JavaScript implementation was released:

At SoftFluent we though JavaScript is great but we are mostly using C# so there is no Common Markdown implementation.

We’re not providing a C# implementation as it would take time to develop and to maintain. Here, we want to show you how to call JavaScript code from C# using the CodeFluent Script Engine from the CodeFluent Runtime.

This is just a sample/preview and not aims to be used in production.

The full (but very short) code is available on GitHub: 

Here’s the main code:

private static readonly string _language = DetermineBestEngine();
private static string DetermineBestEngine()
    // use IE9+'s chakra engine?
    bool useChakra = ScriptEngine.GetVersion(ScriptEngine.ChakraClsid) != null;
    return useChakra ? ScriptEngine.ChakraClsid : ScriptEngine.JavaScriptLanguage;
string method = @"
    function markdownToHtml(text) {
        var reader = new stmd.DocParser();
        var writer = new stmd.HtmlRenderer();
        var parsed = reader.parse(text);
        return writer.render(parsed);

using (ScriptEngine engine = new ScriptEngine(_language))
using (ParsedScript parsed = engine.Parse(File.ReadAllText("stdm.js") + method))
    return (string)parsed.CallMethod("markdownToHtml", engine.Eval(EncodeJavaScriptString(text)));

And how to use it:

Markdown.ToHtml(@"# Hello there
This is a paragraph.
- one
- two
- three
- four
1. pirate
2. ninja
3. zombie")

This code gives the following result :

<h1>Hello there</h1>
<p>This is a paragraph.</p>

CodeFluent Runtime Client is free and available from NuGet. This package contains lots of useful class such as the ScriptEngine.

Have fun with Markdown,

The R&D Team

Template Engine and Extensibility

June 11, 2014 Leave a comment

A few time ago, we presented the CodeFluent Runtime’s Template Engine. Today we’ll see how to extend it to change a little bit its syntax and to add custom keywords.

Here is a simple template:

<% var now = new Date(); %>
Hello <%= Name %>!
It's <%= now.toDateString() %>
<%= CurrentUser %>

To use the standard Template Engine, we use this following code:

Template template = new Template();

template.LoadText(templateText, "Name", "CurrentUser");
string templateResult = template.Run(new Dictionary<string, object>
     { "Name", "Jone Doe" }, 
     { "CurrentUser", Environment.UserName }


This will output:

Hello Jone Doe!
It’s Thu Mar 6 2014
The R&D Team

After some customization, the template will be more readable:

Hello {{Name}}!
It's {{Now:yyyy/MM/dd}}

Before extending the template engine we have to understand how it works. The engine is composed of 4 classes:

  • Template: contains the configuration such as delimitation tokens and methods to load and run the template
  • ParsedTemplate: contains parameters and code or text blocks extracted while parsing the template
  • ParsedBlock / CodeBlock: contains block text and a method to transform it into JavaScript code
  • Output: contains methods to write into the output file

Let’s use the first sample to understand. First, it will parse the template and extract the following blocks:

  • CodeBlock: var now = new Date();
  • TextBlock: Hello
  • CodeBlock: = Name
  • TextBlock: It’s
  • CodeBlock: = now.toDateString()

Then it will transform blocks into JavaScript instructions. These Text blocks are transformed into “Output.Write(block content)”. When code block starts with “=” it will generate “Output.Write(parameterName)”, otherwise the JavaScript is written as is.

The generated JavaScript is:

function __run(Output, Name, CurrentUser) {
 var now = new Date(); 
Output.Write( Name );
Output.Write( now.toDateString() );
Output.Write( CurrentUser );

Now we understand the template engine, let’s extend it.
We would like to change to {{ and }}. To do so, we extend the Template class.

public class CustomTemplate : Template
    public CustomTemplate()
        StartToken = "{{";
        EndToken = "}}";

We also need to create a new CodeBlock to parse the content and write the appropriate JavaScript code:

public class CustomCodeBlock : CodeBlock
    public string Format { get; private set; }
    public string ArgumentName { get; private set; }

    public CustomCodeBlock(string code, int creationIndex)
        : base(code, creationIndex)

    private void Parse(string text)
        if (text == null || text.StartsWith("="))

        string argumentName = text;
        string format = null;
        int formatIndex = text.IndexOf(":");
        if (formatIndex > 0)
            argumentName = text.Substring(0, formatIndex);
            format = text.Substring(formatIndex + 1);

        ArgumentName = argumentName;
        Format = format;

    public override void BuildSourceCode(StringBuilder source, ParsedTemplate parsed)
            if (string.IsNullOrEmpty(Format))
                source.Append(", \"");


        base.BuildSourceCode(source, parsed);

Now we have to create the WriteFormatted function in the Output class:

[ComVisible(true)] // Needed to be used by JavaScript code
public class CustomOutput : Output
    public CustomOutput(ParsedTemplate template, TextWriter writer)
        : base(template, writer)


    public void WriteFormatted(object value, string format)
        if (string.IsNullOrWhiteSpace(format))
            Write(string.Format("{0}", value));
            string formattedValue = string.Format("{0:" + format + "}", value);

Finally let’s say to the Template to use our custom classes instead of the default ones.

public class CustomTemplate : Template
        public override CodeBlock CreateNewCodeBlock(string code, int creationIndex)
            return new CustomCodeBlock(code, creationIndex);

        public override Output CreateNewOutput(ParsedTemplate parsedTemplate, TextWriter writer)
            return new CustomOutput(parsedTemplate, writer);

That’s it! The full sample is available on our GitHub.

Happy Templating

The R&D Team.

How to compress or extract CAB archives?

June 2, 2014 1 comment

Today, on the series “Exploring the CodeFluent Runtime” we’re going to explore how to compress or extract CAB archives.

Cabinet (or CAB) is an archive file format for Windows that supports lossless data compression and embedded digital certificates used for maintaining archive integrity. Cabinet files have .cab file name extensions.

First, we have to add a reference to “CodeFluent.Runtime.dll”. The namespace we’ll use is “CodeFluent.Runtime.Compression”, the same as for compressing or extracting ZIP file.

One of the biggest advantage compare to ZIP file, is that it can work in memory or by using the file system as it uses Stream. The second point is you don’t have to add a native DLL: it’s all managed. While it’s less efficient than a native implementation, it’s easier to deploy.

Here’s an example to compress one file and a directory:

using (MemoryStream stream = new MemoryStream())
    using (CabFile file = new CodeFluent.Runtime.Compression.CabFile(stream, CabFileMode.Compress))
        file.CompressionLevel = CabCompressionLevel.Maximum;

Extracting files is as simple as compressing.

using (CabFile file = new CodeFluent.Runtime.Compression.CabFile(stream, CabFileMode.Decompress))
    file.EntryExtracted += (sender, e) =>

And there’s more…

We add a method to determine the compression method (CAB or ZIP) of a file. This method can use the file extension if available or the first four bytes of the file (i.e. magic number):

CompressionUtilities.SniffFileFormat("", useExtensionAsHint: true) == CompressionFileFormat.Cab

And that’s not all, in the previous article, we wrote about how to sign a file by using the runtime. CAB file can also be signed, so let sign it:

X509Certificate2 certificate = Authenticode.FindSuitableCertificate(); 
Authenticode.SignFile(certificate, "", null, "SoftFluent");

Cab properties

Happy compressing and signing,

The R&D Team


Get every new post delivered to your Inbox.

Join 56 other followers