.

Starting a WPF app programmatically (without a startup uri)

The default project template for WPF applications assumes that you want your main application class to be xaml-based. However, this is not a requirement and you can change it. Doing so allows you to write your own application entry point method and create your own application instance configured the way that you want.

So, you can delete your App.xaml and App.xaml.cs files and create an App.cs file in their place. In that file, do something like this:

internal class App : Application
{
    [STAThread]
    public static int Main(string[] args)
    {
        App app = new App();
        // Setup your application as you want before running it
        return app.Run(new MainWindow());
    }

    public App()
    {
        // (Optional) Load your application resources file (which has a "Page" build action, not "ApplicationDefinition",
        // and a root node of type "ResourceDictionary", not "Application")
        Resources = (ResourceDictionary)Application.LoadComponent(new Uri("/MyAssemblyName;component/Resources.xaml", UriKind.Relative));
    }
}

This allows you specify your main window whichever way you want before running the application. Your application resources file would look something like this:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <!-- Put application resources here -->
</ResourceDictionary>

I always structure my WPF applications this way because it seems simpler and provides more control over how the application is run. (I created a custom WPF application project template in Visual Studio.)

setting up CORS

need the following in your WebAPI web.config:

  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>

Getting started with SpecFlow in Visual Studio

I use VS 2013 for this example.

1) Create a new blank project (just a class library)

2) Install SpecFlow for Visual Studio from the menu (Tools -> Extensions & Updates)

3) right click -> add new item -> SpecFlow Feature File
Just name is “MyFirst.feature” for now.

4) just copy and paste the following in your editor window:

Feature: MyFirst
	In order to avoid silly mistakes
	As a math idiot
	I want to be told the sum of two numbers

@mytag
Scenario: Add two numbers
	Given I have entered 50 + 60 into the calculator
	When I press add
	Then the result should be 110 on the screen

Scenario: Add other numbers
	Given I have entered 6 + 8 into the calculator
	When I press add
	Then the result should be 14 on the screen

5) Right click on the file content and select “generate step definitions”.
use the style = regular expressions in attributes
and simply copy the methods to clipboard

6) create a new file ( just a plain class) and name it MyFirstSteps.cscopy and paste the following code (just a very simple basic implementation as example):

using System;
using NUnit.Framework;
using TechTalk.SpecFlow;

namespace specflow.tests
{
    [Binding]
    public class MyFirstSteps
    {
        Calc c = new Calc();
        [Given(@"I have entered (.*) \+ (.*) into the calculator")]
        public void GivenIHaveEnteredIntoTheCalculator(int p0, int p1)
        {
            c.add(p0, p1);
        }

        [When(@"I press add")]
        public void WhenIPressAdd()
        {
        }

        [Then(@"the result should be (.*) on the screen")]
        public void ThenTheResultShouldBeOnTheScreen(int p0)
        {
            Assert.AreEqual(p0, c.answer);
        }

        internal class Calc
        {

            internal void add(int p0, int p1)
            {
                answer = p0 + p1;
            }

            public int answer { get; set; }
        }
    }
}

7) if you use ReSharper, you can go to tools -> options -> specflow -> general, and change the test run a tool to ReSharper

8) Click Resharper -> Unit tests -> Run All Tests From Solution (Ctrl+U, Y)
This doesn’t do much: right click the specflow file and select “run specflow scenarios”

Simple WPF input prompt

This is the simplest way to prompt a user for input from a WPF app:

var inputBox = Microsoft.VisualBasic.Interaction.InputBox("Prompt here",
                            "Title here",
                            "Default data",
                            -1, -1);
if (inputBox == "")
    return;

you have to add a reference to the Microsoft.VisualBasic assembly

 

WPF stringformat currency to pound (£)

default formatting of currencies etc happens to US, so to override that for GB / UK etc. :

<TextBlock Text="{Binding Path=CurrentPrice, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, StringFormat={}{0:c}, ConverterCulture=en-GB}" />

Creating MD5 hashes

example 1

public static string CreateMD5(string input)
{
    // Use input string to calculate MD5 hash
    MD5 md5 = System.Security.Cryptography.MD5.Create();
    byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
    byte[] hashBytes = md5.ComputeHash(inputBytes);

    // Convert the byte array to hexadecimal string
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < hashBytes.Length; i++)
    {
        sb.Append(hashBytes[i].ToString("X2"));
    }
    return sb.ToString();
}

example 2

// given, a password in a string
string password = @"1234abcd";

// byte array representation of that string
byte[] encodedPassword = new UTF8Encoding().GetBytes(password);

// need MD5 to calculate the hash
byte[] hash = ((HashAlgorithm) CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedPassword);

// string representation (similar to UNIX format)
string encoded = BitConverter.ToString(hash)
   // without dashes
   .Replace("-", string.Empty)
   // make lowercase
   .ToLower();

// encoded contains the hash you are wanting

and something similar:

Convert.ToBase64String

to convert 16 byte output of MD5 to a ~24 char string. A little bit better without reducing security. (j9JIbSY8HuT89/pwdC8jlw== as example)

example 4

public string CalculateMD5Hash(string input)
{
    // step 1, calculate MD5 hash from input
    MD5 md5 = System.Security.Cryptography.MD5.Create();
    byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
    byte[] hash = md5.ComputeHash(inputBytes);

    // step 2, convert byte array to hex string
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < hash.Length; i++)
    {
        sb.Append(hash[i].ToString("X2"));
    }
    return sb.ToString();
}

An example call:

string hash = CalculateMD5Hash("abcdefghijklmnopqrstuvwxyz");

…returns a string like this:    C3FCD3D76192E4007DFB496CCA67E13B

To make the hex string use lower-case letters instead of upper-case, replace the single line inside the for loop with this line:

sb.Append(hash[i].ToString("x2"));

The difference is the ToString method parameter.

Generic Random / Shuffle extention method for Lists etc.

This will allow you to shuffle and Ilist / List etc.

public static class RandomExtension
{
    private static Random rng = new Random();

    public static void Shuffle<T>(this IList<T> list)
    {
        int n = list.Count;
        while (n > 1)
        {
            n--;
            int k = rng.Next(n + 1);
            T value = list[k];
            list[k] = list[n];
            list[n] = value;
        }
    }
}

Another neat “trick” to do so is:

var shuffledcards = cards.OrderBy(a => Guid.NewGuid());

Solution: Using the ‘await’ operator with a lock statement

You won’t be able to lock a resource with async usage, using the lock keyword, due to possible deadlocks that can occur.

The following code will allow you to lock a resource for ASYNC usage:

//Use SemaphoreSlim.WaitAsync method.
System.Threading.SemaphoreSlim mySemaphoreSlim = new SemaphoreSlim(1);

public async Task NextTick()
{
	await mySemaphoreSlim.WaitAsync();
	try
	{
	    await SomeAsyncTaskHereUsingaResource();
	}
	finally
	{
	    mySemaphoreSlim.Release();
	}
}

 

Thread.Sleep vs async Task.Delay

Rather use Task.Delay, since it’s not blocking.

private async void button1_Click(object sender, EventArgs e)
{
    // Call the method that runs asynchronously.
    string result = await WaitAsynchronouslyAsync();

    // Call the method that runs synchronously.
    //string result = await WaitSynchronously ();

    // Display the result.
    textBox1.Text += result;
}

// The following method runs asynchronously. The UI thread is not
// blocked during the delay. You can move or resize the Form1 window 
// while Task.Delay is running.
public async Task<string> WaitAsynchronouslyAsync()
{
    await Task.Delay(10000);
    return "Finished";
}

// The following method runs synchronously, despite the use of async.
// You cannot move or resize the Form1 window while Thread.Sleep
// is running because the UI thread is blocked.
public async Task<string> WaitSynchronously()
{
    // Add a using directive for System.Threading.
    Thread.Sleep(10000);
    return "Finished";
}

Threading in C#

Delaying without blocking:
Thread.Sleep is a synchronous delay. If you want an asynchronous delay then use Task.Delay.

// Execution of the async method will continue one second later, but without blocking.
await Task.Delay(1000);

Task.Run vs Task.Factory.StartNew

 

Working with scheduled tasks:

TaskScheduler ui = TaskScheduler.FromCurrentSynchronizationContext();
var task = Task.Factory.StartNew(() =>
                                     {
                                         //do some work here
                                     },
                                 CancellationToken.None,
                                 TaskCreationOptions.None,
                                 ui);

task.ContinueWith(t => Thread.Sleep(1000), TaskScheduler.Default)
    .ContinueWith(t =>
                      {
                          //do more work here
                      }, ui);

Starting a Async task from a non-async method … such as static void Main():

private static void Main(string[] args)
{
	var myTask = GetIt();
	Task.WaitAll(myTask);
	List<Instrument> result = myTask.Result;
}
private static async Task<List<Instrument>> GetIt()
{
	return await Task.Delay(10000); // DoSomeAsyncWorkHere...
}