Archive

Archive for the ‘Exploring the CodeFluent Runtime’ Category

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

GetArgument

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

HasArgument

Determines whether the argument is specified in the command line.

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

NamedArguments

List all arguments, the name will be the key.

// -> {{“ ProductName”,”Word”},{“SendEmail”,”true”}}
CommandLineUtilities.NamedArguments;

HelpRequested

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.

ChangeType

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

SetCurrentThreadCulture

Sets the current thread culture. Handles integer values as lcid (http://msdn.microsoft.com/en-us/goglobal/bb964664.aspx)

ConvertUtilities.SetCurrentThreadCulture("fr-FR");
ConvertUtilities.SetCurrentThreadCulture(1036);
ConvertUtilities.SetCurrentThreadCulture("1036");

Decamelize
Decamelizes the specified text using default decamelization options.

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

Evaluate

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 

ConcatenateCollection

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"

FormatFileSize

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

FromFileExtension

Converts a file extension to the corresponding image format.

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

IsFlagsEnum

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 

GetMaxValue

Gets the maximum value for a given type.

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

GetUniqueName

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>
"Gérald",
"Alexandra",
"Lionel",
"Marc"
};
ConvertUtilities.GetUniqueName(names, "lionel", StringComparison.InvariantCultureIgnoreCase); // –>  lionel2
ConvertUtilities.GetUniqueName(names, "john", StringComparison.InvariantCultureIgnoreCase); // –> john

Nullify

Nullifies the specified string.

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

RemoveDiacritics

Removes diacritics (accents) from a text.

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

SplitToList

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 

ToHexa

Converts a byte array to its hexadecimal string representation.

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

ToHexaDump

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: http://www.nuget.org/packages/CodeFluentRuntimeClient and use the SingleInstance class:

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

public MainForm() 
{ 

  if (!_singleInstance.WaitForMutext(IntPtr.Zero, IntPtr.Zero)) 
  { 
    Close(); 
  } 

  InitializeComponent();
}

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: https://github.com/SoftFluent/SoftFluent.CommonMarkdown 

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>
<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
  <li>four</li>
</ul>
<ol>
  <li>pirate</li>
  <li>ninja</li>
  <li>zombie</li>
</ol>

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() %>
Cheers,
<%= 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 }
}); 

Console.WriteLine(templateResult);

This will output:

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

After some customization, the template will be more readable:

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

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:

ActiveXObject=null;
function __run(Output, Name, CurrentUser) {
 var now = new Date(); 
Output.WriteBlock(1);
Output.Write( Name );
Output.WriteBlock(3);
Output.Write( now.toDateString() );
Output.WriteBlock(5);
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)
    {
        Parse(code);
    }

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

        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(ArgumentName))
        {
            source.Append(parsed.Template.OutputItemName);
            if (string.IsNullOrEmpty(Format))
            {
                source.Append(".Write(");
                source.Append(ArgumentName);
                source.Append(");");
            }
            else
            {
                source.Append(".WriteFormatted(");
                source.Append(ArgumentName);
                source.Append(", \"");
                source.Append(Format);
                source.Append("\");");
            }

            return;
        }

        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));
        }
        else
        {
            string formattedValue = string.Format("{0:" + format + "}", value);
            Write(formattedValue);
        }
    }
}

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;
        file.AddEntry("File.txt");
        file.AddDirectory("Sample");
    }
}

Extracting files is as simple as compressing.

using (CabFile file = new CodeFluent.Runtime.Compression.CabFile(stream, CabFileMode.Decompress))
{
    file.EntryExtracted += (sender, e) =>
    {
        //e.Entry.Name
        //e.Entry.OutputStream
        //e.Entry.Bytes
        //e.Entry.Size
        //e.Entry.LastWriteTime
        //e.Entry.Tag
    };
    file.ExtractEntries();
}

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("test.cab", 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, "test.cab", null, "SoftFluent");

Cab properties

Happy compressing and signing,

The R&D Team

Exploring the CodeFluent Runtime: Authenticode

May 28, 2014 2 comments

Today, on the series “Exploring the CodeFluent Runtime” we’re going to explore how to sign an application with Authenticode method.

Microsoft Authenticode, which is based on industry standards, allows developers to include information about themselves and their code with their programs through the use of digital signatures. Authenticode allows software vendors to sign:

  • .cab files
  • .cat files
  • .ctl files
  • .dll files
  • .exe files
  • .ocx files

First we need a certificate that allows Code Signing. If you haven’t one, let’s create a self-signed one:

REM May change depending of your installed Windows SDK
cd "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Bin"

REM Generate the root certificate
.\makecert.exe -r -pe -n "CN=Sample.CA" -ss CA -sr CurrentUser -a sha1 -cy authority -sky signature -sv d:\Sample.CA.pvk d:\Sample.CA.cer

REM Add the Root certificate to the user store
certutil.exe -user -addstore Root d:\Sample.CA.cer

REM Create the certificate for code signing
.\makecert.exe -pe -n "CN=Sample.CodeSigning" -eku "1.3.6.1.5.5.7.3.3,1.3.6.1.4.1.311.10.3.13" -a sha1 -cy end -sky signature -ic d:\Sample.CA.cer -iv d:\Sample.CA.pvk -sv d:\Sample.CodeSigning.pvk d:\Sample.CodeSigning.cer

REM Convert to certificate to pfx file format
.\pvk2pfx.exe -pvk d:\Sample.CodeSigning.pvk -spc d:\Sample.CodeSigning.cer -pfx d:\Sample.CodeSigning.pfx

For convenience you can add the certificate to the personal store (“My”) by double clicking on it in the explorer.

We can now sign a file. Add the “CodeFluent.Runtime.dll” reference and use the following code:

// If you have zero more than one code signing certificate in the personal store, you have to load the certificate manually.
X509Certificate2 certificate = Authenticode.FindSuitableCertificate();
Authenticode.SignFile(certificate, "sample.exe", null, "SoftFluent");

The first line find a valid certificate for code signing in the user certificate store. If none is found, it returns null.

The second line signs the file. You have to indicate:

  • the certificate to use
  • the file to sign
  • the timestamp server
  • the display name

If you look at the file properties, you’ll find a new tab ‘Digital Signature’ which contains details about the signer.

Digital Signature

 

Please note:

  • you don’t need to provide a password, nor a path to the certificate => Generic, simple and secure
  • the method doesn’t rely on the Windows SDK, so you don’t have to bother with SDK path => much simplier :)
  • it’s a DLL so it’s very easy to integrate in your application

Additionally you’ll find two methods:

//Determines whether the specified certificate can sign code.
public static bool CanSignCode(X509Certificate2 certificate)

//Determines whether the specified file is signed using authenticode.
public static bool IsSigned(string filePath)

Starting with build 786:

When you sign a file with a timestamp server, an exception is sometimes raised. The workaround is to sign the file without using a timestamp server and then timestamp the signed file:

X509Certificate2 certificate = Authenticode.FindSuitableCertificate();
Authenticode.SignFile(certificate, "sample.exe", null, "Sample");
Authenticode.TimeStampFile("sample.exe", "http://timestamp.verisign.com/scripts/timstamp.dll");

We also introduce a new overload which allow to specify the hash algorithm to use:

Authenticode.SignFile(certificate, "sample.exe", null, "Sample", Authenticode.Sha512AlgorithmId);

Happy authenticoding,

The R&D team

Follow

Get every new post delivered to your Inbox.

Join 55 other followers