mvvm pattern in c#

This is an implementation in C# of the MVVM pattern as described before.

In this implementation I use the MVVM light toolkit, and some patterns I’ve already described: inversion of control and dependecy injection.

First, lets start with the model:

    public class NoteModel : ObservableObject
    {
        private string _note;
        public string Note
        {
            get { return _note; }
            set { Set(ref _note, value); }
        }

        private bool _isFinished;
        public bool IsFinished
        {
            get { return _isFinished; }
            set { Set(ref _isFinished, value); }
        }
    }

As you can see, when assigning to a property, I use a method provided my the MVVM light library: Set(). This method assigns the new value to the property, and fires the IPropertyChanged event, if the new value differs from the old. The IPropertyChanged event allows the view to refresh automatically.

Now, lets look at the view:

<Page DataContext="{Binding MainViewModel, Source={StaticResource Locator}}">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="10" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid Grid.Row="0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="Auto" />
            </Grid.ColumnDefinitions>
            <TextBox Text="{Binding NewNote, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
            <Button Command="{Binding AddNoteCommand}" >
                <Button.Content>
                    <SymbolIcon Symbol="Add" />
                </Button.Content>
            </Button>
        </Grid>
        <ListView ItemsSource="{Binding Notes}" />
    </Grid>
</Page>

I’ve removed all styling informations so everything is easier to understand. Take a look at DataContext: MainViewModel is a property of Locator, and this property is bound to the view. Take a look at the TextBox to see what this means: the Text property is filled with another {Binding NewNote...}, and NewNote is a property of the MainViewModel from above.

There are three types of binding in this example:

  • read binding: The ListView binds itself to the Notes property.
  • read & write in the Textbox: The Mode=TwoWay ensures, user input is written into the property automatically by XAML magic.
  • command binding: the Button binds itself to a property called AddNoteCommand, this property implements the ICommand interface. We’ll see about that.

I recommend you to take a look at this in Visual Studio, this helps you to understand all the other magic XAML stuff.

One last thing to check out: the {StaticResource Locator} part in the DataContext, you’ll find the definition the App.xaml:

<viewModels:ViewModelLocator x:Key="Locator" />

which leads to (in the Presentation project, ViewModels folder):

    public class ViewModelLocator : ViewModelLocatorBase
    {
        public ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
            SimpleIoc.Default.Register<IPlatformInformations, PlatformInformations>();
        }
    }

and this leads to (in the View project, ViewModels folder)

    public class ViewModelLocatorBase
    {
        public ViewModelLocatorBase()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
            SimpleIoc.Default.Register<IDataService, DataService>();
            SimpleIoc.Default.Register<MainViewModel>();
        }

        public MainViewModel MainViewModel => SimpleIoc.Default.GetInstance<MainViewModel>();
    }

Now there is the MainViewModel property!
The SimpleIoc part is an implementation of the Inversion of Control pattern, and provided by the Mvvm light library.

Now the ViewModel.
The constructor part:

    public class MainViewModel : ViewModelBase
    {
        private readonly IDataService _dataService;

        //inversion of control: SimpleIoc will contruct this object with the registered IDataService implementation
        public MainViewModel(IDataService dataService)
        {
            _dataService = dataService;

            _addNoteCommand = new RelayCommand(AddNote, () => CanAddNote);
            _deleteNoteCommand = new RelayCommand<NoteModel>(DeleteNote);

            if (IsInDesignMode)
            {
                Notes = new ObservableCollection<NoteModel>()
                {
                    new NoteModel()
                    {
                        Note = "Hello World",
                        IsFinished = false
                    }
                };
            }
            else
            {
                Initialize();
            }
        }

        private async void Initialize()
        {
            Notes = await _dataService.GetTasks();
        }

        private ObservableCollection<NoteModel> _notes;
        public ObservableCollection<NoteModel> Notes
        {
            get { return _notes; }
            set { Set(ref _notes, value); }
        }
    }

MainViewModel inherits from the ViewModelBase, a class provided by the MVVM light library. It has some nice tools integrated, for example the IsInDesignMode propery.

The ObservableCollection takes care of the necessary events firing, so the view can refresh itself if necessary.

The NewNote property is the one filled by the Textbox. Depending on the input, one can create a new note. So every time the value changes (Set returns true if the value has changed), the should reevaluate if a new note could be created.


        private string _newNote;
        public string NewNote
        {
            get { return _newNote; }
            set
            {
                if (Set(ref _newNote, value))
                    _addNoteCommand.RaiseCanExecuteChanged();
            }
        }

The commands:

        private readonly RelayCommand _addNoteCommand;
        public ICommand AddNoteCommand => _addNoteCommand;

        private bool CanAddNote => !string.IsNullOrEmpty(NewNote);

        private void AddNote()
        {
            Notes.Add(new NoteModel() { Note = NewNote });
            NewNote = "";
        }

        private readonly RelayCommand<NoteModel> _deleteNoteCommand;
        public ICommand DeleteNoteCommand => _deleteNoteCommand;

        private void DeleteNote(NoteModel model)
        {
            Notes.Remove(model);
        }

You can pass an object directly to the command, as done with the DeleteNoteCommand, with the CommandParameter property in the view.

Now start the application and play with it a little bit.
You’ll notice two things:

  • Without any code in view, the displayed items are always up to date. Even some basic animations already work
  • The logic is completely divided from the display, you may use the exact same ViewModel in an Android or iOS application

mvvm pattern

MVVM stands for Model-View-Viewmodel, a pattern used for example in applications & programs for windows.

ModelViewViewmodel

First, lets take a look at the three parts:

Model

a model is an object which stores data, and most of the time represents an object from the real world which is managed by the application. It is used to store data.

Viewmodel

Each page in your application has a Viewmodel associated with it. The Viewmodel provides all data to be displayed in the view and all commands which a user is able to execute

View

The View focuses solely on display.

Why use this pattern?

This pattern, similar to MVC, allows a loose coupling between Application Logic and View Logic. This has some numerous advantages:

  • extensibility & maintainability
  • if you have to redesign the application, you would not need to rewrite already working application logic, you only have to replace the view, and vice versa
  • easy for other developers to understand what you were doing

The full power of this pattern, and why I love it more than MVC, is shown the way it is supported in windows applications.

I’ve made an example in C#: github

I explain this example in detail here

scrum

Scrum ist ein agiler Entwicklungsprozess. Er setzt den Schwerpunkt auf direkte Kommunikation, ermöglich aber trotzdem gute Planung und Dokumentation.

Er setzt das Agile Manifesto um:

  • Individuen und Interaktionen haben Vorrang vor Prozessen und Werkzeugen
  • Funktionsfähige Produkte haben Vorrang vor ausgedehnter Dokumentation
  • Zusammenarbeit mit dem Kunden haben Vorrang vor Vertragsverhandlungen
  • Eingehen auf Änderungen haben Vorrang vor strikter Planverfolgung

Um dies zu erreichen werden zuerst alle Beteiligten in zwei Gruppen aufgeteilt: pigs & chickens.
So sind die pigs die, die unmittelbar zum Erfolg des Produktes beitragen (wie zum Beispiel die Programmierer), alle anderen sind Chickens (wie zum Beispiel die Geschäftsleitung).

Die Gruppenzuordnung bestimmt, wie häufig die entsprechende Person in den Entwicklungsprozess eingreiffen darf. So stehen die Pigs täglich untereinander im Austausch, die Chickens besprechen ihre Anliegen lediglich mit einer Ansprechsperson der Pigs.

pigs

Die pigs sind ein Team von bis maximal 10 Personen. Darin enthalten sind alle Experten, die zur Programmentwicklung benötigt werden.

Sie tauschen sich täglich untereinander über die Projektsfortschritte aus, und sind alle gleichberechtigt, verteilen die Aufgaben untereinander und helfen sich bei auftretenden Problemen. Das Team trägt gemeinsam die Verantwortung für den Projekterfolg.

Zwei Mitglieder des Teams haben zusätzlich spezielle Aufgaben (sie bleiben aber trotzdem gleichberechtigt):

  • der Scrum Master ist der Moderator der Meetings. Er ist damit dafür verantwortlich, dass der Scrum Prozess korrekt ausgeführt wird, und dass alle Impediments (Störfaktoren), die die Teameffizienz beeinträchtigen, aus der Welt geschafft werden.
  • der Produkt Owner priorisiert und bewertet die Arbeit des Teams, er ist die Ansprechsperson falls Fragen betreffend der konkreten Gestaltung des Programmes auftreten. Er geniesst sowohl das Vertrauen des Arbeitgebers als auch das des Teams.

Die Planung

Anforderungen des Projektes werden mittels User Stories und Use Cases formuliert.
User Stories: Als <USER> möchte ich zum
Use Cases: Der <USER> möchte <RESULTAT>

Die so erstellten Anforderungen werden im Product Backlog hinterlegt, und danach vom Arbeitsgeber evaluiert und priorisiert. Anhand dieser Vorgaben wird nun ein Sprint Backlog erstellt: die Vorgaben werden in individuelle Aufgaben unterteilt, deren Aufwand vom Team geschätzt wird.

Nun wird anhand der Entwicklungsgeschwindigkeit des Teams ein Project-Burndown Chart auf Iteration und Release Ebene erstellt.
Die Entwicklung kann beginnen.

Der Sprint

Ein Sprint ist etwa 30 Tage lang. Er ist ein in sich abgeschlossener Prozess an dessen Anfang die Planung des Sprints steht. Während dem Sprint selber werden die konkreten Aufgaben umgesetzt. Am Schluss jedes Sprintes ist eine funktionierende, in sich abgeschlossene Version des Programmes verfügbar.

Planung eines Sprints

Die derzeit wichtigsten Aufgaben werden ausgewählt, und es wird ein Sprint geplant, sodass alle ausgewählten Aufgaben fertig werden.

Wenn die Planung abgeschlossen wurde, wird ein Sprintvertrag zwischen dem Team und dem Arbeitgeber unterzeichnet. Der Vertrag garantiert dem Team, das keine Änderungen an den Anforderungen während dem Sprint gemacht werden. Im Gegenzug garantiert das Team die Ausführung der im Vertrag enthaltenen Aufgaben.

Es wird nun ein Sprint Burndown Char erstellt, der die Sprint Anforderungen visualisiert. Die x Achse ist die Zeit, die y Achse zeigt der geschätzte Arbeitsaufwand der noch zu erledigenden Arbeiten. Gestartet wird bei (0, max(y))

Entwicklungsprozess

Jeden Tag findet ein Daily Scrum statt, ein kurzes Meeting des Teams (5-10min). Jeder schildert knapp, was er gestern gemacht hat und was er heute machen wird. Er meldet sich hier, falls er sich mit jemandem aus dem Team koordinieren muss, oder falls er Hilfe bei einem Problem braucht.

Bei grossen Programmen findet wöchentlich ein Weekly Scrum statt: Ein Delegierter vom Team geht an das sogenannte Scrum of Scrums. Er fasst dort die Ergnisse seines Scrums zusammen und koordiniert mit andern Scrums falls nötig. Bei sehr grossen Programmen kann es sogar ein Meta Scrum geben. Jedes Scrum of Scrums entsendet einen Delegierten, dann geschieht im Prinzip das selbe wie im Weekly Scrum, einfach im grösseren Rahmen.

Ende des Sprints

Nach dem Ende des Sprints ist der y-Wert auf dem Sprint BurndownChart auf 0.

Das Ergebnis des Sprints wird Product Increment genannt, und ist eine funktionierende Version des Programmes. Der umgesetzte Funktionsumfang ist in sich abgeschlossen, und der Product Owner könnte das Programm nun veröffentlichen.

Der vergangene Sprint wird nun vom Team analysiert, positive und negative Aspekte werden gesammelt. Der Scrum Master wertet die Ergebnisse aus, und unternimmt Änderungen am Workflow falls nötig.

Im Sprint Review schliesslich werden die Ergebnisse des Sprints vom Arbeitgeber abgenommen.

Ist das Programm noch nicht fertig, ist nun der Zeitpunkt, um mit der Planung des nächsten Sprints zu beginnen.

Diese Zusammenfassung wurde aus Material von ti8m erstellt, und durch eigene Erfahrungen ergänzt.

encodings

Text has to be stored as zero’s and one’s (naturally…), and there are multiple standards to convert binary to text.
Lets have a quick overview:

ASCII
ASCII is both a standard and an encoding. The encoding called ASCII used to have only 7 bits. The standard called ASCII is widely used in other encoding as well, which basically means in all of those encoding certain letters have the same binary representation (with more leading 0s for 8 bits or even bigger encodings). For example the letter 1101110 in ASCII could be represented as 01101110 in an 8 bits encoding.

ISO 8859-1 or latin1
This is an encoding widely used for european languages. It is ASCII compatible, and uses 8 bits. Unfortunately, 8 bits are not enough to include arabic letters or even chinese one, which means there are a lot of similar ASCII compatible 8 bit encoding.

UTF-8, UTF-16, UTF-32,..
UTF is one of the solutions to the ISO encodings mess. It is also ASCII compatible, but does not have a fixed size. if you use UTF-8, every letter will have at least 8 bits, but less common ones as äöü can have 16 bits, 32 bits or even more. Now all characters there are can be used with the same encoding!

With this in mind, you can now understand what went wrong when looking at misinterpreted text:

latin1 vs utf8

left: correct; middle: UTF-8 interpreted as latin1; right: latin1 interpreted as UTF-8

php autoloading

In php, before you can use a class or method inside a file, you have to include the file first.

As it is cumbersome and error-prone to do this manually, you should use autoloading. You have to meet two requirements for this to work best:

  • Use a valid Objective Oriented approach: for example don’t globally define methods, but group similar methods in classes (example: define a public static function convertToInches in the class UnitConverter instead of just defining it globally)
  • Use namespaces: Use namespaces corresponding to the folder structure of your project. Learn about this at PSR-4

The autoloading itself is quite simple and saves you a lot of time. Place the code below at the entry point of your application.

/*** class loader ***/
function load_my_classes($class) {
    // project-specific namespace prefix
    $prefix = 'Vendor\\Project\\';

    // does the class use the namespace prefix?
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) === 0) {
		// get the relative class name
                $relative_class = substr($class, $len);
    
		// replace namespace separators with directory separators in the relative class name
		// append .php
		$file = __DIR__ . "/" . str_replace('\\', '/', $relative_class) . '.php';

		// if the file exists, require it
		if (file_exists($file)) {
			require $file;
		} else {    
			throw new Exception("Unable to load class: " . $class . " @ path: " . $file);
		}
	} else {
		//as the class uses an unknown namespace prefix, we ignore this one. An other autoloader can take care of this.
	}
});

/*** register the class loader ***/
spl_autoload_register('spl_autoload_register');

Now, whenever php has to use a class it does not know yet, it calls all methods registered by spl_autoload_register (in our case this is load_my_classes), until the class it included.
If it has called all registered methods, but still the class is not found, your application terminates (obviously).

If you’ve followed the naming conventions as specified in PSR-4, you can even take this a step further with composer. Besides other very useful things, composer does automatically generate the autoloading code. It’s worth giving it a try.

licenses

open source software should be distributed under licences. I’ve put together a short overview of the most important ones. and what they accomplish:

MIT: Do whatever you want with the code, but you cannot hold the author responsible for bugs

GNU GPL: Hardcore open-source: If you want to use a library which is licensed under GPL your application has to be open source too.

Creative Commons: A collection of licences, you can choose which flavour you want here. You might be able to guess from the name of the generated license what you can and what you can’t do.

l;drLegal comes in handy if you want to know more about other licences.

I recommend you use the MIT license: You basically do not restrict anyone from using my code, but will not face legal consequences of any kind if your code is broken.

But why should I care?

In your license you can specify how one may use your code (if commercially or not, if allowed to modify it etc).

If your project is open source and free, you probably won’t have any difficulties with licences. However, if you intend to sell it, or keep your code private, you need to review them carefully: Some licences may restrict using code in commercial or non open source projects.

Personally, I think it’s a waste of time clearing up legal issues to use already written code, rather than spending this time on developing. The reason I make all of my code open source is than others can reuse the code and do not need to write the exact same thing I’ve already did. I think this should generally be the focus of open source; reducing the workload of all programmers in general.

mvc pattern in php

This is an implementation in php of the MVC pattern as described before.

First, we need to ensure all requests go to one file only, the index.php file. There we will construct our controller, and run the application. We do this by placing a correctly configured .htaccess file in the root directory of our webpage. I’ve commented out the commands, feel free to take a look.

The actual code in the index.php file is quite simple:

// (skipped code for including files)

//construct the controller
$controller = new HomeController($_SERVER["REQUEST_URI"]);
//execute the application
echo $controller->execute();

That was easy. Let’s take a look at our controller:

class HomeController {
	private $params;
	
	/**
	 * HomeController constructor.
	 *
	 * @param $params : the request URL
	 */
	public function __construct($params) {
		$this->params = $params;
	}
	
	/**
	 * execute the application
	 *
	 * @return string
	 */
	public function execute() {
		if ($this->params == "/") {
			$view = new HomeView("hallo welt!");
			return $view->renderHome();
		}
		else {
			if ($this->params == "/famoser") {
				$view = new HomeView();
				$person = new PersonModel("famoser", "01.01.1990");
				return $view->renderPerson($person);
			}
			else {
				if ($this->params == "/famoser/multiple") {
					$view = new HomeView();
					$persons = array();
					for ($i = 0; $i &amp;amp;amp;lt; 5; $i++) $persons[] = new PersonModel("famoser (" . $i . ")", "01.01.1990"); return $view->renderMultiplePersons($persons);
				}
				else {
					$view = new HomeView("not found");
					$view->addKeyValue("url", $this->params);
					return $view->renderError();
				}
			}
		}
	}
}

As you can see, the controller checks if the $params variable is a valid url. If it is, it contructs an object called the HomeView, and passes models and text to it. Then it lets the HomeView render the templates, and returns the received data.

Let take a look at a simplified HomeView (full code at github):

/**
* a simplyfied HomeView, I've removed the constructor and other for this example irrelevant code
*/
class HomeView {
	private $message;
	private $keyValues;

	public function getMessage() {
		return $this->message;
	}
	
	/**
	 * use this function to pass simple data to the view
	 */
	public function addKeyValue($key, $value) {
		$this->keyValues[$key] = $value;
	}
	
	/**
	 * retrieves values added by addKeyValue from the controller
	 */
	public function getValue($key) {
		return $this->keyValues[$key];
	}
	
	/**
	 * render the home template
	 */
	public function renderHome() {
		return $this->includeFile("index");
	}
	
	/**
	 * render the person template
	 */
	public function renderPerson(PersonModel $person) {
		$this->person = $person;
		return $this->includeFile("person");
	}

	/**
	 * render multiple persons
	 */
	public function renderMultiplePersons(array $persons) {
		$result = "";
		foreach ($persons as $person) {
			$this->person = $person;
			$result .= "

" . $this->includeFile("person") . "

";
		}
		return $result;
	}
	
	/**
	 * renders a file, writes the output it produces into a variable and returns that.
	 */
	private function includeFile($fileName) {
                //shorted
                include $filename;

	}
}

As you can see, the HomeView basically serves as a container for all data it needs to display. As the controller calls a function as renderHome, it loads a specific template and returns the rendered content to the controller.
Lastly, lets take a look at a template file:

if ($this instanceof HomeView) {
	echo $this->getMessage();
}

As I’m including the file from the HomeView, the context in this file ($this) is still the view. Now I can call the methods from the view to retrieve the data I have to render to human readable information.

What advantages has this approach?

  • reuse of templates is made easy: from one template, I can include others by calling functions provided by the view object (for example renderMultiplePersons)
  • a clear separation of view & logic: the controller does not care how the data he provides is displayed, he simply constructs the view with the appropriate data, and the view does not care where the data comes from, and just loads the appropriate templates.

mvc pattern

MVC stands for Model-View-Controller, a pattern widely used in web application development.
First, lets take a look at the three parts:

ModelViewController

Controller

For each part of your application you use a different controller. It executes a different set of instructions based on the request, manages the models, and constructs the view.

Typically, after a request is made, following steps are undertaken by the controller:

  • check if the request is valid, else return an error message
  • update data if the request wishes to do so
  • retrieve all data needed in the view
  • construct a view object, and let it render the view

Model

a model is an object which stores data, and most of the time represents an object from the real world which is managed by the application. It is the primary form of communication between your views and your controllers.

View

the view is responsible for displaying information received from the controller such as models.

Why use this pattern?

This pattern allows a loose coupling between Application Logic and View Logic. This has some numerous advantages:

  • extensibility & maintainability
  • if you have to redesign the application, you would not need to rewrite already working application logic, you only have to replace the view, and vice versa
  • easy for other developers to understand what you were doing

I’ve made an example in php: github

I explain this example in detail here

repository pattern

This pattern is an application of the separation of concerns principle. It basically separates the consumer from the supplier of data.

For the consumer of an RSS feed it is irrelevant if the feed is read out from the storage, or downloaded from the internet. This is where the Repository Pattern jumps into action; it provides a simple API for the consumer, and takes care of resolving the data from the best source available.

A small example (c#):

internal class RssRepository
{
    public List<RssItem> GetRssItems()
    {
        if (DeviceHelper.HasInternet)
        {
            return RssHelper.DownloadFeedItems();
        }
        else
        {
            return StorageHelper.RetrieveCachedFeedItems();
        }
    }
}

KISS

Keep It Simple, Stupid!
Do not write complex code.

Simplify your code by following principles as DRYseparation of concerns and single responsibility principle. Everyone who takes a look at your code should be able to understand what it does as fast as possible. If one of your methods is very long (30 lines and up), or needs comments to be easy human readable you are probably writing overcomplicated code. Try to further split up your logic, divide it into smaller, easier bits of code.

Some signs your method may be overcomplicated:

  • you cannot name it in a way so you do not need additional comments to explain its functionality
  • it is longer than 30 lines
  • it is split up into various parts which all deal with a different part of the problem (read out file, process its contents, append lines, save it again)
  • you need comments to explain its functionality

Of course, if you need to implement an encryption or a compression algorithm, the code for this specific task may be rather complex. Still, for any other part of your application KISS is applicable.