Monday, 16 May 2016

How to do async calls without locking the UI thread in WPF

WPF developers that have worked with async await have most likely run into problems with avoiding race conditions with the UI thread, either making the entire UI lock up or burden the UI thread and cause clients not responding. This article will show you how to avoid this. The way to do this is to await using another thread and afterwards use that result back again on the WPF thread to do the updates in the UI. We use ThreadPool.QueueUserWorkItem for this. As you can see, we user an inner method marked with async keyword to await the results. This is done to avoid the classic "async proliferation" seen in async code, where the async keyword spreads upwards to all methods. We instead use an outher method and call the async method and use the Result of the Task returned. We could do some quality checking here, to check if the Task succeeded of course. The Task object contains status information about if the results are really available or not and Result will throw an exception if there was an error in the retrieval of the async results from the lower layers of the software app layers. Example code:

DispatcherUtil.AsyncWorkAndUiThreadUpdate(Dispatcher.CurrentDispatcher, () => GetSomeItems(someId),
 x => GetSomeItemsUpdateUIAfterwards(x), displayWaitCursor:true);
//Note here that we retrieve the data not on the UI thread, but on a dedicated thread and after retrieved the
//result, we do an update in the GUI. 
private List<SomeItemDataContract> GetSomeItems(int someId)
        {
         var retrieveTask = GomeSomeItemsInnerAsync(someId);
         return retrieveTask.Result;
        }
 
private async Task<List<SomeItemDataContract>> GetSomeItemsInnerAsync(int someId)
        {
         List<SomeItemDataContract> retrieveTask = await SomeServiceAgent.GetSomeItems(someId);
         return retrieveTask;
        }

private void GetSomeItemsUpdateUIAfterwards(SomeItemDataContract x){
 if (x != null){
  //Do some UI stuff - remember RaisePropertyChanged
 }
}


Utility method:

public static void AsyncWorkAndUiThreadUpdate<T>(Dispatcher currentDispatcher, Func<T> threadWork, Action<T> guiUpdate, 
bool displayWaitCursor = false)
        {
         if (displayWaitCursor)
          PublishMouseCursorEvent<T>(Cursors.Wait);

         // ReSharper disable once UnusedAnonymousMethodSignature 
         ThreadPool.QueueUserWorkItem(delegate(object state)
            {
              T resultAfterThreadWork = threadWork();
              // ReSharper disable once UnusedAnonymousMethodSignature
              currentDispatcher.BeginInvoke(DispatcherPriority.Normal, new Action<T>(delegate {
       
              if (displayWaitCursor)
               PublishMouseCursorEvent<T>(Cursors.Arrow);
 
              guiUpdate(resultAfterThreadWork);
           }), resultAfterThreadWork);

            });
 
        }

The PublishMouseCursorEvent publishes a prism event that is captured by a Bootstrapper class, but what you choose to do here is of course up to you. One way is to subscribe such an event (either a CompositePresentationEvent as in Prism or an ordinary CLR event for example):
private void OnCursorEvent(CursorEventArg eventArg)
{
 if (eventArg != null)
 {
 Mouse.OverrideCursor = eventArg.Cursor;
 }
}

Sunday, 8 May 2016

RSA algorithm demo in MonoDevelop and GtkSharp

This article will present a demo of using RSA in Monodevelop using GtkSharp UI framework. As you know, the Mono project offers an implementation of .NET framework, such as BCL, CLR, MSIL and so on - and also the classes in System.Security.Cryptography! So let us delve into the details of doing some RSA crypto! First off, the GUI looks like this:


In MonoDevelop we use the Stetic GUI Designer to build the GUI!





Cool! We can build apps that runs on Linux and Windows with Monodevelop! Now over to the code of this app!




using System;
using Gtk;
using System.Text;
using System.Security.Cryptography; 
using System.Security; 
using System.IO; 

public partial class MainWindow: Gtk.Window
{

 private RSACryptoServiceProvider _rsa;
 private RSAParameters _rsaPrivateKey;
 private RSAParameters _rsaPublicKey;
 private byte[] _cipherBytes; 
 private byte[] _decipherBytes; 
 private byte[] _plainTextBytes;

 public MainWindow () : base ("Pango")
 {
  Application.Init ();
  Build ();
  SetupControls ();
  Application.Run ();
 }

 private void SetupControls(){
  Gdk.Color color = new Gdk.Color (255, 30, 80);
     lblP.ModifyFont (Pango.FontDescription.FromString ("Purisa 10")); 
  //lblP.ModifyBg (StateType.Normal, new Gdk.Color (255, 80, 10));
 }

 protected void OnDeleteEvent (object sender, DeleteEventArgs a)
 {
  Application.Quit ();
  a.RetVal = true;
 }

 protected void btnRsaSetupClick (object sender, EventArgs e)
 {
  _rsa = new RSACryptoServiceProvider ();
 
  StringWriter writer = new StringWriter (); 
  string rsaSetupXml = _rsa.ToXmlString (true);
  writer.Write (rsaSetupXml); 
  //tbRsaSetup.Buffer.Text = writer.ToString ();
  writer.Close ();

  _rsaPrivateKey = _rsa.ExportParameters (true);
  _rsaPublicKey = _rsa.ExportParameters (false); 

  SetupControls ();
  DisplayRsaSetup (_rsaPrivateKey);
 } 

 private void DisplayRsaSetup (RSAParameters rsaParams){
  try {
   lblPValue.Text = Convert.ToBase64String (rsaParams.P);
   lblQValue.Text = Convert.ToBase64String (rsaParams.Q);
   lblModulusValue.Text = Convert.ToBase64String (rsaParams.Modulus);
   lblDValue.Text = Convert.ToBase64String(rsaParams.D);
   lblEValue.Text = Convert.ToBase64String (rsaParams.Exponent);

  } catch (Exception err) {
   Console.WriteLine (err.Message);
  }

 }

 protected void btnEncryptClicked (object sender, EventArgs e)
 {
  if (_rsa == null)
   return;
  _plainTextBytes = Encoding.UTF8.GetBytes (textViewPlainText.Buffer.Text);
  _cipherBytes = _rsa.Encrypt (_plainTextBytes, false);
  textviewEncrypted.Buffer.Text = Convert.ToBase64String(_cipherBytes);
 }

 protected void btnDecryptClicked (object sender, EventArgs e)
 {
  textviewDecrypted.Buffer.Text = string.Empty; 

  if (_rsa == null)
   return;
  if (_cipherBytes == null)
   return; 
  _decipherBytes = _rsa.Decrypt (_cipherBytes, false); 

  textviewDecrypted.Buffer.Text = Encoding.UTF8.GetString(_decipherBytes); 
 }

}





As you can see in the code, we instantiate a new RSACryptoServiceProvider instance. We use the Encrypt and Decrypt method, using the second argument set to false to not use the OAEP padding, that is the Optimal Assymetric Encryption Padding for compability. Setting false here for padding will use the PKCS# instead. PKCS stands for Public Key Cryptography Standards. I have tested also with the parameters set to true i OAEP, and it seems to work nice also with Monodevelop - so you could use both types of padding. Note that we use the ExportParameters methods of the RSACryptoServiceProvider to the the RSAParameters object. In assymetric encryption, we must guard our private key and expose our public key. This is a comprehensive demo of the RSA algorithm. We would use the ExportParameters method with the parameters set to false to not include the private key. To export the RSA parameters with more compability, you can export the parameters as XML. You can use the ToXmlString() method to export the XML as a string. You can either export the RSA parameters as a string or to a file, and you can then use the method FromXmlString() to import the RSA parameters.

 {
  _rsa = new RSACryptoServiceProvider ();
 
  StringWriter writer = new StringWriter (); 
  string rsaSetupXml = _rsa.ToXmlString (true);
  writer.Write (rsaSetupXml); 
  //tbRsaSetup.Buffer.Text = writer.ToString ();
  writer.Close ();

As you can see in the code above, you can use a StringWriter to write to a string, but you can also use a FileStream to write the contents out to a file. Using the ToXmlString - you will export the information needed for a public key by setting the argument of this method to FALSE. To include private key information, you would provide the value TRUE here. In the RSA algorithm the following is belonging to the "PUBLIC Domain":
  • Modulus
  • Public exponent E
The "PRIVATE Domain" contains the additional information:
  • Private exponent D
  • Prime P
  • Prime Q
Private domain will also reveal the values DQ, DP, InverseQ that is given by this extra information. The security of the RSA algorithm relies on the toughness of prime factorization of large prime numbers. RSA will use large numbers and the public key only contains the modulus (product) of the prime numbers and a public exponent E that the sender will use this information as a public key to encrypt the information. The receiver, which knows the private key can then decrypt the information with this extra information. So the key note here is to guard your private key and share your public key! And that you can do RSA encryption when making applications for Linux of course, with Monodevelop! The .NET Framework is already there for you to use and it is very updated. To work with this sample, a download link is shown below. Bunzip the file using the command: tar xjvf RsaDemo.tar.bz2 Monodevelop project with RsaDemo

tar xjvf Symmetric.tar.bz2 

Just so you know:
tar - Tape ARchiver
And the options:
x - extract
v - verbose output (lists all files as they are extracted)
j - deal with bzipped file
f - read from a file, rather than a tape device

"tar --help" will give you more options and info

After unpacking, just open the solution in MonoDevelop.

So .NET Developers - Start your engines - Start developing for Linux!

Friday, 6 May 2016

Symmetric crypto algorithms in C# with MonoDevelop and GTK-Sharp

Using MonoDevelop and GTK-Sharp (GTK#) offers a .NET developer to develop applications for other platforms such as applications in Linux and other OS-es. Let's look more at the very able MonoDeveloper IDE and GTK-Sharp. As a .NET developer who has written .NET applications for many years, MonoDevelop has fully matured into a very good platform to develop a multitiude of applications. GTK# resembles .NET Windows Forms in many ways. We will here use some symmetric crypto algorithms in .NET that is available with Mono framework. The demo provides Digital Encryption Standard (DES) and Triple-DES, plus the Advanced Encryption Standard (AES) - Rijndael. The GUI will look like this:

The GUI is designed with the GUI designer Stetic in Monodevelop, for developing GTK#-applications. We can choose the Mode of the cryptographic algorithm, default here is Cipher Block Chaining. We can also set the padding of the cryptographic algorithm. Note that not all combinations are legal. I have tested with Rijndael, Cipher Block Chaining and padding set to Zeros, which seems to be working ok. You can use the demo here to test out other combinations. You can also generate different Initialization Vectors and Keys to use with the algorithm.

The code to achieve the encryption and decryption is listed below:

using System;
using System.Security.Cryptography;
using Gtk;
using System.IO;

public partial class MainWindow: Gtk.Window
{

 private SymmetricAlgorithm _symmetricAlgorithm; 
 private byte[] _intializationVector; 
 private byte[] _key;
 private byte[] _cipherBytes;



 public MainWindow () : base (Gtk.WindowType.Toplevel)
 {
  Build ();
 }

 protected void OnDeleteEvent (object sender, DeleteEventArgs a)
 {
  Application.Quit ();
  a.RetVal = true;
 }

 protected void btnGenerateIVClick (object sender, EventArgs e)
 {
     _symmetricAlgorithm = CreateSymmetricAlgorithm (); 

  _symmetricAlgorithm.GenerateIV ();
  _intializationVector = _symmetricAlgorithm.IV;

  lbInitializationVector.Text = Convert.ToBase64String(_symmetricAlgorithm.IV);

//  MessageDialog msgBox = new MessageDialog (null, DialogFlags.Modal, 
//                      MessageType.Info, ButtonsType.Ok, "Why hello world!");
//  msgBox.Run ();
//  msgBox.Destroy ();
 }

 protected void btnEncrypt_Click (object sender, EventArgs e)
 {
  _symmetricAlgorithm = CreateSymmetricAlgorithm (); //ensure that we use the selected algorithm
  _cipherBytes = Encrypt(textviewPlainText.Buffer.Text);
  textviewCipher.Buffer.Text = Convert.ToBase64String(_cipherBytes); 
 }

 private byte[] Encrypt(string text){
  byte[] encrypted;
  ICryptoTransform encryptor = _symmetricAlgorithm.CreateEncryptor (_key, _intializationVector);
  using (MemoryStream msEncrypt = new MemoryStream ()) {
   using (CryptoStream csEncrypt = new CryptoStream (msEncrypt, encryptor, CryptoStreamMode.Write)) {
    using (StreamWriter swWriter = new StreamWriter (csEncrypt)) {
     swWriter.Write (text);
    }
    encrypted = msEncrypt.ToArray (); 
   }

  }
  return encrypted;
 }

 private string Decrypt(byte[] cipherBytes){
  try {
   ICryptoTransform decryptor = _symmetricAlgorithm.CreateDecryptor (_key, 
    _intializationVector);
   using (MemoryStream msEncrypt = new MemoryStream (cipherBytes)) {
    using (CryptoStream csEncrypt = new CryptoStream (msEncrypt, decryptor,
     CryptoStreamMode.Read)) {
     using (StreamReader sReader = new StreamReader (csEncrypt)) {
      string decrypted = sReader.ReadToEnd();
      return decrypted;
     }
    } 
   }
  } catch (Exception err) {
   Console.WriteLine (err.Message);
  }
  return string.Empty;
 }

 private SymmetricAlgorithm CreateSymmetricAlgorithm(){
  SymmetricAlgorithm sa = null;
  if (rbDES.Active)
   sa = DESCryptoServiceProvider.Create ();
  if (rbThreeDES.Active)
   sa = TripleDESCryptoServiceProvider.Create ();
  if (rbRijndael.Active)
   sa = RijndaelManaged.Create ();

  if (sa == null)
   sa = DESCryptoServiceProvider.Create (); 

  if (_intializationVector != null)
   sa.IV = _intializationVector;
  if (_key != null)
   sa.Key = _key;

  sa.Mode = GetCipherMode ();
  sa.Padding = GetPadding ();
  return sa;
 }

 private PaddingMode GetPadding(){
  if (rbPaddingNone.Active)
   return PaddingMode.None;
  if (rbPaddingZeros.Active)
   return PaddingMode.PKCS7;
  if (rbPaddingAnsiX923.Active)
   return PaddingMode.ANSIX923;
  if (rbPaddingISO1126.Active)
   return PaddingMode.ISO10126;
  return PaddingMode.Zeros;
 }

 private CipherMode GetCipherMode(){
  if (rbCBC.Active)
   return CipherMode.CBC;
  if (rbCFB.Active)
   return CipherMode.CFB;
  if (rbCTS.Active)
   return CipherMode.CTS;
  if (rbECB.Active)
   return CipherMode.ECB;
  if (rbOFB.Active)
   return CipherMode.OFB;

  return CipherMode.CBC;
 }

 protected void btnKeyClick (object sender, EventArgs e)
 {
  _symmetricAlgorithm = CreateSymmetricAlgorithm ();     

  _symmetricAlgorithm.GenerateKey ();  
  _key = _symmetricAlgorithm.Key;
  lblKey.Text = Convert.ToBase64String (_symmetricAlgorithm.Key);
 }

 protected void btnDecryptClick (object sender, EventArgs e)
 {
  _symmetricAlgorithm = CreateSymmetricAlgorithm (); //ensure that we use the selected algorithm
  string decrypted = Decrypt(Convert.FromBase64String(textviewCipher.Buffer.Text));
  textviewDecrypted.Buffer.Text = decrypted; 
 }
}











To open up this sample, I have uploaded the MonoDevelop project as a tar.bz2 file available for download here: Sample project Monodevelop in this article To unzip the tar bunzip2 file, just the following command:
tar xjvf Symmetric.tar.bz2 

Just so you know:
tar - Tape ARchiver
And the options:
x - extract
v - verbose output (lists all files as they are extracted)
j - deal with bzipped file
f - read from a file, rather than a tape device

"tar --help" will give you more options and info

After unpacking, just open the solution in MonoDevelop.