EratoWPF – Sieve of Eratosthenes (WPF and MVVM)

Hello!
I have just finished another simple app. This time it’s an application to look for prime numbers. The app is again simple but the reason for that is I wanted to make an approach to something new. This time it is MVVM design pattern.
What is MVVM? It is a software design pattern which goal is to separate user interface form application’s logic and data model.
M – model – data source
V – view – user interface
VM – view model – logic and a ‘go-between’ model and view
Use of MVVM pattern allows for a project to be simultaneously developed by a graphic designer and a coder as the UI does not (and should not) require any code-behind. Another advantage is that the whole logic and data-model can be quickly ported to new UI. Microsoft emphasises use of Blend for Visual Studio which is a graphic-design tool for creating (not only, but also) WPF user interfaces to design UIs. In this case I didn’t follow that advice. XAML editor in Visual Studio is sufficient for me.

So, how the separation is achieved? In EratoWPF case, first  I created a model which is PrimeNumbers class in PrimeNumbers.cs file. To be sure that it is working as it should I also created another project called PrimeNumbersSieveTester which is a small console application that tests the class.
Next, I started building the view in XAML with input text boxes and some buttons to run the algorithm or clear inputs.
Finally, I started building the view model. It represents the content of the UI. The view model also privately instantiates the model. The UI will not have access to it.

Binding
To allow the UI use (to display and/or update) properties from view model we use data binding. To achieve that first we need to set data-context for the UI.

The XAML code above will create an object viewModel which is an instance of ViewModel class. The code below will set main grid data-context to viewModel.

Now, to bind a property from viewModel to a control in WPF user interfaces:

The code above binds Text property of a text box to InputRangeStart property in viewModel and IsEnabled to InputsEnabled. Modes specify type of binding. OneWay allows only to dispaly data from viewModelTwoWay allows also to update data in viewModel.
This also requires a view model to implement INotifyPropertChanged. It’s quite simple:

That creates an event handler which is fired every time a property is changed. To set up a property to fire that event it is required to invoke OnPropertyChanged(“PropertyName”); method in a set accessor of this property.

Commands
As it was written earlier in this post, an application designed according to MVVM pattern should not have any code-behind. Therefore, it is required to use commands instead of events.
First, we need to create command class which implements ICommand interface:

That is basic implementation of a command. However, if a command operates on view model instance it is advisable to add private and readonly field for view model and create a constructor that sets it to viewModel defined in XAML.

After that, we need to create an instance of this command in our view model to allow it to be bound to a control in the UI.

Now, to bind the command to a control:

And that’s pretty much it. This is very basic introduction to MVVM, but good enough for a start. There are other aspects of MVVM (such as converters or dependency properties any many many more that I am not aware of at the moment) but I am sure that I’ll come to that as well. As they say: Rome wasn’t build in a day!
Good luck!

Source code: https://github.com/mickaj/EratoWPF
Readme: https://mkajzer.pl/?page_id=200
Installer: https://mkajzer.pl/download/EratoWPF/EratoWPF_installer.zip

Recommended reading (in Polish): “MVVM i XAML w Visual Studio 2015”, Jacek Matulewski, published by Helion, 2016, ISBN: 978-83-283-2867-9
http://helion.pl/ksiazki/mvvm-i-xaml-w-visual-studio-2015-jacek-matulewski,xamlmv.htm

Interfaces

Hello!
Today I’m going to write a word or two about interfaces. So, what are they? In simple words an interface is a statement that a class has certain features defined by the interface. It says that a class is equipped in certain capabilities. Here’s an abstract example. Do you recall pre-smartphones era, circa 2000? Cell phones that time had two primary functions: voice call and text messaging. But some of the fancier models had colour screen, photo camera etc. To reflect that we would say that this fancy phone is of Phone class and implement IPhotoCamera interface.
Let’s create simple Phone class with methods to make a call and send text message:

And a simplest interface I can possibly imagine:

There are few things you need to know about interfaces:
1) Interfaces can consist only of methods, properties, events or indexers
2) Implementation of methods takes place in actual class which inherits the interface. Signature of implementation must be complement with its definition in interface.
3) Interfaces can be generic.
4) Definition of a property interface includes only get; and/or set; accessor keyword without actual implementation.
5) Naming convention is to add capital ‘I’ prefix before the name of an interface.
Let’s get back to our example. Our IPhotoCamera interface contains definition of one property and one method. If a class inherits this interface it must implement what’s defined in the interface.

Now, let’s move back to our main. We can test our two classes by simply invoking methods that are available. But, there’s no use for interfaces so far. This could be easily achieved without it. Class HiEndPhone inherits after CellPhone class and could have its unique method specified without use of interfaces. But using interfaces allows us to write method specifically for objects that implement an interface that will access only what was specified in interface declaration.

But all this above is not the most important thing about interfaces. In C# a class can inherit from only one class. However, this limitation does not include interfaces. You can implement in your class as many interfaces as you want. That’s the most important feature in the concept of interfaces.
To sum things up: an interface is an indication of certain capabilities that a class must implement and actually implement; a class can implement multiple interfaces; naming convention for interfaces is to precede its actual name with capital ‘I’ letter.
Regards, Michal

MSDN: https://msdn.microsoft.com/en-us/library/ms173156.aspx?f=255&MSPPError=-2147217396

Delegates, Lambda expressions, callbacks and events

Shalom!
Since my completion of the course (read here) I have turned my focus onto delegates and events. All in order to fully comprehend the MVVM pattern. This post will be mainly about delegates and events, but I will also write a bit some of the related topics (Lambda expressions, callbacks and Func, Action and Predicate delegates).

Delegates
In short words delegates are types that can hold a reference to methods. Those methods must be consistent with delegate type signature. They can hold a named methods, anonymous methods and Lambda expressions. Interesting feature of a delegate is that its instance can hold references to more than one method which can be added/removed simply by using + or – operator. Here’s an example of delegate signature:

To create an instance of a delegate:

To invoke methods referenced in the delegate simply invoke it exactly the same way as regular methods or use Invoke(); method.

Delegate can hold references to more than one method. These methods will be invoked in the same order as they were added. If a delegate returns a value it will return value from the very last method in its invocation list.


Anonymous methods and Lambda expressions
Anonymous method is a method which is declared and its body is defined when assigning it to a delegate. Lambda expressions (introduced in C# version 3.0) are more or less the same as anonymous methods but with simplified syntax.

Lambda expressions use ‘=>‘ operator. It can be understood as ‘becomes’ or ‘goes to’. In other words what’s before the operator is inputs and what’s after the operator it output. Input and output has to be consistent with delegate type to which you want to assign the expression. If there is only one instruction after the operator and the delegate returns a value it is not necessary to use ‘return‘ keyword.

Func, Action, Predicate
These are ‘built-in’ generic delegate types introduced in C# 3.0. Generic parameters represents type of arguments and type of returned value (if any).

One of the purpose where you can use predicates is filtering a collection. For example, you can use RemoveAll(Predicate<T> match); method to remove from a list all elements that satisfy the condition.

Callbacks
While doing research about delegates it was often claimed that main purpose of delegates is allowing communication between two classes. Original meaning of ‘delegate’ noun is someone who is sent to other party with a message. And this is how delegates should also be comprehended in C# and programming.
Imagine that there is a class with a method that takes a significant amount of time to execute. To keep application responsive it would be worth to have some feedback about the status or progress of this time-costly method. It is possible to achieve via callbacks.
Here’s a Calculation class with a method simulating some lengthy calculations:

This class defines CallBack delegate type which takes one integer argument and doesn’t return any value. This delegate is also an argument in our Process method that want’s to send feedback to another class which is achieved by invoking that argument somewhere in the method.
UI for this example is a WPF window. It consists of a textbox where user gives number of cycles that Process method will run and a button that executes that method. There is also a numeric indicator of current cycle and a progress bar. Those two controls receive feedback from Process method. There is also a text box to witness that the UI is responsive while the Process method is runnind. Here’s XAML code:

Code-behind the main window consists of Click event for a button that starts the process and UpdateUI method.

Process method is started as a new Task to keep the UI responsive. UpdateUI method must have signature consistent with CallBack delegate defined in Calculation class as this method is used as an argument in Process method.

Events
Concept of events enables a programmer to use a kind of notification system between objects. To depicts that I prepared small program that imitates a wallet and adding money to it. Here’s listing of Wallet class:

First of all it has a delegate GotSomeMoney declared that defines event handler signature. Event handler is a method that is executed when an event occurs. It takes two parameters: object sender (which is an object that fires the event) and EventArgs e  (object of an EventArgs class that holds argument that you want to pass with the event).
At the very end of the file above I declared a new class MoneyEventArgs which is derived form EventArgs class. This class has two properties that will be passed with the event.
Having these two parameters in event handler is to follow the .NET guidelines. It is not necessary but if you take a look at all the events for all of the controls (in WinForms and in WPF as well) you’ll see that they follow the same guidelines.
Now, if you analyse setter for Money property in Wallet class you will notice that FireEvent method is executed in some particular circumstances. This method takes one integer argument. Now, if we move on the the code of this method that it creates new instance of MoneyEventArgs class and assign certain values to its properties. Then, it checks if there are any subscriber for the OnGotSomeMoney event and if affirmative it fires the event with this as an object argument and that newly created instance of MoneyEventArgs class.
Now, let’s move to the UI. It has a text box to provide owner’s name and a button that initializes new instance of Wallet class. It also has a counter that displays content of the wallet and buttons that allows a user to add some money. The are disabled until the initialize button is clicked. Here’s XAML code:

This XAML code also defines myWallet instance of Wallet class. It all happens in <Window.Resources>. This instance will be available also in code-behind.
Now, let’s take a look at code-behind:

Code-behind has ThisWallet_OnGotSomeMoney method which signature is consistent with GotSomeMoney delegate in Wallet class. This method will be assigned as a subscriber to OnGotSomeMoney event of thisWallet instance by clicking Initialize button. Note, that this assignment is achieved by using ‘+=’ operator. To avoid clearing all subscribes it is not possible to use ‘=’ operator event. You can only subscribe to event by using ‘+=’ or unsubscribe by using ‘-=’ operator.
ThisWallet_OnGotSomeMoney method takes some values from sender and MoneyEventArgs and creates some strings that will be displayed in a message box when the event occurs.

Understanding all of these concepts required to be quite focused and multiple reading or watching of the sources I had available. If I were to recommend something that helps to understand these aspects of programming here are some links:
Jesse Dietrichson: https://www.youtube.com/channel/UCiA3tURI8dwCOUzCeM90c2g
https://www.youtube.com/watch?v=8e2GEFNctwQ&t=1466s

.NET Interview Preparation Videos
https://www.youtube.com/channel/UCHI5xgQujSyqz_UyKdLFaqw
https://www.youtube.com/watch?v=ifbYA8hyvjc&t=416s

All of the code presented in this post can be found here:
https://github.com/mickaj/DelegatesLambda
Feel free to test it!

That’s it for today. Next, I will post something about interfaces. Hopefully, shortly…
Regards, Michal

.NET programming basic course

Hi!
As I had mentioned in one of my previous posts I attended a programming course dedicated for C#/.NET beginners. The course was organised by polish IT leader Comarch (at the end of this post you will find a link to the course on their website).
I have to say that most of the topics presented during the course were nothing new to me. But, it’s completely different than learning on your own no matter if it’s from a book or YouTube course or lecture. Having that possibility to ask questions and get instant answer is the biggest advantage. Sometimes, you think that you might have not understood something you ask a question to clarify and you get an affirmative answer –  that’s a confidence boost. That gives you that feeling that you’re on the right track. You can’t get that any other way than face-to-face learning experience.
What’s more that improves the quality of the course is the fact that it was mostly all time practice. The theory part was more of a brief introduction to the topic than a lecture. All important things were presented with an example and tested by students ourselves.
After completing the course I have one advice for anyone who wants to get into programming: be extremely careful when learning online. Some of the learning materials are not prepared with that mindset that someone who’s going to learn is absolute beginner. They tend to go shortcuts, don’t pay attention to details which denies learners to fully comprehend the knowledge. And sometimes they teach bad habits (for instance I have not heard before the course about the ‘private field, public property’ convention).
What I learnt during the course and I find most important for me at this stage is deeper insight into class inheritance and polymorphism.
I am pretty happy with the course but still there were some disappointments. I was really hoping to get some more details about such aspects as interfaces, data-binding and MVVM model. We talked a bit about interfaces, the tutor showed us an example of data-binding and he said few words about MVVM. But I was simply hoping for more.
Generally, I find the course much beneficial for me and I will surely continue with courses from Comarch. The course ended with issuing a certificate. That’s my first 🙂
Thanks, Michal

Programowanie .NET – kurs podstawowy (Comarch)

RomanDecimalConverter

Greetings,
I have finished another quick project. The plan for this was to introduce myself to WPF and XAML. My general thoughts are that despite that WinForms seems to be easier and quicker way to design a Windows application I find WPF more organised and more controllable that WinForms. I designed all windows for this application using only XAML editor (not the visual one) in Visual Studio. That gives better understanding what is happening with the window.

The application itself is quite simple: it converts Roman numbers to Decimal, and the other way around. Algorithms of conversion are quite simple so I won’t describe them here (they can be found in readme file, or by analysing the code).

That was quite a nice way to leap into WPF. Next week, I’m going to three-day basics of .NET programming course which I hope will give me more insight to WPF and MVVM model (which, I’ve deducted from some of the YouTube lectures about WPF, is essential for writing a well-organised and maintainable applications).

Stay tuned!

ClickOnce installer (*.zip)
Source code (*.zip)
Readme file (*.txt)

Localising your application

Hello!
Some time ago, while working on an abandoned project (which, I have to admit honestly, turned out to be too laborious and complicated for me at that point) I had worked out a method to localise the program using XML files. That worked perfectly okay but only recently I have that there are way easiest methods to achieve that.
Let’s start with XML method. Available languages have a unique file with all strings stored in. The file is organised as follows:

As you can see each window has a specific section in XML file, and only this section will be loaded when a window is displayed. Every window has a method which loads all related strings:

Drawbacks of this method are clearly visible: you have to write a method which will load all strings from XML file. And you have to be extremely careful not to omit any text you want to display. It worked but not effectively at all.

There is other much simpler method which I found at AltControlDelete.pl. It uses resource files and System.Globalization. General idea is that you create individual *.resx file for each language: Lang.resx for default (English) language and Lang.xx-XX.resx, where xx-XX is the name of a culture (for instance, pl-PL for Polish). What’s important is that access modifier for those files must be set as public as shown below.

lang_resx
These files must be stored in one folder (let say “Languages”). Now, you need to include them in your source code and you’re ready to use these strings in your code:

To use it with XAML you need to add appropriate namespace to Window element in XAML file:

Now, to switch between languages you need to change Culture in your process:

Of course, you need to build your app in a way that user has the possibility to switch between languages as he intends.

That’s about it. The method with *.resx files is much simpler and most of all quicker and to some point less prone to omissions and mistakes. Of course, there are other methods (for instance, Mulitilingual app toolkit  from Microsoft) but this one seems to me that is easy enough and does not require any add-on or third-party software other than Visual Studio).

This post is based on articles available at www.altcontroldelete.pl by Jerzy Piechowiak.

WPF TUTORIAL – APLIKACJE WIELOJĘZYCZNE
TWORZENIE APLIKACJI WIELOJĘZYCZNYCH Z C# I ASP.NET W VISUAL STUDIO

 

MakeNoMistakes 1.1

Greetings!

I have just finished the application introduced in previous post. To remind what the application is about: it is an implementation of a classic game Minesweeper. My addition to the idea is that once you click on a mine you have one chance to disarm the mine by solving small equation (addition or subtraction).

Here are links to ClickOnce installer and source code. As usual the code was written in MS Visual Studio.

ClickOnce installer (*.ZIP)
Source code (*.ZIP)

One note before you try it out – don’t mind the graphics. I am hopeless at drawings.

Enjoy!

More on dictionaries

Shalom!

Sometime ago I mentioned usage dictionaries to workaround lack of possibility to use variable which name is stored in another variable. It is useful trick (at least for me – beginner) but dictionaries may be employed to perform multitude of tasks. So, to preserve my newly gained skills I present most important aspects of dictionaries.

The main idea behind dictionaries is to have a structure that holds certain values tied to certain keys. It may be depicted as 1-D array which instead of numeric indexes uses any type of variables as example below shows:

stock

INITIALISING A DICTIONARY

Dictionary is a collection. To use it you need to include appropriate namespace: System.Collections.Generic. Definition of a dictionary must specify three things: its name, type of key and type of stored value:

The example below initialises empty dictionary – it was created using a constructor that doesn’t take any arguments. However, this is not the only option. Visual Studio suggest six different variations of constructor. You can set initial size of a dictionary, method of comparing keys – I am not going to describe each constructor as Visual Studio does that sufficiently. I just mention that it is possible to initialise a dictionary using a constructor that takes existing dictionary as an argument. Such action will copy of an argument dictionary to the newly created one. I find it most useful.

 

OPERATIONS INSIDE DICTIONARY

Adding new element
It is that simple that I was tempted to omit that, but for sake of conscientiousness here’s a quick example. To add a new element to a dictionary you need to use Add method and provide key and value of new element:


Accessing/modifying value of an element

Again, it’s very simple. Code below illustrates that:


Looping through whole dictionary
It is no secret that to run through whole dictionary you have to use foreach loop. To correctly design that loop you need to use KeyValuePair as an iterator. It is also necessary to provide types of keys and values accordingly to dictionary we want to loop through.

Other useful methods for dictionaries
Here are some other methods that you may find useful. These are quite simple operations so their description will be presented together with the code.

 

EXAMPLE OF USAGE

So, now we have basic comprehension of what dictionaries are and how to use them. I am sure you will easily find a task that which can utilise dictionaries. But to provide an example I’ll show one possible implementation.
Currently, I am writing an application which will allow user to switch between different languages (dictionaries, languages – that obvious, isn’t it?). The plan is to store language data in an XML file and load its content to a dictionary. Then, instead of hard-coding every word that is visible for end-user the program will display data stored in the dictionary. Here’s a class that allows that:

The class is static – there’s no need to create various instances as only one language can be displayed. The class has only one property – LoadedLanguage – a dictionary that uses string key to store string values.
There are two methods: method ExistLanguge(string) checks if a language file chosen by user exists. If it does the method returns true and the program continues. If the file doesn’t exist the program displays a warning message. Additionally, if the chosen language is English and its XML file doesn’t exist the program terminates as English is default language.
Another method is used to load specified language to the dictionary. As earlier said the language data is stored in the XML file. That XML file is divided into sections depending on which form it relates to.

Method LoadLanguage(string, string) takes as arguments language to load and section of XML file to load. Then it loops through the XML file and creates key/value pairs in the dictionary according to nodes present between specified area. Then these pairs are used in various parts of the program to display labels in specified language.

So, that quick guide through dictionaries would be it for today. Enjoy!

Examples (*.cs)