November 26, 2013

Working with SandCastle Problems

I created a project using the "SHFB v1.9.7.0 with Visual Studio Package". This was used to convert an old help project to the latest format. However after the conversion I had make 2 fixes to get the project to build. SandcastleHelpBuilder post conversion fixes:
  1. Ensure that in the "Project Properties" tab 'Build' option that the 'Framework Version' field is set to '.NET Framework 2.0', the framework version of the compiled source code.
  2. Ensure that in the "Project Properties" tab 'Paths' option that the 'Working files path' field is set to 'Working\'.

November 6, 2013

Path Extension Class

This helper creates a temporary file with the given extension.
public static class PathExtensions
{
 // Create a temporary file with a specific file extension
 public static string GetTempFileName(string extension)
 {
  string tempFileName = Path.GetTempFileName();
  string newtempFileName = tempFileName.Replace(".tmp", extension);
  File.Move(tempFileName, newtempFileName);
  return newtempFileName;
 }
}

November 5, 2013

Guid String Formats

Most concise form is
 string guid = Guid.NewGuid().ToString("N");
There are other formats as well The ToString(string format) method can format a guid in one of several ways:
"N" - xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx (32 digits)
"D" - xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (32 digits separated by hyphens)
"B" - {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} (same as "D" with addition of braces)
"P" - (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) (same as "D" with addition of parentheses)
"X" - {0x00000000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}
The Guid can be shortened as a string by using Base64 encoding:
//Compress the given Guid as a base64 string that is 22 characters long.
private static string ToShortString(Guid guid)
{
  string encoded = Convert.ToBase64String(guid.ToByteArray());
  return encoded.Substring(0, 22); // Last 2 characters are always ==
}

September 23, 2013

Using the Windows 7 shell Taskbar Item to show that a WPF application is busy/idle

Add the following to the Main window XAML:
    <Window.TaskbarItemInfo>
        <TaskbarItemInfo />
    </Window.TaskbarItemInfo>
In code: To make the task bar icon pulse green to show that it is busy but when the application cannot determine how far through the proceesing the app is:
this.TaskbarItemInfo.ProgressState = TaskbarItemProgressState.Indeterminate;
To stop the task bar icon pulsating green/return it to normal:
this.TaskbarItemInfo.ProgressState = TaskbarItemProgressState.None;
To show progress through the task bar icon:
this.TaskbarItemInfo.ProgressState = TaskbarItemProgressState.Normal;
// ProgressValue must be a value between 0.0 and 1.0
this.TaskbarItemInfo.ProgressValue = progressPercentage/100.0d; 

August 28, 2013

LINQPad Command-Line and Scripting

LINQPad Command-Line and Scripting
Sample usage:
CALL C:\...\LinqPad\lprun.exe "C:\...\Queries\AttachDatabases.linq" DEV
This runs the given linq query. The sample is a "C# Program" and has a "Main" method taking "string[] args" as a paremeter. In this way the "DEV" string at the end of the line is passed as a parameter to the linq program.
Here is the sample linq script:
<Query Kind="Program" />

void Main(string[] args)
{
  string attachFolder = @"C:\Databases\";
  if ((args != null) && (args.Length == 1))
  {
  attachFolder = Path.Combine(attachFolder, args[0]);
  }
  Console.WriteLine("Attaching to databases in \'" + attachFolder + "\'"); 
  Console.WriteLine("");
  var server = @".\";
  var databaseNames = new[] { "XXX", "YYY", "ZZZ", "AAA" };

    using(var connection = new SqlConnection(
   string.Format("Server={0};Database=master;Trusted_Connection=True;", server)))
    {
    connection.Open();
  
    // attach the databases
    foreach(var database in databaseNames)
    {
      var dataFile = Path.Combine(attachFolder, database + "_Data.MDF");
      if (File.Exists(dataFile))
      {
        Console.WriteLine("Attaching {0}", database);
        var attachCommand = connection.CreateCommand();
        attachCommand.CommandText = "sp_attach_db  @dbName, @dataFileName, @logFileName";
        attachCommand.Parameters.AddWithValue("dbName", database);
        attachCommand.Parameters.AddWithValue("dataFileName", dataFile);
        attachCommand.Parameters.AddWithValue("logFileName", 
            Path.Combine(attachFolder, database + "_Log.LDF"));    
        attachCommand.ExecuteNonQuery();
      }
      else
      {
        Console.WriteLine("No data file for {0}", database);
      }
    }
      }
  
    Console.WriteLine("");
    Console.WriteLine("Press any key to continue ...");
    Console.ReadKey(false);
}
If you want the script to hang around a bit so that you can read the error messages then you can add the the following lines to the end
Console.WriteLine("");
Console.WriteLine("Press any key to continue ...");
Console.ReadKey(false);
This keeps the script alive until a key is pressed.

August 16, 2013

An Animated WPF Gif

The Image control in WPF does not support animated GIF files by default. However, there is a library on codeplex, here, that can be used to do this.
Here is my usage of this library for an animated busy indicator.
In the XAML, first of all create an XML namespace for the library:
xmlns:gif="http://wpfanimatedgif.codeplex.com"
then use it with an image control:
<Image Name="imgBusy" 
       Stretch="UniformToFill" VerticalAlignment="Top" Width="20"  
    gif:ImageBehavior.AnimatedSource="/ScriptRunnerWPF;component/Resources/busyIndicator.gif" 
    gif:ImageBehavior.AutoStart="False" />
In code the animation of the GIF can be controlled:
Start the animation
   
this.imgBusy.Visibility = System.Windows.Visibility.Visible;
ImageAnimationController iac = ImageBehavior.GetAnimationController(this.imgBusy);
if (iac != null)
    iac.Play();
Resume the animation
// Resume the animation (or restart it if it was completed)
ImageAnimationController iac = ImageBehavior.GetAnimationController(this.imgBusy);
if (iac != null)
 iac.Pause();
this.imgBusy.Visibility = System.Windows.Visibility.Hidden;

Using StackTrace

Using StackTrace to show the first 3 lines of a stack trace in the debugger:
StackTrace st = new StackTrace(false);
st.Dump("UpdateScriptRunning Stack Trace", 3);
and the accompanying extension method:
public static class StackTraceExtender
{
  public static void Dump(this StackTrace st, string context, int numFrames)
  {
    Debug.WriteLine(context ?? "");
    string stk = st.ToString();
    string[] wanted = stk.Split(new string[] { "\r\n" }, 
                             StringSplitOptions.RemoveEmptyEntries);
    foreach (string line in wanted.Take(numFrames))
    {
        Debug.WriteLine(line ?? "");
    }
  }
}

July 8, 2013

WPF Hyperlink Sample

Here are a couple of examples
WPF Application Hyperlink (in this case handle the RequestNavigate)
<TextBlock>Files found using the given <Hyperlink 
Name="hlRules" 
NavigateUri="Rules" 
RequestNavigate="Hyperlink_RequestNavigate">Rules</Hyperlink>:
</TextBlock>
private void HyperlinkRequestNavigate(object sender, RequestNavigateEventArgs e)
{
   // What to do with a hyperlink navigation request?
   // If it is an internet URI this will invoke the default browser
   // Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));

   // Otherwise show a dialog or whatever you want
   e.Handled = true;
}
Also check this out this link for a reusable hyperlink navigation routine using dependent properties.

How about using a WPF hyperlink in MVVM. Here is how it is done.
In the XAML add the textblock with the hyperlink and bind it to a command ('AboutCommand' in this case). Note in this sample the text of the hyperlink is also bound to some property 'Version'
 <TextBlock>
    <Hyperlink Command="{Binding AboutCommand}"><TextBlock Text="{Binding Version}" /></Hyperlink>
 </TextBlock>
The command is implemented in the ViewModel
private RelayCommand aboutCommand;

public RelayCommand AboutCommand
{
 get
 {
  return aboutCommand ?? (aboutCommand = new RelayCommand(ExecuteAboutCommand));
 }
}

private void ExecuteAboutCommand()
{
 IAboutDialogService aboutDialogService = ServiceLocator.Current.GetInstance<IAboutDialogService>();
 aboutDialogService.ShowAboutDialog(this.Title);
}

Monotonic Variable

Made this definition up myself. This is effectively a one way variable that starts off in one state and switches to another alternate state. It always starts off in a known state and during the period when it can be accessed by multiple threads it can only be switched to the other alternate state. This has repercussions for thread safe access to the variable with .NET. In certain cases, it can be that none is required. TODO: Explain in more detail.

Generally I use a boolean for my monotonic variable but it is not necessarily a boolean, I have used a reference type in a monotonic manner where the variable has a null reference to begin with, but at some point the reference is assigned.


June 30, 2013

Code Contract


Normally we use Debug.Assert() for code contracts. To stop the Debug.Assert() statements from activating during unit tests, add the following to te unit tests application config file ("App.Config"):
  <?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.diagnostics>
        <assert assertuienabled="false"/> <!-- Disable Debug.Assert() when running unit tests in debug mode. -->
    </system.diagnostics>
</configuration>
Following is a code contract type class that can make code assertions without throwing an Assert dialog during an NUnit test. Also the code contracts will be logged in release. A potential product failure in the field could be traced back to a code contract failure.
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;

namespace Common.CodeContracts
{
    /// <summary>
    /// A simple code contract class to replace Debug.Assert(). It can be used in release 
    /// and will log code contract failures to the Trace output window.
    /// </summary>
    public static class RuntimeCodeContract
    {
        // Switch on the Debugger.Break when required
        public static bool DebuggerBreakOnFailure { get; set; } = false;

        public static void Requires(bool condition,
                string message,
                [CallerFilePath] string file = "",
                [CallerMemberName] string member = "",
                [CallerLineNumber] int line = 0)
        {
            if (!condition)
            {
                var msg = $"Code contract failure detected: \"{message}\" in member \"{member}\" on line {line} in file \"{file}\"";
                Trace.TraceError(msg);
                if (DebuggerBreakOnFailure)
                {
                    Debugger.Break(); // Use the call stack window to find the invoker location
                }

                //throw new InvalidOperationException(msg);
            }
        }

        public static void RequiresArgument(bool condition,
                string paramName,
                string message = "",
                [CallerFilePath] string file = "",
                [CallerMemberName] string member = "",
                [CallerLineNumber] int line = 0)
        {
            if (!condition)
            {
                var msg = $"Argument requirement failure detected: {message} \"{paramName}\" in member \"{member}\" on line {line} in file \"{file}\"";
                Trace.TraceError(msg);
                if (DebuggerBreakOnFailure)
                {
                    Debugger.Break(); // Use the call stack window to find the invoker location
                }

                //throw new ArgumentException(message, paramName);
            }
        }

        public static void RequiresArgumentNotNull(object parameter,
                string paramName,
                [CallerFilePath] string file = "",
                [CallerMemberName] string member = "",
                [CallerLineNumber] int line = 0)
        {
            if (parameter == null)
            {
                var msg = $"Argument {paramName} was null in member {member} on line {line} in file {file}";
                Trace.TraceError(msg);
                if (DebuggerBreakOnFailure)
                {
                    Debugger.Break(); // Use the call stack window to find the invoker location
                }

                //throw new ArgumentNullException(msg, paramName);
            }
        }

    }
}
It is also a good example of using the compiler attributes "CallerFilePath", "CallerMemberName", and "CallerLineNumber" for diagnostics.

C# Task Object

Task basics
Task and Thread Difference

Here are some notes that I made from these and other blogs:
Task - Specifies some work to be executed asynchronously
ContinueWith - Specifies some work to be executed asynchronously after a task has completed

In computer science terms, a Task is a future or a promise. Basically, a Task "promises" to return you a T, but not immediately

A Thread is one of many ways to fulfill that promise. But not every Task needs a Thread. If the value you are waiting for comes from the filesystem or a database or the network, then there is no need for a thread. The Task might just register a callback to receive the value when the disk is done seeking.

In particular, the Task does not say why it is that it takes such a long time to return the value. It might be that it takes a long time to compute, or it might that it takes a long time to fetch. Only in the former case would you use a Thread to run a Task. (In .NET, threads are freaking expensive, so you generally want to avoid them as much as possible and really only use them if you want to run multiple heavy computations on multiple CPUs.

Tasks can be organised in parent child relationships so that a parent task will wait for its children to complete.

Here is an example of how to start a task with a particular return type and then wait for it to finish
var someTask = Task<int>.Factory.StartNew(() => slowFunc(1, 2));
Task<int32> task = new Task<int32>(n => Sum((Int32)n), 1000);
task.Start(); // Start the task
task.Wait();  // Wait for it to finish
Here is an example of how to cancel a task.
CancellationTokenSource cts = new CancellationTokenSource();
Task<int32> t = new Task<int32>(() => Sum(cts.Token, 1000), cts.Token);
t.Start(); // Start the task
cts.Cancel(); // Cancel the task

Task<int32> t = new Task<int32>(n => Sum((Int32)n), 1000);
       t.Start();
       // notice the use of the Result property
       Task cwt = t.ContinueWith(task => Console.WriteLine(
                       "The sum is: " + task.Result));
They are very easy to use and have a lot of advantages over Threads as follows:
  • You can create return types to Tasks as if they are functions.
  • You can the "ContinueWith" method, which will wait for the previous task and then start the execution. (Abstracting wait)
  • You can use Task.WaitAll and pass an array of tasks so you can wait till all tasks are complete.
  • You can attach task to the parent task, thus you can decide whether the parent or the child will exist first.
  • You can achieve data parallelism with LINQ queries.
  • You can create parallel for and foreach loops
  • Very easy to handle exceptions with tasks.
  • Most important thing is if the same code is run on single core machine it will just act as a single process without any overhead of threads.
Disadvantage of tasks over threads:
  • Not knowing what thread the task is invoked on can be a problem in itself when locking access to data so assume the worst.
  • You need .Net 4.0
  • Newcomers who have learned operating systems can understand threads better.

Tip:- Always use Task.Factory.StartNew method which is semantically perfect and standard. Actually, under the hood it is a slightly more efficient means to initiate the task as well.

Also can force a task to execute on the GUI thread:
// Get the UI thread's context
var context = TaskScheduler.FromCurrentSynchronizationContext();
...
Task task = Task.Factory.StartNew( () =>
   {
       // Do some work...           
   })
   // Continue on the UI thread, since this lets us update when our
   // "work" completes.
   .ContinueWith(_ => this.label1.Text = "Task Complete!", context);
OR even simpler from within the GUI do
Task task = Task.Factory.StartNew( () =>
   {
       // Do some work...           
   })
   // Continue on the UI thread, since this lets us update when our
   // "work" completes.
   .ContinueWith(_ => this.label1.Text = "Task Complete!",
       TaskScheduler.FromCurrentSynchronizationContext());

May 30, 2013

NIST 800-131A Standard Summary

Read through the NIST 800-131A document and have tried to summarise the standard here. I have excluded all time limited options for this and mention here only the standards that are deemed always acceptable.

Encryption

Triple DES Encryption is being deprecated and only 3 key triple DES is now acceptable. SKIPJACK encryption is no longer acceptable. AES Encryption has 3 approved key lengths: 128, 192 and 256.
From the following Rijndael AES differences link it seems that the AES encryption algorithm is a form of the Rijndael algorithm except that it has a fixed block size. Essentially, if you want to use Rijndael as AES you need to make sure that:

  • The block size is set to 128 bits
  • You are not using CFB mode, or if you are, the feedback size is also 128 bits

Digital Signatures

There are three digital signature algorithmns approved: DSA, ECDSA and RSA. It seems that for RSA that this equates to a key size of at least 2048 bits.

Random Number Generators

The following are listed as the standards currently acceptable as specified in the SP 800-90 document: HASH, HMAC, CTR, DUAL_EC.

Digital Signatures

Basically this section says that the key length must be of at least 112 bits.

Hash Functions

SHA1 is no longer acceptable for digital signature generation HOWEVER, for “… hash-only applications (e.g., hashing passwords and using SHA-1 to compute a checksum…”, it is still acceptable (see page 14, end of section 9). SHA-224/256/384/512 are all deemed acceptable for all hashing function applications.

Message Authentication Codes

HMAC based hashing functions are always acceptable when the key size is at least 112 bits

Command Line Parameter Accessors in .NET

How can strings containing white space be passed as command line parameters?
Here is the test console program:
class Program
{     
    static void Main(string[] args)
    {
        Console.WriteLine("Main(string[] args)=" + string.Join(",", args));
        Console.WriteLine("Environment.CommandLine=" + Environment.CommandLine);
        Console.WriteLine("Environment.GetCommandLineArgs()=" + string.Join(",", Environment.GetCommandLineArgs()));

        Console.WriteLine("");
        Console.WriteLine("Press any key to continue ...");
        Console.ReadKey(false);
    }
}
Using the following as command ine arguments:
Test -b:"Dummy User" "whataboutthis?" /x'Does this work' /a:another a"rgument
Produces this (the command line arguments are comma separated):
Main(string[] args)=Test,-b:Dummy User,whataboutthis?,/x'Does,this,work',/a:another,argument
Environment.CommandLine="C:\Users\...\bin\Debug\TestAccountName.vshost.exe" Test -b:"Dummy User" "whataboutthis?" /x 'Does this work' /a:another a"rgument
Environment.GetCommandLineArgs()=C:\Users\...\bin\Debug\TestAccountName.vshost.exe,Test,-b:Dummy User,whataboutthis? ,/x'Does,this,work',/a:another,argument

Looks like quotation characters "" can be used to enclose a part of a command line that contains white space, the quotation characters themselves are removed. Placing matching quotation characters around/within a command line argument ensures that it is interpreted as a single command line argument even if it contains whitespace characters. Quotation characters are stripped from the command line parameters as they are processed so they will not appear in the arguments.

Summary
Main(string[] args)
  • Gives access to ONLY the command line parameters themselves.
  • Executable is NOT included as a command line parameter.
  • Quotation marks can be used to capture a parameter or part of a parameter containing whitespace
Environment.CommandLine
  • Gives access to the raw command line
Environment.GetCommandLineArgs()
  • Gives access to ALL the command line parameters.
  • Executable is first command line parameter.
  • Quotation marks can be used to capture a parameter or part of a parameter containing whitespace

February 21, 2013

De Morgan's Theorem

Wikipedia has more info on this
I am always forgetting this rule:
NOT (P  OR Q) = (NOT P) AND (NOT Q)
NOT (P AND Q) = (NOT P)  OR (NOT Q) 
or in more generealised form:
NOT (P  OR Q  OR R  OR ...) = (NOT P) AND (NOT Q) AND (NOT R) AND ...
NOT (P AND Q AND R AND ...) = (NOT P)  OR (NOT Q)  OR (NOT R)  OR ...
In C#
!(P || Q) = (!P) && (!Q)
!(P && Q) = (!P) OR (!Q) 
Can be useful sometimes to improve code readability but do not use it for optimisation (let the compiler do that)

February 4, 2013

A Generic ThreadPool.QueueUserWorkItem

Found the idea here
A generic version of the "ThreadPool.QueueUserWorkItem" method. I believe that this really belongs in the .NET framework
// Generic QueueUserWorkItem implementation, the thread routine signature
public delegate void ThreadRoutine<T>(T state);

/// <summary>
/// Extensions to the ThreadPool class
/// </summary>
public static class ThreadPoolExtender
{
  /// <summary>
  /// Queue specified thread routine/work item for processing 
  /// on a thread pool thread.
  /// </summary>
  /// <typeparam name="T">Thread routine parameter type.</typeparam>
  /// <param name="state">object containing state for the thread 
  /// routine.</param>
  /// <param name="threadRoutine">Thread routine/work item to queue 
  /// that shall be executed on a thread pool thread</param>
  /// <returns>indicates success.</returns>
  public static bool QueueUserWorkItem<T>(T state, ThreadRoutine<T> threadRoutine)
  {
    return ThreadPool.QueueUserWorkItem(s => threadRoutine((T)s), state);
  }
}
Sample usage with an an anonymous object
 
res = ThreadPoolExtender.QueueUserWorkItem(
    // Anonymous type, saves defining a class type just for this call
    new { onFinishedDelegate = onFinished, Folderpath = folderPath },
    (input) => // input matches the anonymous object defined in the line above
    {   // Start worker thread work
        bool outcome = this.DoSomething(input.Folderpath);
        // In this example we callback on a delegate to indicate that 
        // the thread work is complete
        input.onFinishedDelegate(outcome); 
    }); // End worker thread work