Archive for the ‘C#’ Category.

Containerize .net Framework 4.8 Console Application

Introduction

In this article, we are going to create a Docker Image for a .net framework console application. The Docker Image will enable us to execute the console application within a Docker Container.

The Console Application

The console application that we will be using is called HelloWorldConsole.exe. When executed from the command line the application displays “Hello World”.

The application is a C# (c sharp) program that has been compiled using .net framework 4.7 and here is the source code for the application which we will be using within this article. Although in this article we will only be using the compiled application.

using System;

namespace HelloWorldConsole
{
    internal class Program
    {
        static void Main()
        {
            Console.WriteLine("Hello World");
        }
    }
}

Containerizing Procedure

In this procedure, we are going to create a Dockerfile. The file will describe how to create the Docker Image for the console application HelloWorldConsole.exe.

  1. In the same directory as the HelloWorldConsole.exe application create a text file called Dockerfile no extension.
  2. Using a text editor add the following code to the Dockerfile
    FROM mcr.microsoft.com/dotnet/framework/runtime:4.8
    WORKDIR /app
    COPY . .
    ENTRYPOINT ["/app/HelloWorldConsole.exe"]
  3. Open a command prompt and change the directory to the folder containing the Dockerfile
  4. Execute the docker command to build the image file. The command will create a new docker image called helloworldconsole. Docker image names are all lowercase. The full stop (period) at the end of the command is very important as this informs the command to look for the Dockerfile in the current working directory.

    docker image build --tag helloworldconsole .

  5. Execute the docker command to run the container using the image built in the previous step. The name argument will give set the container name to hello1 and helloworldconsole is the name of the image that will be used to create the container.

    docker run --name hello1 helloworldconsole

    There will be a short delay while the container boots and then the container will execute the HelloWorldConsole.exe console application.

  6. The output from the console application will be stored in the docker logs. You can review the log messages by using the docker log command with the name of the container.

    docker logs hello1

  7. The container hello1 can be stopped using the cocker stop command with the name of the container. To confirm the container has stopped execute the command docker container ls command.

    docker stop hello1

    docker container ls



Summary

In this article, we created a Docker image called helloworldconsole. Then using the image helloworldconsole we created a docker container called hello1. The container executed the console application HelloWorldConsole.exe. We viewed the output of the console application using docker logs and then stopped the container using the command docker stop.

How To Use Extension Methods in C#

Extension Methods can extend any type with additional methods
Extension Methods requirements:

  • Class must be static
  • The function must be static
  • The function must use ‘this’ in the arguments to denote the type that is being extended.
using System;

namespace ExtensionMethodExample
{
    internal class Program
    {
        static void Main()
        {
            string hello = "Hello";
            Console.WriteLine(hello.Shout());

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }

    public static class StringExtensions
    {
        public static string Shout(this string message)
        {
            return message.ToUpper();
        }
    }
}

C# Open File Dialog

            // Configure open file dialog box 
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.Title = "Select File"; // dialog title
            dlg.FileName = ""; // Default file name 
            dlg.DefaultExt = ".csv"; // Default file extension 
            dlg.Filter = "CSV File (.csv)|*.csv|All Files (*.*)|*.*"; // Filter files by extension 

            // Show the dialog and process result
            if (dlg.ShowDialog() == true)
            {
                string filename = dlg.FileName;
            }

Almost Equal C#

Test if two values are almost equal.

/// 
/// Test if two doubles are approximately equal
/// 
/// Test variable one
/// Test variable two
/// epsilon a measure of equality
/// boolean true = values are approximately equal, false = values are not equal
public static Boolean almostEqual(double a, double b, double eps)
{
    return Math.Abs(a - b) < eps;
}

Example using the function.

double a = 1.234;
double b = 1.235;
double eps = 0.01;
Console.WriteLine("equal = " + almostEqual(a, b, eps).ToString());

Using OpenCV inside a C# WPF application

In this example I will create a C++ dll that with contain the OpenCV image processing code. I then will create a C# WPF application, within this application i will then include the dll and using the image processing function.

  1. Install OpenCV http://docs.opencv.org/doc/tutorials/introduction/windows_install/windows_install.html#windows-installation
  2. Create a C++ Win32 console Application, in this example it will be called ImageProcessingAgain
  3. Click Next. Select Application type dll. Then click finish.
  4. Click Property Manager, right click on debug, then select ‘Add Existing Property Sheet’. If you dont have a property sheet follow the following tutorial for creating The Local Method http://docs.opencv.org/doc/tutorials/introduction/windows_visual_studio_Opencv/windows_visual_studio_Opencv.html
  5. Add the following code to the cpp

    // ImageProcessAgain.cpp : Defines the exported functions for the DLL application.
    //
    
    #include "stdafx.h"
    
    #include "opencv\cv.h"
    #include "opencv\highgui.h"
    
    extern "C"
    {   
    	__declspec(dllexport) int exampleImageProcessing(LPCWSTR);
    }
    
    extern int __cdecl exampleImageProcessing(LPCWSTR filename)
    {
    	IplImage* img = cvLoadImage((char*)filename);
    	return img->width;
    }
    
  6. build the dll project
  7. Create a C# WPF project called UsingOpencvAgain
  8. copy the dll and then include the dll within the C# project
  9. Select the dll in the solution explorer, set the ‘copy to output directory’ property to ‘copy if newer’
  10. Create two textboxes and a button
  11. Add the following C# code to the application

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using System.Runtime.InteropServices;
    
    namespace UsingOpencvAgain
    {
        /// 
        /// Interaction logic for MainWindow.xaml
        /// 
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }
    
            [DllImport("ImageProcessAgain.dll", CallingConvention = CallingConvention.Cdecl)]
            public static extern int exampleImageProcessing(string filename);
    
            private void button1_Click(object sender, RoutedEventArgs e)
            {
                textBox2.Text = exampleImageProcessing(textBox1.Text).ToString();
            }
        }
    }
    
    

Simple Write File using C#

A very simple method for writing to a file, not forget to include using System.IO;.

string filename = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\test.txt";
string content = "This is the new file content";
File.WriteAllText(filename, content);

Data Validation and Exceptions in C#

The setName funcion demostrates simple data validation on the argument value.

void setName(string value)
{
    // validate empty
    if (string.IsNullOrWhiteSpace(value))
    {
        throw new ArgumentNullException("Please enter a value");
    }

    // validate length
    if (value.Length > 10)
    {
        throw new ArgumentException("The value is too long");
    }

    // value is valid
    MessageBox.Show("The value is valid");
}

When calling the setName function it is important that we implement code to catch any exceptions

try
{
    setName(textBox1.Text);
}
catch (Exception ex)
{
    MessageBox.Show("Error " + ex.Message);
}

C# type checking with the is statement

A var type can be checked using the ‘is’ statement

var a = 1.0;

if (a is int)
{
    MessageBox.Show("int");
}
else
{
    MessageBox.Show("is NOT int");
}

C# class properties

The code below shows the short hand and long hand syntax for defining class properties.

public class Example
{
  // class property short hand
  public string Firstname {get; set;}


  // class property long hand
  private string _Lastname;
  public string Lastame
  {
     get {return _Lastname}
     set {_Lastname = value}
  }
}

Simple C# LINQ example

The LINQ example below creates a generic collection of the class Car. Then using a LINQ statement the collection is filtered to find cars that are newer than 2009.

List myCars = new List() {
    new Car() { Make="BMW", Model="550i", Year=2009 },
    new Car() { Make="Toyota", Model="4Runner", Year=2010 },
    new Car() { Make="BMW", Model="745li", Year=2008 },
    new Car() { Make="Ford", Model="Escape", Year=2008 },
    new Car() { Make="BMW", Model="550i", Year=2010 }
};


var newCars = from c in myCars
                where c.Year > 2009
                select new { c.Model, c.Make, c.Year };

foreach (var car in newCars)
{
    Console.WriteLine("{0} {1} - {2}", car.Make, car.Model, car.Year);
}

class Car
{
   public string Make { get; set; }
   public string Model { get; set; }
   public int Year { get; set; }
}