Posts

Showing posts from June, 2018

How to serialize and deserialize objects using NewtonSoft JSON

Image
Some instructions on how to use Newtonsoft JSON to serialize and deserialize your objects in C# Step 1: Create a new Visual Studio project Just a simple console application will do: Step 2: Install Newtonsoft Json using Nuget Available at the NuGet site: https://www.nuget.org/packages/newtonsoft.json/ Enter the command to install Newtonsoft Json in the Visual Studio package manager console: [code language="xml"] Install-Package Newtonsoft.Json -Version 11.0.2 [/code] Step 3. Create an example class to serialize/deserialize [code language="csharp"] public class DataStructure { public string Name { get; set; } public List<int> Identifiers { get; set; } } [/code] Step 4. Create methods to serialize and deserialize [code language="csharp"] public static void Serialize(object obj) { var serializer = new JsonSerializer(); using (var sw = new StreamWriter(filePath)) usi...

Refactoring conditional statements using polymorphism in C#

Image
Suppose you have a conditional statement such as a switch or if-else that performs various actions depending on an object's type: It is often beneficial to try to avoid lengthy switch/if-else constructions. This post demonstrates how these can be refactored using polymorphism. Consider the following Employee class which uses a conditional statement to return a salary depending on employee types Apprentice, Developer, Manager: [code language="csharp"] public class Employee { public int GetSalary(EmployeeType type) { var salary = 0; switch (type) { case EmployeeType.Apprentice: salary = 10000; break; case EmployeeType.Developer: salary = 20000; break; case EmployeeType.Manager: salary = 30000; break; } return salary; } } [/code] Employee type enumerations as follow...

Using the Appccelerate state machine to navigate between WPF XAML views

Image
A post describing how to utilise Appccelerate as a means of employing a state machine in your MVVM / WPF application. Implementing state machines using the state pattern can lead to complicated code. A state machine software component that allows us to implement a state machine as a single class is a significant step towards maintaining clean code, reducing complexity and effort. Hopefully this article demonstrates this. This example seeks to utilise Appccelerate state machine as a means of navigating between XAML views in a WPF application employing the MVVM (Model View ViewModel) pattern. In our example we wish to be able to navigate between three WPF screens (user controls) in the manner described by the following state diagram: Step 1: Create a new WPF application Step 2: Create the event handling classes RelayCommand.cs [code language="csharp"] using System; using System.Windows.Input; public class RelayCommand<T> : ICommand { private re...