Posts

Applying a genetic algorithm to the Linear Assignment Problem

Image
Some sample C# code on how a genetic algorithm can be applied to the linear assignment problem. This problem can be efficiently solved using the Hungarian algorithm, but I wanted to demonstrate how the genetic algorithm can produce an optimal solution too. This example is implemented as a simple console application using code developed in Microsoft Visual Studio. To help break down the problem a little, I develop a number of classes for the purposes of encoding potential solutions as chromosomes, maintaining a population of chromosome and applying genetic operators to the population of solutions in the form of crossover, mutation and selection. Code samples as follows: Program.cs The main program loop: [code language="csharp"] using System; namespace LinearAssignmentProblem { class Program { static void Main(string[] args) { var tasks = 5; var popSize = 100; var rnd = new Random(); // Do we seek to maxi...

Handling changes to observable collection values as events in C#

Image
From StackOverflow searches, I see that there are two possible ways: use an implementation of a TrulyObservableCollection; or use a Binding List. StackOverflow resource: https://stackoverflow.com/questions/1427471/observablecollection-not-noticing-when-item-in-it-changes-even-with-inotifyprop In your console application first implement a property that implements INotifyPropertyChanged for you: ViewModelBase.cs [code language="csharp"] using System.ComponentModel; namespace ObservableCollection { public class ViewModelBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } [/code] Code samples as follows: 1. TrulyObservableCollection [code language="csharp"] using System; using System.Collections.Generic...

How to send an e-mail via Google SMTP using C#

Image
First things first, some useful StackOverflow links: https://stackoverflow.com/questions/9201239/send-e-mail-via-smtp-using-c-sharp https://stackoverflow.com/questions/17462628/the-server-response-was-5-7-0-must-issue-a-starttls-command-first-i16sm1806350 To demonstrate how this is done I first create a new Visual Studio project: Some example code for sending an email via a Google email account (smtp.goolgle.com) - obviously replace this with email / credentials of your own... I put the code within a try-catch block in order to capture any errors that may occur while attempting this. [code language="csharp"] using System; using System.Net; using System.Net.Mail; namespace EmailSmtp { class Program { static void Main(string[] args) { try { // Credentials var credentials = new NetworkCredential("someEmail@gmail.com", "somePassword"); // Mail message var ...

How to enable SSL / Https in a Visual Studio Web Api project

Image
useful link is here: https://dotnetcodr.com/2015/09/18/how-to-enable-ssl-for-a-net-project-in-visual-studio/ Create a new Web Api project in Visual Studio: Select/click on the Web API project name in the solution explorer, and then click on the Properties tab. Set 'SSL Enabled' to true: The same properties window will also show the HTTPS url for the application. In the above example it’s https://localhost:44314/. Copy that URL and go to the project properties window. Navigate to the Web tab and override the Project Url property with the https address that you copied: Build and run the application. The likelihood is that a message appears in the browser saying that the localhost address is not trusted, you can continue to the website at your own risk. Here’s a Firefox example: The problem is that the certificate automatically installed by Visual Studio is untrusted. In the search programs and files, type 'mmc' (Microsoft Management Console):...

Creating a zip archive in C#

Image
StackOverflow link where I got this technique from is here: https://stackoverflow.com/questions/2454956/create-normal-zip-file-programmatically/ First create a new console application: Add references to System.IO.Compression and System.IO.Compression.FileSystem: Select a folder containing a set of files that you would like to archive. You could make this more sophisticated and create your own list of file paths, but I'm just keeping things simple for now: Here is the sample code I use to test the .NET compression library Program.cs [code language="csharp"] using System.IO; using System.IO.Compression; namespace ZipArchive { class Program { static void Main(string[] args) { var zipFile = @"C:\data\myzip.zip"; var files = Directory.GetFiles(@"c:\data"); using (var archive = ZipFile.Open(zipFile, ZipArchiveMode.Create)) { foreach (var fPath in files) ...

How to serialize and deserialize Json objects in C#

Image
A simple console app to demonstrate this. After creating your Visual Studio application, console or otherwise, make sure the System.Web.Extension reference is added: Suppose we have an object we wish to serialize/deserialize, such as an instance of this class: [code language="csharp"] public class Shared { public List<string> Emails { get; set; } public string Message { get; set; } public List<string> Ids { get; set; } } [/code] One possible way is to make use of the JavaScriptSerializer class. By the way, here is a useful StackOverflow link if you are having trouble finding JavaScriptSerializer in .NET 4.0: https://stackoverflow.com/questions/7000811/cannot-find-javascriptserializer-in-net-4-0 So that in this example, we not only instantiate our example class for serialization using JavaScriptSerializer, but deserialize it back into the original object as well: Console application code listing as follows: Program.cs [code language...

How to encrypt basic authentication credentials in a Web Api application

Image
This post shows you how to handle encrypted user credentials in a Web Api application and offer further security by enforcing https for all REST api calls. Step 1: Create a new Web Api application: This is our web service that will need to authenticate encrypted user credentials. Step 2: Add a class for handling encryption and decryption Crypto.cs [code language="csharp"] using System; using System.Linq; using System.Security.Cryptography; using System.Text; namespace WebApiEncrypt.Models { public static class Crypto { private const string PrivateKey = "<RSAKeyValue><Modulus>s6lpjspk+3o2GOK5TM7JySARhhxE5gB96e9XLSSRuWY2W9F951MfistKRzVtg0cjJTdSk5mnWAVHLfKOEqp8PszpJx9z4IaRCwQ937KJmn2/2VyjcUsCsor+fdbIHOiJpaxBlsuI9N++4MgF/jb0tOVudiUutDqqDut7rhrB/oc=</Modulus><Exponent>AQAB</Exponent><P>3J2+VWMVWcuLjjnLULe5TmSN7ts0n/TPJqe+bg9avuewu1rDsz+OBfP66/+rpYMs5+JolDceZSiOT+ACW2Neuw==</P><Q>0Ho...